xref: /freebsd-14.2/sys/cam/ctl/ctl.c (revision c8d5eda2)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
5  * Copyright (c) 2012 The FreeBSD Foundation
6  * Copyright (c) 2014-2017 Alexander Motin <[email protected]>
7  * Copyright (c) 2017 Jakub Wojciech Klama <[email protected]>
8  * Copyright (c) 2018 Marcelo Araujo <[email protected]>
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 <[email protected]>
45  */
46 
47 #include <sys/cdefs.h>
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/ctype.h>
51 #include <sys/kernel.h>
52 #include <sys/types.h>
53 #include <sys/kthread.h>
54 #include <sys/bio.h>
55 #include <sys/fcntl.h>
56 #include <sys/lock.h>
57 #include <sys/module.h>
58 #include <sys/mutex.h>
59 #include <sys/condvar.h>
60 #include <sys/malloc.h>
61 #include <sys/conf.h>
62 #include <sys/ioccom.h>
63 #include <sys/queue.h>
64 #include <sys/sbuf.h>
65 #include <sys/smp.h>
66 #include <sys/endian.h>
67 #include <sys/proc.h>
68 #include <sys/sched.h>
69 #include <sys/sysctl.h>
70 #include <sys/nv.h>
71 #include <sys/dnv.h>
72 #include <vm/uma.h>
73 
74 #include <cam/cam.h>
75 #include <cam/scsi/scsi_all.h>
76 #include <cam/scsi/scsi_cd.h>
77 #include <cam/scsi/scsi_da.h>
78 #include <cam/ctl/ctl_io.h>
79 #include <cam/ctl/ctl.h>
80 #include <cam/ctl/ctl_frontend.h>
81 #include <cam/ctl/ctl_util.h>
82 #include <cam/ctl/ctl_backend.h>
83 #include <cam/ctl/ctl_ioctl.h>
84 #include <cam/ctl/ctl_ha.h>
85 #include <cam/ctl/ctl_private.h>
86 #include <cam/ctl/ctl_debug.h>
87 #include <cam/ctl/ctl_scsi_all.h>
88 #include <cam/ctl/ctl_error.h>
89 
90 struct ctl_softc *control_softc = NULL;
91 
92 /*
93  * Template mode pages.
94  */
95 
96 /*
97  * Note that these are default values only.  The actual values will be
98  * filled in when the user does a mode sense.
99  */
100 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
101 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
102 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
103 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
104 	/*read_retry_count*/0,
105 	/*correction_span*/0,
106 	/*head_offset_count*/0,
107 	/*data_strobe_offset_cnt*/0,
108 	/*byte8*/SMS_RWER_LBPERE,
109 	/*write_retry_count*/0,
110 	/*reserved2*/0,
111 	/*recovery_time_limit*/{0, 0},
112 };
113 
114 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
115 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
116 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
117 	/*byte3*/SMS_RWER_PER,
118 	/*read_retry_count*/0,
119 	/*correction_span*/0,
120 	/*head_offset_count*/0,
121 	/*data_strobe_offset_cnt*/0,
122 	/*byte8*/SMS_RWER_LBPERE,
123 	/*write_retry_count*/0,
124 	/*reserved2*/0,
125 	/*recovery_time_limit*/{0, 0},
126 };
127 
128 const static struct scsi_format_page format_page_default = {
129 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
130 	/*page_length*/sizeof(struct scsi_format_page) - 2,
131 	/*tracks_per_zone*/ {0, 0},
132 	/*alt_sectors_per_zone*/ {0, 0},
133 	/*alt_tracks_per_zone*/ {0, 0},
134 	/*alt_tracks_per_lun*/ {0, 0},
135 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
136 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
137 	/*bytes_per_sector*/ {0, 0},
138 	/*interleave*/ {0, 0},
139 	/*track_skew*/ {0, 0},
140 	/*cylinder_skew*/ {0, 0},
141 	/*flags*/ SFP_HSEC,
142 	/*reserved*/ {0, 0, 0}
143 };
144 
145 const static struct scsi_format_page format_page_changeable = {
146 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
147 	/*page_length*/sizeof(struct scsi_format_page) - 2,
148 	/*tracks_per_zone*/ {0, 0},
149 	/*alt_sectors_per_zone*/ {0, 0},
150 	/*alt_tracks_per_zone*/ {0, 0},
151 	/*alt_tracks_per_lun*/ {0, 0},
152 	/*sectors_per_track*/ {0, 0},
153 	/*bytes_per_sector*/ {0, 0},
154 	/*interleave*/ {0, 0},
155 	/*track_skew*/ {0, 0},
156 	/*cylinder_skew*/ {0, 0},
157 	/*flags*/ 0,
158 	/*reserved*/ {0, 0, 0}
159 };
160 
161 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
162 	/*page_code*/SMS_RIGID_DISK_PAGE,
163 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
164 	/*cylinders*/ {0, 0, 0},
165 	/*heads*/ CTL_DEFAULT_HEADS,
166 	/*start_write_precomp*/ {0, 0, 0},
167 	/*start_reduced_current*/ {0, 0, 0},
168 	/*step_rate*/ {0, 0},
169 	/*landing_zone_cylinder*/ {0, 0, 0},
170 	/*rpl*/ SRDP_RPL_DISABLED,
171 	/*rotational_offset*/ 0,
172 	/*reserved1*/ 0,
173 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
174 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
175 	/*reserved2*/ {0, 0}
176 };
177 
178 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
179 	/*page_code*/SMS_RIGID_DISK_PAGE,
180 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
181 	/*cylinders*/ {0, 0, 0},
182 	/*heads*/ 0,
183 	/*start_write_precomp*/ {0, 0, 0},
184 	/*start_reduced_current*/ {0, 0, 0},
185 	/*step_rate*/ {0, 0},
186 	/*landing_zone_cylinder*/ {0, 0, 0},
187 	/*rpl*/ 0,
188 	/*rotational_offset*/ 0,
189 	/*reserved1*/ 0,
190 	/*rotation_rate*/ {0, 0},
191 	/*reserved2*/ {0, 0}
192 };
193 
194 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
195 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
196 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
197 	/*byte3*/0,
198 	/*read_retry_count*/0,
199 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
200 	/*recovery_time_limit*/{0, 0},
201 };
202 
203 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
204 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
205 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
206 	/*byte3*/SMS_VER_PER,
207 	/*read_retry_count*/0,
208 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
209 	/*recovery_time_limit*/{0, 0},
210 };
211 
212 const static struct scsi_caching_page caching_page_default = {
213 	/*page_code*/SMS_CACHING_PAGE,
214 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
215 	/*flags1*/ SCP_DISC | SCP_WCE,
216 	/*ret_priority*/ 0,
217 	/*disable_pf_transfer_len*/ {0xff, 0xff},
218 	/*min_prefetch*/ {0, 0},
219 	/*max_prefetch*/ {0xff, 0xff},
220 	/*max_pf_ceiling*/ {0xff, 0xff},
221 	/*flags2*/ 0,
222 	/*cache_segments*/ 0,
223 	/*cache_seg_size*/ {0, 0},
224 	/*reserved*/ 0,
225 	/*non_cache_seg_size*/ {0, 0, 0}
226 };
227 
228 const static struct scsi_caching_page caching_page_changeable = {
229 	/*page_code*/SMS_CACHING_PAGE,
230 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
231 	/*flags1*/ SCP_WCE | SCP_RCD,
232 	/*ret_priority*/ 0,
233 	/*disable_pf_transfer_len*/ {0, 0},
234 	/*min_prefetch*/ {0, 0},
235 	/*max_prefetch*/ {0, 0},
236 	/*max_pf_ceiling*/ {0, 0},
237 	/*flags2*/ 0,
238 	/*cache_segments*/ 0,
239 	/*cache_seg_size*/ {0, 0},
240 	/*reserved*/ 0,
241 	/*non_cache_seg_size*/ {0, 0, 0}
242 };
243 
244 const static struct scsi_control_page control_page_default = {
245 	/*page_code*/SMS_CONTROL_MODE_PAGE,
246 	/*page_length*/sizeof(struct scsi_control_page) - 2,
247 	/*rlec*/0,
248 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
249 	/*eca_and_aen*/0,
250 	/*flags4*/SCP_TAS,
251 	/*aen_holdoff_period*/{0, 0},
252 	/*busy_timeout_period*/{0, 0},
253 	/*extended_selftest_completion_time*/{0, 0}
254 };
255 
256 const static struct scsi_control_page control_page_changeable = {
257 	/*page_code*/SMS_CONTROL_MODE_PAGE,
258 	/*page_length*/sizeof(struct scsi_control_page) - 2,
259 	/*rlec*/SCP_DSENSE,
260 	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
261 	/*eca_and_aen*/SCP_SWP,
262 	/*flags4*/0,
263 	/*aen_holdoff_period*/{0, 0},
264 	/*busy_timeout_period*/{0, 0},
265 	/*extended_selftest_completion_time*/{0, 0}
266 };
267 
268 #define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
269 
270 const static struct scsi_control_ext_page control_ext_page_default = {
271 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
272 	/*subpage_code*/0x01,
273 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
274 	/*flags*/0,
275 	/*prio*/0,
276 	/*max_sense*/0
277 };
278 
279 const static struct scsi_control_ext_page control_ext_page_changeable = {
280 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
281 	/*subpage_code*/0x01,
282 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
283 	/*flags*/0,
284 	/*prio*/0,
285 	/*max_sense*/0xff
286 };
287 
288 const static struct scsi_info_exceptions_page ie_page_default = {
289 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
290 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
291 	/*info_flags*/SIEP_FLAGS_EWASC,
292 	/*mrie*/SIEP_MRIE_NO,
293 	/*interval_timer*/{0, 0, 0, 0},
294 	/*report_count*/{0, 0, 0, 1}
295 };
296 
297 const static struct scsi_info_exceptions_page ie_page_changeable = {
298 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
299 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
300 	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
301 	    SIEP_FLAGS_LOGERR,
302 	/*mrie*/0x0f,
303 	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
304 	/*report_count*/{0xff, 0xff, 0xff, 0xff}
305 };
306 
307 #define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
308 
309 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
310 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
311 	/*subpage_code*/0x02,
312 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
313 	/*flags*/0,
314 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
315 	/*descr*/{}},
316 	{{/*flags*/0,
317 	  /*resource*/0x01,
318 	  /*reserved*/{0, 0},
319 	  /*count*/{0, 0, 0, 0}},
320 	 {/*flags*/0,
321 	  /*resource*/0x02,
322 	  /*reserved*/{0, 0},
323 	  /*count*/{0, 0, 0, 0}},
324 	 {/*flags*/0,
325 	  /*resource*/0xf1,
326 	  /*reserved*/{0, 0},
327 	  /*count*/{0, 0, 0, 0}},
328 	 {/*flags*/0,
329 	  /*resource*/0xf2,
330 	  /*reserved*/{0, 0},
331 	  /*count*/{0, 0, 0, 0}}
332 	}
333 };
334 
335 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
336 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
337 	/*subpage_code*/0x02,
338 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
339 	/*flags*/SLBPP_SITUA,
340 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
341 	/*descr*/{}},
342 	{{/*flags*/0,
343 	  /*resource*/0,
344 	  /*reserved*/{0, 0},
345 	  /*count*/{0, 0, 0, 0}},
346 	 {/*flags*/0,
347 	  /*resource*/0,
348 	  /*reserved*/{0, 0},
349 	  /*count*/{0, 0, 0, 0}},
350 	 {/*flags*/0,
351 	  /*resource*/0,
352 	  /*reserved*/{0, 0},
353 	  /*count*/{0, 0, 0, 0}},
354 	 {/*flags*/0,
355 	  /*resource*/0,
356 	  /*reserved*/{0, 0},
357 	  /*count*/{0, 0, 0, 0}}
358 	}
359 };
360 
361 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
362 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
363 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
364 	/*caps1*/0x3f,
365 	/*caps2*/0x00,
366 	/*caps3*/0xf0,
367 	/*caps4*/0x00,
368 	/*caps5*/0x29,
369 	/*caps6*/0x00,
370 	/*obsolete*/{0, 0},
371 	/*nvol_levels*/{0, 0},
372 	/*buffer_size*/{8, 0},
373 	/*obsolete2*/{0, 0},
374 	/*reserved*/0,
375 	/*digital*/0,
376 	/*obsolete3*/0,
377 	/*copy_management*/0,
378 	/*reserved2*/0,
379 	/*rotation_control*/0,
380 	/*cur_write_speed*/0,
381 	/*num_speed_descr*/0,
382 };
383 
384 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
385 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
386 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
387 	/*caps1*/0,
388 	/*caps2*/0,
389 	/*caps3*/0,
390 	/*caps4*/0,
391 	/*caps5*/0,
392 	/*caps6*/0,
393 	/*obsolete*/{0, 0},
394 	/*nvol_levels*/{0, 0},
395 	/*buffer_size*/{0, 0},
396 	/*obsolete2*/{0, 0},
397 	/*reserved*/0,
398 	/*digital*/0,
399 	/*obsolete3*/0,
400 	/*copy_management*/0,
401 	/*reserved2*/0,
402 	/*rotation_control*/0,
403 	/*cur_write_speed*/0,
404 	/*num_speed_descr*/0,
405 };
406 
407 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
408     "CAM Target Layer");
409 static int worker_threads = -1;
410 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
411     &worker_threads, 1, "Number of worker threads");
412 static int ctl_debug = CTL_DEBUG_NONE;
413 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
414     &ctl_debug, 0, "Enabled debug flags");
415 static int ctl_lun_map_size = 1024;
416 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
417     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
418 #ifdef  CTL_TIME_IO
419 static int ctl_time_io_secs = CTL_TIME_IO_DEFAULT_SECS;
420 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, time_io_secs, CTLFLAG_RWTUN,
421     &ctl_time_io_secs, 0, "Log requests taking more seconds");
422 #endif
423 
424 /*
425  * Maximum number of LUNs we support.  MUST be a power of 2.
426  */
427 #define	CTL_DEFAULT_MAX_LUNS	1024
428 static int ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
429 TUNABLE_INT("kern.cam.ctl.max_luns", &ctl_max_luns);
430 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_luns, CTLFLAG_RDTUN,
431     &ctl_max_luns, CTL_DEFAULT_MAX_LUNS, "Maximum number of LUNs");
432 
433 /*
434  * Maximum number of ports registered at one time.
435  */
436 #define	CTL_DEFAULT_MAX_PORTS		1024
437 static int ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
438 TUNABLE_INT("kern.cam.ctl.max_ports", &ctl_max_ports);
439 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_ports, CTLFLAG_RDTUN,
440     &ctl_max_ports, CTL_DEFAULT_MAX_LUNS, "Maximum number of ports");
441 
442 /*
443  * Maximum number of initiators we support.
444  */
445 #define	CTL_MAX_INITIATORS	(CTL_MAX_INIT_PER_PORT * ctl_max_ports)
446 
447 /*
448  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
449  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
450  * SCSI Ports (0x88), Third-party Copy (0x8F), SCSI Feature Sets (0x92),
451  * Block limits (0xB0), Block Device Characteristics (0xB1) and
452  * Logical Block Provisioning (0xB2)
453  */
454 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	11
455 
456 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
457 				  int param);
458 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
459 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
460 static int ctl_init(void);
461 static int ctl_shutdown(void);
462 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
463 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
464 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
465 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
466 			      struct ctl_ooa *ooa_hdr,
467 			      struct ctl_ooa_entry *kern_entries);
468 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
469 		     struct thread *td);
470 static int ctl_enable_lun(struct ctl_lun *lun);
471 static int ctl_disable_lun(struct ctl_lun *lun);
472 static int ctl_free_lun(struct ctl_lun *lun);
473 
474 static int ctl_do_mode_select(union ctl_io *io);
475 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
476 			   uint64_t res_key, uint64_t sa_res_key,
477 			   uint8_t type, uint32_t residx,
478 			   struct ctl_scsiio *ctsio,
479 			   struct scsi_per_res_out *cdb,
480 			   struct scsi_per_res_out_parms* param);
481 static void ctl_pro_preempt_other(struct ctl_lun *lun,
482 				  union ctl_ha_msg *msg);
483 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
484 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
485 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
486 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
487 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
488 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
489 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
490 					 int alloc_len);
491 static int ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len);
492 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
493 					 int alloc_len);
494 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
495 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
496 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
497 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
498 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
499 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
500     bool seq);
501 static ctl_action ctl_seq_check(union ctl_io *io1, union ctl_io *io2);
502 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
503     union ctl_io *pending_io, const uint8_t *serialize_row,
504     union ctl_io *ooa_io);
505 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
506 				union ctl_io **starting_io);
507 static void ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io,
508     bool skip);
509 static void ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *io,
510     bool skip);
511 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
512 				const struct ctl_cmd_entry *entry,
513 				struct ctl_scsiio *ctsio);
514 static void ctl_failover_lun(union ctl_io *io);
515 static void ctl_scsiio_precheck(struct ctl_scsiio *ctsio);
516 static int ctl_scsiio(struct ctl_scsiio *ctsio);
517 
518 static int ctl_target_reset(union ctl_io *io);
519 static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
520 			 ctl_ua_type ua_type);
521 static int ctl_lun_reset(union ctl_io *io);
522 static int ctl_abort_task(union ctl_io *io);
523 static int ctl_abort_task_set(union ctl_io *io);
524 static int ctl_query_task(union ctl_io *io, int task_set);
525 static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
526 			      ctl_ua_type ua_type);
527 static int ctl_i_t_nexus_reset(union ctl_io *io);
528 static int ctl_query_async_event(union ctl_io *io);
529 static void ctl_run_task(union ctl_io *io);
530 #ifdef CTL_IO_DELAY
531 static void ctl_datamove_timer_wakeup(void *arg);
532 static void ctl_done_timer_wakeup(void *arg);
533 #endif /* CTL_IO_DELAY */
534 
535 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
536 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
537 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io, bool samethr);
538 static void ctl_datamove_remote_write(union ctl_io *io);
539 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io, bool samethr);
540 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
541 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
542 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
543 				    ctl_ha_dt_cb callback);
544 static void ctl_datamove_remote_read(union ctl_io *io);
545 static void ctl_datamove_remote(union ctl_io *io);
546 static void ctl_process_done(union ctl_io *io);
547 static void ctl_thresh_thread(void *arg);
548 static void ctl_work_thread(void *arg);
549 static void ctl_enqueue_incoming(union ctl_io *io);
550 static void ctl_enqueue_rtr(union ctl_io *io);
551 static void ctl_enqueue_done(union ctl_io *io);
552 static void ctl_enqueue_isc(union ctl_io *io);
553 static const struct ctl_cmd_entry *
554     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
555 static const struct ctl_cmd_entry *
556     ctl_validate_command(struct ctl_scsiio *ctsio);
557 static int ctl_cmd_applicable(uint8_t lun_type,
558     const struct ctl_cmd_entry *entry);
559 static int ctl_ha_init(void);
560 static int ctl_ha_shutdown(void);
561 
562 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
563 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
564 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
565 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
566 
567 /*
568  * Load the serialization table.  This isn't very pretty, but is probably
569  * the easiest way to do it.
570  */
571 #include "ctl_ser_table.c"
572 
573 /*
574  * We only need to define open, close and ioctl routines for this driver.
575  */
576 static struct cdevsw ctl_cdevsw = {
577 	.d_version =	D_VERSION,
578 	.d_flags =	0,
579 	.d_open =	ctl_open,
580 	.d_close =	ctl_close,
581 	.d_ioctl =	ctl_ioctl,
582 	.d_name =	"ctl",
583 };
584 
585 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
586 
587 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
588 
589 static moduledata_t ctl_moduledata = {
590 	"ctl",
591 	ctl_module_event_handler,
592 	NULL
593 };
594 
595 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
596 MODULE_VERSION(ctl, 1);
597 
598 static struct ctl_frontend ha_frontend =
599 {
600 	.name = "ha",
601 	.init = ctl_ha_init,
602 	.shutdown = ctl_ha_shutdown,
603 };
604 
605 static int
606 ctl_ha_init(void)
607 {
608 	struct ctl_softc *softc = control_softc;
609 
610 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
611 	                    &softc->othersc_pool) != 0)
612 		return (ENOMEM);
613 	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
614 		ctl_pool_free(softc->othersc_pool);
615 		return (EIO);
616 	}
617 	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
618 	    != CTL_HA_STATUS_SUCCESS) {
619 		ctl_ha_msg_destroy(softc);
620 		ctl_pool_free(softc->othersc_pool);
621 		return (EIO);
622 	}
623 	return (0);
624 };
625 
626 static int
627 ctl_ha_shutdown(void)
628 {
629 	struct ctl_softc *softc = control_softc;
630 	struct ctl_port *port;
631 
632 	ctl_ha_msg_shutdown(softc);
633 	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
634 		return (EIO);
635 	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
636 		return (EIO);
637 	ctl_pool_free(softc->othersc_pool);
638 	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
639 		ctl_port_deregister(port);
640 		free(port->port_name, M_CTL);
641 		free(port, M_CTL);
642 	}
643 	return (0);
644 };
645 
646 static void
647 ctl_ha_datamove(union ctl_io *io)
648 {
649 	struct ctl_lun *lun = CTL_LUN(io);
650 	struct ctl_sg_entry *sgl;
651 	union ctl_ha_msg msg;
652 	uint32_t sg_entries_sent;
653 	int do_sg_copy, i, j;
654 
655 	memset(&msg.dt, 0, sizeof(msg.dt));
656 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
657 	msg.hdr.original_sc = io->io_hdr.remote_io;
658 	msg.hdr.serializing_sc = io;
659 	msg.hdr.nexus = io->io_hdr.nexus;
660 	msg.hdr.status = io->io_hdr.status;
661 	msg.dt.flags = io->io_hdr.flags;
662 
663 	/*
664 	 * We convert everything into a S/G list here.  We can't
665 	 * pass by reference, only by value between controllers.
666 	 * So we can't pass a pointer to the S/G list, only as many
667 	 * S/G entries as we can fit in here.  If it's possible for
668 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
669 	 * then we need to break this up into multiple transfers.
670 	 */
671 	if (io->scsiio.kern_sg_entries == 0) {
672 		msg.dt.kern_sg_entries = 1;
673 #if 0
674 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
675 			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
676 		} else {
677 			/* XXX KDM use busdma here! */
678 			msg.dt.sg_list[0].addr =
679 			    (void *)vtophys(io->scsiio.kern_data_ptr);
680 		}
681 #else
682 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
683 		    ("HA does not support BUS_ADDR"));
684 		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
685 #endif
686 		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
687 		do_sg_copy = 0;
688 	} else {
689 		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
690 		do_sg_copy = 1;
691 	}
692 
693 	msg.dt.kern_data_len = io->scsiio.kern_data_len;
694 	msg.dt.kern_total_len = io->scsiio.kern_total_len;
695 	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
696 	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
697 	msg.dt.sg_sequence = 0;
698 
699 	/*
700 	 * Loop until we've sent all of the S/G entries.  On the
701 	 * other end, we'll recompose these S/G entries into one
702 	 * contiguous list before processing.
703 	 */
704 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
705 	    msg.dt.sg_sequence++) {
706 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
707 		    sizeof(msg.dt.sg_list[0])),
708 		    msg.dt.kern_sg_entries - sg_entries_sent);
709 		if (do_sg_copy != 0) {
710 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
711 			for (i = sg_entries_sent, j = 0;
712 			     i < msg.dt.cur_sg_entries; i++, j++) {
713 #if 0
714 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
715 					msg.dt.sg_list[j].addr = sgl[i].addr;
716 				} else {
717 					/* XXX KDM use busdma here! */
718 					msg.dt.sg_list[j].addr =
719 					    (void *)vtophys(sgl[i].addr);
720 				}
721 #else
722 				KASSERT((io->io_hdr.flags &
723 				    CTL_FLAG_BUS_ADDR) == 0,
724 				    ("HA does not support BUS_ADDR"));
725 				msg.dt.sg_list[j].addr = sgl[i].addr;
726 #endif
727 				msg.dt.sg_list[j].len = sgl[i].len;
728 			}
729 		}
730 
731 		sg_entries_sent += msg.dt.cur_sg_entries;
732 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
733 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
734 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
735 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
736 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
737 			io->io_hdr.port_status = 31341;
738 			ctl_datamove_done(io, true);
739 			return;
740 		}
741 		msg.dt.sent_sg_entries = sg_entries_sent;
742 	}
743 
744 	/*
745 	 * Officially handover the request from us to peer.
746 	 * If failover has just happened, then we must return error.
747 	 * If failover happen just after, then it is not our problem.
748 	 */
749 	if (lun)
750 		mtx_lock(&lun->lun_lock);
751 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
752 		if (lun)
753 			mtx_unlock(&lun->lun_lock);
754 		io->io_hdr.port_status = 31342;
755 		ctl_datamove_done(io, true);
756 		return;
757 	}
758 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
759 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
760 	if (lun)
761 		mtx_unlock(&lun->lun_lock);
762 }
763 
764 static void
765 ctl_ha_done(union ctl_io *io)
766 {
767 	union ctl_ha_msg msg;
768 
769 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
770 		memset(&msg, 0, sizeof(msg));
771 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
772 		msg.hdr.original_sc = io->io_hdr.remote_io;
773 		msg.hdr.nexus = io->io_hdr.nexus;
774 		msg.hdr.status = io->io_hdr.status;
775 		msg.scsi.scsi_status = io->scsiio.scsi_status;
776 		msg.scsi.tag_num = io->scsiio.tag_num;
777 		msg.scsi.tag_type = io->scsiio.tag_type;
778 		msg.scsi.sense_len = io->scsiio.sense_len;
779 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
780 		    io->scsiio.sense_len);
781 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
782 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
783 		    msg.scsi.sense_len, M_WAITOK);
784 	}
785 	ctl_free_io(io);
786 }
787 
788 static void
789 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
790 			    union ctl_ha_msg *msg_info)
791 {
792 	struct ctl_scsiio *ctsio;
793 
794 	if (msg_info->hdr.original_sc == NULL) {
795 		printf("%s: original_sc == NULL!\n", __func__);
796 		/* XXX KDM now what? */
797 		return;
798 	}
799 
800 	ctsio = &msg_info->hdr.original_sc->scsiio;
801 	ctsio->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
802 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
803 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
804 	ctsio->io_hdr.status = msg_info->hdr.status;
805 	ctsio->scsi_status = msg_info->scsi.scsi_status;
806 	ctsio->sense_len = msg_info->scsi.sense_len;
807 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
808 	       msg_info->scsi.sense_len);
809 	ctl_enqueue_isc((union ctl_io *)ctsio);
810 }
811 
812 static void
813 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
814 				union ctl_ha_msg *msg_info)
815 {
816 	struct ctl_scsiio *ctsio;
817 
818 	if (msg_info->hdr.serializing_sc == NULL) {
819 		printf("%s: serializing_sc == NULL!\n", __func__);
820 		/* XXX KDM now what? */
821 		return;
822 	}
823 
824 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
825 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
826 	ctl_enqueue_isc((union ctl_io *)ctsio);
827 }
828 
829 void
830 ctl_isc_announce_lun(struct ctl_lun *lun)
831 {
832 	struct ctl_softc *softc = lun->ctl_softc;
833 	union ctl_ha_msg *msg;
834 	struct ctl_ha_msg_lun_pr_key pr_key;
835 	int i, k;
836 
837 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
838 		return;
839 	mtx_lock(&lun->lun_lock);
840 	i = sizeof(msg->lun);
841 	if (lun->lun_devid)
842 		i += lun->lun_devid->len;
843 	i += sizeof(pr_key) * lun->pr_key_count;
844 alloc:
845 	mtx_unlock(&lun->lun_lock);
846 	msg = malloc(i, M_CTL, M_WAITOK);
847 	mtx_lock(&lun->lun_lock);
848 	k = sizeof(msg->lun);
849 	if (lun->lun_devid)
850 		k += lun->lun_devid->len;
851 	k += sizeof(pr_key) * lun->pr_key_count;
852 	if (i < k) {
853 		free(msg, M_CTL);
854 		i = k;
855 		goto alloc;
856 	}
857 	bzero(&msg->lun, sizeof(msg->lun));
858 	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
859 	msg->hdr.nexus.targ_lun = lun->lun;
860 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
861 	msg->lun.flags = lun->flags;
862 	msg->lun.pr_generation = lun->pr_generation;
863 	msg->lun.pr_res_idx = lun->pr_res_idx;
864 	msg->lun.pr_res_type = lun->pr_res_type;
865 	msg->lun.pr_key_count = lun->pr_key_count;
866 	i = 0;
867 	if (lun->lun_devid) {
868 		msg->lun.lun_devid_len = lun->lun_devid->len;
869 		memcpy(&msg->lun.data[i], lun->lun_devid->data,
870 		    msg->lun.lun_devid_len);
871 		i += msg->lun.lun_devid_len;
872 	}
873 	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
874 		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
875 			continue;
876 		pr_key.pr_iid = k;
877 		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
878 		i += sizeof(pr_key);
879 	}
880 	mtx_unlock(&lun->lun_lock);
881 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->lun, sizeof(msg->lun) + i,
882 	    M_WAITOK);
883 	free(msg, M_CTL);
884 
885 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
886 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
887 			ctl_isc_announce_mode(lun, -1,
888 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
889 			    lun->mode_pages.index[i].subpage);
890 		}
891 	}
892 }
893 
894 void
895 ctl_isc_announce_port(struct ctl_port *port)
896 {
897 	struct ctl_softc *softc = port->ctl_softc;
898 	union ctl_ha_msg *msg;
899 	int i;
900 
901 	if (port->targ_port < softc->port_min ||
902 	    port->targ_port >= softc->port_max ||
903 	    softc->ha_link != CTL_HA_LINK_ONLINE)
904 		return;
905 	i = sizeof(msg->port) + strlen(port->port_name) + 1;
906 	if (port->lun_map)
907 		i += port->lun_map_size * sizeof(uint32_t);
908 	if (port->port_devid)
909 		i += port->port_devid->len;
910 	if (port->target_devid)
911 		i += port->target_devid->len;
912 	if (port->init_devid)
913 		i += port->init_devid->len;
914 	msg = malloc(i, M_CTL, M_WAITOK);
915 	bzero(&msg->port, sizeof(msg->port));
916 	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
917 	msg->hdr.nexus.targ_port = port->targ_port;
918 	msg->port.port_type = port->port_type;
919 	msg->port.physical_port = port->physical_port;
920 	msg->port.virtual_port = port->virtual_port;
921 	msg->port.status = port->status;
922 	i = 0;
923 	msg->port.name_len = sprintf(&msg->port.data[i],
924 	    "%d:%s", softc->ha_id, port->port_name) + 1;
925 	i += msg->port.name_len;
926 	if (port->lun_map) {
927 		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
928 		memcpy(&msg->port.data[i], port->lun_map,
929 		    msg->port.lun_map_len);
930 		i += msg->port.lun_map_len;
931 	}
932 	if (port->port_devid) {
933 		msg->port.port_devid_len = port->port_devid->len;
934 		memcpy(&msg->port.data[i], port->port_devid->data,
935 		    msg->port.port_devid_len);
936 		i += msg->port.port_devid_len;
937 	}
938 	if (port->target_devid) {
939 		msg->port.target_devid_len = port->target_devid->len;
940 		memcpy(&msg->port.data[i], port->target_devid->data,
941 		    msg->port.target_devid_len);
942 		i += msg->port.target_devid_len;
943 	}
944 	if (port->init_devid) {
945 		msg->port.init_devid_len = port->init_devid->len;
946 		memcpy(&msg->port.data[i], port->init_devid->data,
947 		    msg->port.init_devid_len);
948 		i += msg->port.init_devid_len;
949 	}
950 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
951 	    M_WAITOK);
952 	free(msg, M_CTL);
953 }
954 
955 void
956 ctl_isc_announce_iid(struct ctl_port *port, int iid)
957 {
958 	struct ctl_softc *softc = port->ctl_softc;
959 	union ctl_ha_msg *msg;
960 	int i, l;
961 
962 	if (port->targ_port < softc->port_min ||
963 	    port->targ_port >= softc->port_max ||
964 	    softc->ha_link != CTL_HA_LINK_ONLINE)
965 		return;
966 	mtx_lock(&softc->ctl_lock);
967 	i = sizeof(msg->iid);
968 	l = 0;
969 	if (port->wwpn_iid[iid].name)
970 		l = strlen(port->wwpn_iid[iid].name) + 1;
971 	i += l;
972 	msg = malloc(i, M_CTL, M_NOWAIT);
973 	if (msg == NULL) {
974 		mtx_unlock(&softc->ctl_lock);
975 		return;
976 	}
977 	bzero(&msg->iid, sizeof(msg->iid));
978 	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
979 	msg->hdr.nexus.targ_port = port->targ_port;
980 	msg->hdr.nexus.initid = iid;
981 	msg->iid.in_use = port->wwpn_iid[iid].in_use;
982 	msg->iid.name_len = l;
983 	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
984 	if (port->wwpn_iid[iid].name)
985 		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
986 	mtx_unlock(&softc->ctl_lock);
987 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
988 	free(msg, M_CTL);
989 }
990 
991 void
992 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
993     uint8_t page, uint8_t subpage)
994 {
995 	struct ctl_softc *softc = lun->ctl_softc;
996 	union ctl_ha_msg *msg;
997 	u_int i, l;
998 
999 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
1000 		return;
1001 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1002 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1003 		    page && lun->mode_pages.index[i].subpage == subpage)
1004 			break;
1005 	}
1006 	if (i == CTL_NUM_MODE_PAGES)
1007 		return;
1008 
1009 	/* Don't try to replicate pages not present on this device. */
1010 	if (lun->mode_pages.index[i].page_data == NULL)
1011 		return;
1012 
1013 	l = sizeof(msg->mode) + lun->mode_pages.index[i].page_len;
1014 	msg = malloc(l, M_CTL, M_WAITOK | M_ZERO);
1015 	msg->hdr.msg_type = CTL_MSG_MODE_SYNC;
1016 	msg->hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
1017 	msg->hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
1018 	msg->hdr.nexus.targ_lun = lun->lun;
1019 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
1020 	msg->mode.page_code = page;
1021 	msg->mode.subpage = subpage;
1022 	msg->mode.page_len = lun->mode_pages.index[i].page_len;
1023 	memcpy(msg->mode.data, lun->mode_pages.index[i].page_data,
1024 	    msg->mode.page_len);
1025 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->mode, l, M_WAITOK);
1026 	free(msg, M_CTL);
1027 }
1028 
1029 static void
1030 ctl_isc_ha_link_up(struct ctl_softc *softc)
1031 {
1032 	struct ctl_port *port;
1033 	struct ctl_lun *lun;
1034 	union ctl_ha_msg msg;
1035 	int i;
1036 
1037 	/* Announce this node parameters to peer for validation. */
1038 	msg.login.msg_type = CTL_MSG_LOGIN;
1039 	msg.login.version = CTL_HA_VERSION;
1040 	msg.login.ha_mode = softc->ha_mode;
1041 	msg.login.ha_id = softc->ha_id;
1042 	msg.login.max_luns = ctl_max_luns;
1043 	msg.login.max_ports = ctl_max_ports;
1044 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1045 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1046 	    M_WAITOK);
1047 
1048 	STAILQ_FOREACH(port, &softc->port_list, links) {
1049 		ctl_isc_announce_port(port);
1050 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1051 			if (port->wwpn_iid[i].in_use)
1052 				ctl_isc_announce_iid(port, i);
1053 		}
1054 	}
1055 	STAILQ_FOREACH(lun, &softc->lun_list, links)
1056 		ctl_isc_announce_lun(lun);
1057 }
1058 
1059 static void
1060 ctl_isc_ha_link_down(struct ctl_softc *softc)
1061 {
1062 	struct ctl_port *port;
1063 	struct ctl_lun *lun;
1064 	union ctl_io *io;
1065 	int i;
1066 
1067 	mtx_lock(&softc->ctl_lock);
1068 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1069 		mtx_lock(&lun->lun_lock);
1070 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1071 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1072 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1073 		}
1074 		mtx_unlock(&lun->lun_lock);
1075 
1076 		mtx_unlock(&softc->ctl_lock);
1077 		io = ctl_alloc_io(softc->othersc_pool);
1078 		mtx_lock(&softc->ctl_lock);
1079 		ctl_zero_io(io);
1080 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1081 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1082 		ctl_enqueue_isc(io);
1083 	}
1084 
1085 	STAILQ_FOREACH(port, &softc->port_list, links) {
1086 		if (port->targ_port >= softc->port_min &&
1087 		    port->targ_port < softc->port_max)
1088 			continue;
1089 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1090 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1091 			port->wwpn_iid[i].in_use = 0;
1092 			free(port->wwpn_iid[i].name, M_CTL);
1093 			port->wwpn_iid[i].name = NULL;
1094 		}
1095 	}
1096 	mtx_unlock(&softc->ctl_lock);
1097 }
1098 
1099 static void
1100 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1101 {
1102 	struct ctl_lun *lun;
1103 	uint32_t iid;
1104 
1105 	if (len < sizeof(msg->ua)) {
1106 		printf("%s: Received truncated message %d < %zu\n",
1107 		    __func__, len, sizeof(msg->ua));
1108 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1109 		return;
1110 	}
1111 
1112 	mtx_lock(&softc->ctl_lock);
1113 	if (msg->hdr.nexus.targ_mapped_lun >= ctl_max_luns ||
1114 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1115 		mtx_unlock(&softc->ctl_lock);
1116 		return;
1117 	}
1118 	mtx_lock(&lun->lun_lock);
1119 	mtx_unlock(&softc->ctl_lock);
1120 	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1121 		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1122 	iid = ctl_get_initindex(&msg->hdr.nexus);
1123 	if (msg->ua.ua_all) {
1124 		if (msg->ua.ua_set)
1125 			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1126 		else
1127 			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1128 	} else {
1129 		if (msg->ua.ua_set)
1130 			ctl_est_ua(lun, iid, msg->ua.ua_type);
1131 		else
1132 			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1133 	}
1134 	mtx_unlock(&lun->lun_lock);
1135 }
1136 
1137 static void
1138 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1139 {
1140 	struct ctl_lun *lun;
1141 	struct ctl_ha_msg_lun_pr_key pr_key;
1142 	int i, k;
1143 	ctl_lun_flags oflags;
1144 	uint32_t targ_lun;
1145 
1146 	if (len < offsetof(struct ctl_ha_msg_lun, data[0])) {
1147 		printf("%s: Received truncated message %d < %zu\n",
1148 		    __func__, len, offsetof(struct ctl_ha_msg_lun, data[0]));
1149 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1150 		return;
1151 	}
1152 	i = msg->lun.lun_devid_len + msg->lun.pr_key_count * sizeof(pr_key);
1153 	if (len < offsetof(struct ctl_ha_msg_lun, data[i])) {
1154 		printf("%s: Received truncated message data %d < %zu\n",
1155 		    __func__, len, offsetof(struct ctl_ha_msg_lun, data[i]));
1156 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1157 		return;
1158 	}
1159 
1160 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1161 	mtx_lock(&softc->ctl_lock);
1162 	if (targ_lun >= ctl_max_luns ||
1163 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1164 		mtx_unlock(&softc->ctl_lock);
1165 		return;
1166 	}
1167 	mtx_lock(&lun->lun_lock);
1168 	mtx_unlock(&softc->ctl_lock);
1169 	if (lun->flags & CTL_LUN_DISABLED) {
1170 		mtx_unlock(&lun->lun_lock);
1171 		return;
1172 	}
1173 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1174 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1175 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1176 		mtx_unlock(&lun->lun_lock);
1177 		printf("%s: Received conflicting HA LUN %d\n",
1178 		    __func__, targ_lun);
1179 		return;
1180 	} else {
1181 		/* Record whether peer is primary. */
1182 		oflags = lun->flags;
1183 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1184 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1185 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1186 		else
1187 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1188 		if (oflags != lun->flags)
1189 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1190 
1191 		/* If peer is primary and we are not -- use data */
1192 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1193 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1194 			lun->pr_generation = msg->lun.pr_generation;
1195 			lun->pr_res_idx = msg->lun.pr_res_idx;
1196 			lun->pr_res_type = msg->lun.pr_res_type;
1197 			lun->pr_key_count = msg->lun.pr_key_count;
1198 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1199 				ctl_clr_prkey(lun, k);
1200 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1201 				memcpy(&pr_key, &msg->lun.data[i],
1202 				    sizeof(pr_key));
1203 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1204 				ctl_set_prkey(lun, pr_key.pr_iid,
1205 				    pr_key.pr_key);
1206 				i += sizeof(pr_key);
1207 			}
1208 		}
1209 
1210 		mtx_unlock(&lun->lun_lock);
1211 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1212 		    __func__, targ_lun,
1213 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1214 		    "primary" : "secondary"));
1215 
1216 		/* If we are primary but peer doesn't know -- notify */
1217 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1218 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1219 			ctl_isc_announce_lun(lun);
1220 	}
1221 }
1222 
1223 static void
1224 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1225 {
1226 	struct ctl_port *port;
1227 	struct ctl_lun *lun;
1228 	int i, new;
1229 
1230 	if (len < offsetof(struct ctl_ha_msg_port, data[0])) {
1231 		printf("%s: Received truncated message %d < %zu\n",
1232 		    __func__, len, offsetof(struct ctl_ha_msg_port, data[0]));
1233 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1234 		return;
1235 	}
1236 	i = msg->port.name_len + msg->port.lun_map_len +
1237 	    msg->port.port_devid_len + msg->port.target_devid_len +
1238 	    msg->port.init_devid_len;
1239 	if (len < offsetof(struct ctl_ha_msg_port, data[i])) {
1240 		printf("%s: Received truncated message data %d < %zu\n",
1241 		    __func__, len, offsetof(struct ctl_ha_msg_port, data[i]));
1242 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1243 		return;
1244 	}
1245 
1246 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1247 	if (port == NULL) {
1248 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1249 		    msg->hdr.nexus.targ_port));
1250 		new = 1;
1251 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1252 		port->frontend = &ha_frontend;
1253 		port->targ_port = msg->hdr.nexus.targ_port;
1254 		port->fe_datamove = ctl_ha_datamove;
1255 		port->fe_done = ctl_ha_done;
1256 	} else if (port->frontend == &ha_frontend) {
1257 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1258 		    msg->hdr.nexus.targ_port));
1259 		new = 0;
1260 	} else {
1261 		printf("%s: Received conflicting HA port %d\n",
1262 		    __func__, msg->hdr.nexus.targ_port);
1263 		return;
1264 	}
1265 	port->port_type = msg->port.port_type;
1266 	port->physical_port = msg->port.physical_port;
1267 	port->virtual_port = msg->port.virtual_port;
1268 	port->status = msg->port.status;
1269 	i = 0;
1270 	free(port->port_name, M_CTL);
1271 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1272 	    M_CTL);
1273 	i += msg->port.name_len;
1274 	if (msg->port.lun_map_len != 0) {
1275 		if (port->lun_map == NULL ||
1276 		    port->lun_map_size * sizeof(uint32_t) <
1277 		    msg->port.lun_map_len) {
1278 			port->lun_map_size = 0;
1279 			free(port->lun_map, M_CTL);
1280 			port->lun_map = malloc(msg->port.lun_map_len,
1281 			    M_CTL, M_WAITOK);
1282 		}
1283 		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1284 		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1285 		i += msg->port.lun_map_len;
1286 	} else {
1287 		port->lun_map_size = 0;
1288 		free(port->lun_map, M_CTL);
1289 		port->lun_map = NULL;
1290 	}
1291 	if (msg->port.port_devid_len != 0) {
1292 		if (port->port_devid == NULL ||
1293 		    port->port_devid->len < msg->port.port_devid_len) {
1294 			free(port->port_devid, M_CTL);
1295 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1296 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1297 		}
1298 		memcpy(port->port_devid->data, &msg->port.data[i],
1299 		    msg->port.port_devid_len);
1300 		port->port_devid->len = msg->port.port_devid_len;
1301 		i += msg->port.port_devid_len;
1302 	} else {
1303 		free(port->port_devid, M_CTL);
1304 		port->port_devid = NULL;
1305 	}
1306 	if (msg->port.target_devid_len != 0) {
1307 		if (port->target_devid == NULL ||
1308 		    port->target_devid->len < msg->port.target_devid_len) {
1309 			free(port->target_devid, M_CTL);
1310 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1311 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1312 		}
1313 		memcpy(port->target_devid->data, &msg->port.data[i],
1314 		    msg->port.target_devid_len);
1315 		port->target_devid->len = msg->port.target_devid_len;
1316 		i += msg->port.target_devid_len;
1317 	} else {
1318 		free(port->target_devid, M_CTL);
1319 		port->target_devid = NULL;
1320 	}
1321 	if (msg->port.init_devid_len != 0) {
1322 		if (port->init_devid == NULL ||
1323 		    port->init_devid->len < msg->port.init_devid_len) {
1324 			free(port->init_devid, M_CTL);
1325 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1326 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1327 		}
1328 		memcpy(port->init_devid->data, &msg->port.data[i],
1329 		    msg->port.init_devid_len);
1330 		port->init_devid->len = msg->port.init_devid_len;
1331 		i += msg->port.init_devid_len;
1332 	} else {
1333 		free(port->init_devid, M_CTL);
1334 		port->init_devid = NULL;
1335 	}
1336 	if (new) {
1337 		if (ctl_port_register(port) != 0) {
1338 			printf("%s: ctl_port_register() failed with error\n",
1339 			    __func__);
1340 		}
1341 	}
1342 	mtx_lock(&softc->ctl_lock);
1343 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1344 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1345 			continue;
1346 		mtx_lock(&lun->lun_lock);
1347 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1348 		mtx_unlock(&lun->lun_lock);
1349 	}
1350 	mtx_unlock(&softc->ctl_lock);
1351 }
1352 
1353 static void
1354 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1355 {
1356 	struct ctl_port *port;
1357 	int i, iid;
1358 
1359 	if (len < offsetof(struct ctl_ha_msg_iid, data[0])) {
1360 		printf("%s: Received truncated message %d < %zu\n",
1361 		    __func__, len, offsetof(struct ctl_ha_msg_iid, data[0]));
1362 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1363 		return;
1364 	}
1365 	i = msg->iid.name_len;
1366 	if (len < offsetof(struct ctl_ha_msg_iid, data[i])) {
1367 		printf("%s: Received truncated message data %d < %zu\n",
1368 		    __func__, len, offsetof(struct ctl_ha_msg_iid, data[i]));
1369 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1370 		return;
1371 	}
1372 
1373 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1374 	if (port == NULL) {
1375 		printf("%s: Received IID for unknown port %d\n",
1376 		    __func__, msg->hdr.nexus.targ_port);
1377 		return;
1378 	}
1379 	iid = msg->hdr.nexus.initid;
1380 	if (port->wwpn_iid[iid].in_use != 0 &&
1381 	    msg->iid.in_use == 0)
1382 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1383 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1384 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1385 	free(port->wwpn_iid[iid].name, M_CTL);
1386 	if (msg->iid.name_len) {
1387 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1388 		    msg->iid.name_len, M_CTL);
1389 	} else
1390 		port->wwpn_iid[iid].name = NULL;
1391 }
1392 
1393 static void
1394 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1395 {
1396 
1397 	if (len < sizeof(msg->login)) {
1398 		printf("%s: Received truncated message %d < %zu\n",
1399 		    __func__, len, sizeof(msg->login));
1400 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1401 		return;
1402 	}
1403 
1404 	if (msg->login.version != CTL_HA_VERSION) {
1405 		printf("CTL HA peers have different versions %d != %d\n",
1406 		    msg->login.version, CTL_HA_VERSION);
1407 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1408 		return;
1409 	}
1410 	if (msg->login.ha_mode != softc->ha_mode) {
1411 		printf("CTL HA peers have different ha_mode %d != %d\n",
1412 		    msg->login.ha_mode, softc->ha_mode);
1413 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1414 		return;
1415 	}
1416 	if (msg->login.ha_id == softc->ha_id) {
1417 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1418 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1419 		return;
1420 	}
1421 	if (msg->login.max_luns != ctl_max_luns ||
1422 	    msg->login.max_ports != ctl_max_ports ||
1423 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1424 		printf("CTL HA peers have different limits\n");
1425 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1426 		return;
1427 	}
1428 }
1429 
1430 static void
1431 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1432 {
1433 	struct ctl_lun *lun;
1434 	u_int i;
1435 	uint32_t initidx, targ_lun;
1436 
1437 	if (len < offsetof(struct ctl_ha_msg_mode, data[0])) {
1438 		printf("%s: Received truncated message %d < %zu\n",
1439 		    __func__, len, offsetof(struct ctl_ha_msg_mode, data[0]));
1440 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1441 		return;
1442 	}
1443 	i = msg->mode.page_len;
1444 	if (len < offsetof(struct ctl_ha_msg_mode, data[i])) {
1445 		printf("%s: Received truncated message data %d < %zu\n",
1446 		    __func__, len, offsetof(struct ctl_ha_msg_mode, data[i]));
1447 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1448 		return;
1449 	}
1450 
1451 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1452 	mtx_lock(&softc->ctl_lock);
1453 	if (targ_lun >= ctl_max_luns ||
1454 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1455 		mtx_unlock(&softc->ctl_lock);
1456 		return;
1457 	}
1458 	mtx_lock(&lun->lun_lock);
1459 	mtx_unlock(&softc->ctl_lock);
1460 	if (lun->flags & CTL_LUN_DISABLED) {
1461 		mtx_unlock(&lun->lun_lock);
1462 		return;
1463 	}
1464 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1465 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1466 		    msg->mode.page_code &&
1467 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1468 			break;
1469 	}
1470 	if (i == CTL_NUM_MODE_PAGES) {
1471 		mtx_unlock(&lun->lun_lock);
1472 		return;
1473 	}
1474 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1475 	    min(lun->mode_pages.index[i].page_len, msg->mode.page_len));
1476 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1477 	if (initidx != -1)
1478 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1479 	mtx_unlock(&lun->lun_lock);
1480 }
1481 
1482 /*
1483  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1484  * subsystem come in here.
1485  */
1486 static void
1487 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1488 {
1489 	struct ctl_softc *softc = control_softc;
1490 	union ctl_io *io;
1491 	struct ctl_prio *presio;
1492 	ctl_ha_status isc_status;
1493 
1494 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1495 	if (event == CTL_HA_EVT_MSG_RECV) {
1496 		union ctl_ha_msg *msg, msgbuf;
1497 
1498 		if (param > sizeof(msgbuf))
1499 			msg = malloc(param, M_CTL, M_WAITOK);
1500 		else
1501 			msg = &msgbuf;
1502 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1503 		    M_WAITOK);
1504 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1505 			printf("%s: Error receiving message: %d\n",
1506 			    __func__, isc_status);
1507 			if (msg != &msgbuf)
1508 				free(msg, M_CTL);
1509 			return;
1510 		}
1511 
1512 		CTL_DEBUG_PRINT(("CTL: msg_type %d len %d\n",
1513 		    msg->hdr.msg_type, param));
1514 		switch (msg->hdr.msg_type) {
1515 		case CTL_MSG_SERIALIZE:
1516 			io = ctl_alloc_io(softc->othersc_pool);
1517 			ctl_zero_io(io);
1518 			// populate ctsio from msg
1519 			io->io_hdr.io_type = CTL_IO_SCSI;
1520 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1521 			io->io_hdr.remote_io = msg->hdr.original_sc;
1522 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1523 					    CTL_FLAG_IO_ACTIVE;
1524 			/*
1525 			 * If we're in serialization-only mode, we don't
1526 			 * want to go through full done processing.  Thus
1527 			 * the COPY flag.
1528 			 *
1529 			 * XXX KDM add another flag that is more specific.
1530 			 */
1531 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1532 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1533 			io->io_hdr.nexus = msg->hdr.nexus;
1534 			io->scsiio.priority = msg->scsi.priority;
1535 			io->scsiio.tag_num = msg->scsi.tag_num;
1536 			io->scsiio.tag_type = msg->scsi.tag_type;
1537 #ifdef CTL_TIME_IO
1538 			io->io_hdr.start_time = time_uptime;
1539 			getbinuptime(&io->io_hdr.start_bt);
1540 #endif /* CTL_TIME_IO */
1541 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1542 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1543 			       CTL_MAX_CDBLEN);
1544 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1545 				const struct ctl_cmd_entry *entry;
1546 
1547 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1548 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1549 				io->io_hdr.flags |=
1550 					entry->flags & CTL_FLAG_DATA_MASK;
1551 			}
1552 			ctl_enqueue_isc(io);
1553 			break;
1554 
1555 		/* Performed on the Originating SC, XFER mode only */
1556 		case CTL_MSG_DATAMOVE: {
1557 			struct ctl_sg_entry *sgl;
1558 			int i, j;
1559 
1560 			io = msg->hdr.original_sc;
1561 			if (io == NULL) {
1562 				printf("%s: original_sc == NULL!\n", __func__);
1563 				/* XXX KDM do something here */
1564 				break;
1565 			}
1566 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1567 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1568 			/*
1569 			 * Keep track of this, we need to send it back over
1570 			 * when the datamove is complete.
1571 			 */
1572 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1573 			if (msg->hdr.status == CTL_SUCCESS)
1574 				io->io_hdr.status = msg->hdr.status;
1575 
1576 			if (msg->dt.sg_sequence == 0) {
1577 #ifdef CTL_TIME_IO
1578 				getbinuptime(&io->io_hdr.dma_start_bt);
1579 #endif
1580 				i = msg->dt.kern_sg_entries +
1581 				    msg->dt.kern_data_len /
1582 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1583 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1584 				    M_WAITOK | M_ZERO);
1585 				CTL_RSGL(io) = sgl;
1586 				CTL_LSGL(io) = &sgl[msg->dt.kern_sg_entries];
1587 
1588 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1589 
1590 				io->scsiio.kern_sg_entries =
1591 					msg->dt.kern_sg_entries;
1592 				io->scsiio.rem_sg_entries =
1593 					msg->dt.kern_sg_entries;
1594 				io->scsiio.kern_data_len =
1595 					msg->dt.kern_data_len;
1596 				io->scsiio.kern_total_len =
1597 					msg->dt.kern_total_len;
1598 				io->scsiio.kern_data_resid =
1599 					msg->dt.kern_data_resid;
1600 				io->scsiio.kern_rel_offset =
1601 					msg->dt.kern_rel_offset;
1602 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1603 				io->io_hdr.flags |= msg->dt.flags &
1604 				    CTL_FLAG_BUS_ADDR;
1605 			} else
1606 				sgl = (struct ctl_sg_entry *)
1607 					io->scsiio.kern_data_ptr;
1608 
1609 			for (i = msg->dt.sent_sg_entries, j = 0;
1610 			     i < (msg->dt.sent_sg_entries +
1611 			     msg->dt.cur_sg_entries); i++, j++) {
1612 				sgl[i].addr = msg->dt.sg_list[j].addr;
1613 				sgl[i].len = msg->dt.sg_list[j].len;
1614 			}
1615 
1616 			/*
1617 			 * If this is the last piece of the I/O, we've got
1618 			 * the full S/G list.  Queue processing in the thread.
1619 			 * Otherwise wait for the next piece.
1620 			 */
1621 			if (msg->dt.sg_last != 0)
1622 				ctl_enqueue_isc(io);
1623 			break;
1624 		}
1625 		/* Performed on the Serializing (primary) SC, XFER mode only */
1626 		case CTL_MSG_DATAMOVE_DONE: {
1627 			if (msg->hdr.serializing_sc == NULL) {
1628 				printf("%s: serializing_sc == NULL!\n",
1629 				       __func__);
1630 				/* XXX KDM now what? */
1631 				break;
1632 			}
1633 			/*
1634 			 * We grab the sense information here in case
1635 			 * there was a failure, so we can return status
1636 			 * back to the initiator.
1637 			 */
1638 			io = msg->hdr.serializing_sc;
1639 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1640 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1641 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1642 			io->io_hdr.port_status = msg->scsi.port_status;
1643 			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1644 			if (msg->hdr.status != CTL_STATUS_NONE) {
1645 				io->io_hdr.status = msg->hdr.status;
1646 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1647 				io->scsiio.sense_len = msg->scsi.sense_len;
1648 				memcpy(&io->scsiio.sense_data,
1649 				    &msg->scsi.sense_data,
1650 				    msg->scsi.sense_len);
1651 				if (msg->hdr.status == CTL_SUCCESS)
1652 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1653 			}
1654 			ctl_enqueue_isc(io);
1655 			break;
1656 		}
1657 
1658 		/* Preformed on Originating SC, SER_ONLY mode */
1659 		case CTL_MSG_R2R:
1660 			io = msg->hdr.original_sc;
1661 			if (io == NULL) {
1662 				printf("%s: original_sc == NULL!\n",
1663 				    __func__);
1664 				break;
1665 			}
1666 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1667 			io->io_hdr.msg_type = CTL_MSG_R2R;
1668 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1669 			ctl_enqueue_isc(io);
1670 			break;
1671 
1672 		/*
1673 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1674 		 * mode.
1675 		 * Performed on the Originating (i.e. secondary) SC in XFER
1676 		 * mode
1677 		 */
1678 		case CTL_MSG_FINISH_IO:
1679 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1680 				ctl_isc_handler_finish_xfer(softc, msg);
1681 			else
1682 				ctl_isc_handler_finish_ser_only(softc, msg);
1683 			break;
1684 
1685 		/* Preformed on Originating SC */
1686 		case CTL_MSG_BAD_JUJU:
1687 			io = msg->hdr.original_sc;
1688 			if (io == NULL) {
1689 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1690 				       __func__);
1691 				break;
1692 			}
1693 			ctl_copy_sense_data(msg, io);
1694 			/*
1695 			 * IO should have already been cleaned up on other
1696 			 * SC so clear this flag so we won't send a message
1697 			 * back to finish the IO there.
1698 			 */
1699 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1700 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1701 
1702 			/* io = msg->hdr.serializing_sc; */
1703 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1704 			ctl_enqueue_isc(io);
1705 			break;
1706 
1707 		/* Handle resets sent from the other side */
1708 		case CTL_MSG_MANAGE_TASKS: {
1709 			struct ctl_taskio *taskio;
1710 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1711 			    softc->othersc_pool);
1712 			ctl_zero_io((union ctl_io *)taskio);
1713 			taskio->io_hdr.io_type = CTL_IO_TASK;
1714 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1715 			taskio->io_hdr.nexus = msg->hdr.nexus;
1716 			taskio->task_action = msg->task.task_action;
1717 			taskio->tag_num = msg->task.tag_num;
1718 			taskio->tag_type = msg->task.tag_type;
1719 #ifdef CTL_TIME_IO
1720 			taskio->io_hdr.start_time = time_uptime;
1721 			getbinuptime(&taskio->io_hdr.start_bt);
1722 #endif /* CTL_TIME_IO */
1723 			ctl_run_task((union ctl_io *)taskio);
1724 			break;
1725 		}
1726 		/* Persistent Reserve action which needs attention */
1727 		case CTL_MSG_PERS_ACTION:
1728 			presio = (struct ctl_prio *)ctl_alloc_io(
1729 			    softc->othersc_pool);
1730 			ctl_zero_io((union ctl_io *)presio);
1731 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1732 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1733 			presio->io_hdr.nexus = msg->hdr.nexus;
1734 			presio->pr_msg = msg->pr;
1735 			ctl_enqueue_isc((union ctl_io *)presio);
1736 			break;
1737 		case CTL_MSG_UA:
1738 			ctl_isc_ua(softc, msg, param);
1739 			break;
1740 		case CTL_MSG_PORT_SYNC:
1741 			ctl_isc_port_sync(softc, msg, param);
1742 			break;
1743 		case CTL_MSG_LUN_SYNC:
1744 			ctl_isc_lun_sync(softc, msg, param);
1745 			break;
1746 		case CTL_MSG_IID_SYNC:
1747 			ctl_isc_iid_sync(softc, msg, param);
1748 			break;
1749 		case CTL_MSG_LOGIN:
1750 			ctl_isc_login(softc, msg, param);
1751 			break;
1752 		case CTL_MSG_MODE_SYNC:
1753 			ctl_isc_mode_sync(softc, msg, param);
1754 			break;
1755 		default:
1756 			printf("Received HA message of unknown type %d\n",
1757 			    msg->hdr.msg_type);
1758 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1759 			break;
1760 		}
1761 		if (msg != &msgbuf)
1762 			free(msg, M_CTL);
1763 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1764 		printf("CTL: HA link status changed from %d to %d\n",
1765 		    softc->ha_link, param);
1766 		if (param == softc->ha_link)
1767 			return;
1768 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1769 			softc->ha_link = param;
1770 			ctl_isc_ha_link_down(softc);
1771 		} else {
1772 			softc->ha_link = param;
1773 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1774 				ctl_isc_ha_link_up(softc);
1775 		}
1776 		return;
1777 	} else {
1778 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1779 		return;
1780 	}
1781 }
1782 
1783 static void
1784 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1785 {
1786 
1787 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1788 	    src->scsi.sense_len);
1789 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1790 	dest->scsiio.sense_len = src->scsi.sense_len;
1791 	dest->io_hdr.status = src->hdr.status;
1792 }
1793 
1794 static void
1795 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1796 {
1797 
1798 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1799 	    src->scsiio.sense_len);
1800 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1801 	dest->scsi.sense_len = src->scsiio.sense_len;
1802 	dest->hdr.status = src->io_hdr.status;
1803 }
1804 
1805 void
1806 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1807 {
1808 	struct ctl_softc *softc = lun->ctl_softc;
1809 	ctl_ua_type *pu;
1810 
1811 	if (initidx < softc->init_min || initidx >= softc->init_max)
1812 		return;
1813 	mtx_assert(&lun->lun_lock, MA_OWNED);
1814 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1815 	if (pu == NULL)
1816 		return;
1817 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1818 }
1819 
1820 void
1821 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1822 {
1823 	int i;
1824 
1825 	mtx_assert(&lun->lun_lock, MA_OWNED);
1826 	if (lun->pending_ua[port] == NULL)
1827 		return;
1828 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1829 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1830 			continue;
1831 		lun->pending_ua[port][i] |= ua;
1832 	}
1833 }
1834 
1835 void
1836 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1837 {
1838 	struct ctl_softc *softc = lun->ctl_softc;
1839 	int i;
1840 
1841 	mtx_assert(&lun->lun_lock, MA_OWNED);
1842 	for (i = softc->port_min; i < softc->port_max; i++)
1843 		ctl_est_ua_port(lun, i, except, ua);
1844 }
1845 
1846 void
1847 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1848 {
1849 	struct ctl_softc *softc = lun->ctl_softc;
1850 	ctl_ua_type *pu;
1851 
1852 	if (initidx < softc->init_min || initidx >= softc->init_max)
1853 		return;
1854 	mtx_assert(&lun->lun_lock, MA_OWNED);
1855 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1856 	if (pu == NULL)
1857 		return;
1858 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1859 }
1860 
1861 void
1862 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1863 {
1864 	struct ctl_softc *softc = lun->ctl_softc;
1865 	int i, j;
1866 
1867 	mtx_assert(&lun->lun_lock, MA_OWNED);
1868 	for (i = softc->port_min; i < softc->port_max; i++) {
1869 		if (lun->pending_ua[i] == NULL)
1870 			continue;
1871 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1872 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1873 				continue;
1874 			lun->pending_ua[i][j] &= ~ua;
1875 		}
1876 	}
1877 }
1878 
1879 void
1880 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1881     ctl_ua_type ua_type)
1882 {
1883 	struct ctl_lun *lun;
1884 
1885 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1886 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1887 		mtx_lock(&lun->lun_lock);
1888 		ctl_clr_ua(lun, initidx, ua_type);
1889 		mtx_unlock(&lun->lun_lock);
1890 	}
1891 }
1892 
1893 static int
1894 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1895 {
1896 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1897 	struct ctl_lun *lun;
1898 	struct ctl_lun_req ireq;
1899 	int error, value;
1900 
1901 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1902 	error = sysctl_handle_int(oidp, &value, 0, req);
1903 	if ((error != 0) || (req->newptr == NULL))
1904 		return (error);
1905 
1906 	mtx_lock(&softc->ctl_lock);
1907 	if (value == 0)
1908 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1909 	else
1910 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1911 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1912 		mtx_unlock(&softc->ctl_lock);
1913 		bzero(&ireq, sizeof(ireq));
1914 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1915 		ireq.reqdata.modify.lun_id = lun->lun;
1916 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1917 		    curthread);
1918 		if (ireq.status != CTL_LUN_OK) {
1919 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1920 			    __func__, ireq.status, ireq.error_str);
1921 		}
1922 		mtx_lock(&softc->ctl_lock);
1923 	}
1924 	mtx_unlock(&softc->ctl_lock);
1925 	return (0);
1926 }
1927 
1928 static int
1929 ctl_init(void)
1930 {
1931 	struct make_dev_args args;
1932 	struct ctl_softc *softc;
1933 	int i, error;
1934 
1935 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1936 			       M_WAITOK | M_ZERO);
1937 
1938 	make_dev_args_init(&args);
1939 	args.mda_devsw = &ctl_cdevsw;
1940 	args.mda_uid = UID_ROOT;
1941 	args.mda_gid = GID_OPERATOR;
1942 	args.mda_mode = 0600;
1943 	args.mda_si_drv1 = softc;
1944 	args.mda_si_drv2 = NULL;
1945 	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1946 	if (error != 0) {
1947 		free(softc, M_DEVBUF);
1948 		control_softc = NULL;
1949 		return (error);
1950 	}
1951 
1952 	sysctl_ctx_init(&softc->sysctl_ctx);
1953 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1954 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1955 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "CAM Target Layer");
1956 
1957 	if (softc->sysctl_tree == NULL) {
1958 		printf("%s: unable to allocate sysctl tree\n", __func__);
1959 		destroy_dev(softc->dev);
1960 		free(softc, M_DEVBUF);
1961 		control_softc = NULL;
1962 		return (ENOMEM);
1963 	}
1964 
1965 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1966 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1967 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1968 	softc->flags = 0;
1969 
1970 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1971 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1972 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1973 
1974 	if (ctl_max_luns <= 0 || powerof2(ctl_max_luns) == 0) {
1975 		printf("Bad value %d for kern.cam.ctl.max_luns, must be a power of two, using %d\n",
1976 		    ctl_max_luns, CTL_DEFAULT_MAX_LUNS);
1977 		ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
1978 	}
1979 	softc->ctl_luns = malloc(sizeof(struct ctl_lun *) * ctl_max_luns,
1980 	    M_DEVBUF, M_WAITOK | M_ZERO);
1981 	softc->ctl_lun_mask = malloc(sizeof(uint32_t) *
1982 	    ((ctl_max_luns + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1983 	if (ctl_max_ports <= 0 || powerof2(ctl_max_ports) == 0) {
1984 		printf("Bad value %d for kern.cam.ctl.max_ports, must be a power of two, using %d\n",
1985 		    ctl_max_ports, CTL_DEFAULT_MAX_PORTS);
1986 		ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
1987 	}
1988 	softc->ctl_port_mask = malloc(sizeof(uint32_t) *
1989 	  ((ctl_max_ports + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1990 	softc->ctl_ports = malloc(sizeof(struct ctl_port *) * ctl_max_ports,
1991 	     M_DEVBUF, M_WAITOK | M_ZERO);
1992 
1993 	/*
1994 	 * In Copan's HA scheme, the "master" and "slave" roles are
1995 	 * figured out through the slot the controller is in.  Although it
1996 	 * is an active/active system, someone has to be in charge.
1997 	 */
1998 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1999 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
2000 	    "HA head ID (0 - no HA)");
2001 	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
2002 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
2003 		softc->is_single = 1;
2004 		softc->port_cnt = ctl_max_ports;
2005 		softc->port_min = 0;
2006 	} else {
2007 		softc->port_cnt = ctl_max_ports / NUM_HA_SHELVES;
2008 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
2009 	}
2010 	softc->port_max = softc->port_min + softc->port_cnt;
2011 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
2012 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
2013 
2014 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2015 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
2016 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
2017 
2018 	STAILQ_INIT(&softc->lun_list);
2019 	STAILQ_INIT(&softc->fe_list);
2020 	STAILQ_INIT(&softc->port_list);
2021 	STAILQ_INIT(&softc->be_list);
2022 	ctl_tpc_init(softc);
2023 
2024 	if (worker_threads <= 0)
2025 		worker_threads = max(1, mp_ncpus / 4);
2026 	if (worker_threads > CTL_MAX_THREADS)
2027 		worker_threads = CTL_MAX_THREADS;
2028 
2029 	for (i = 0; i < worker_threads; i++) {
2030 		struct ctl_thread *thr = &softc->threads[i];
2031 
2032 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
2033 		thr->ctl_softc = softc;
2034 		STAILQ_INIT(&thr->incoming_queue);
2035 		STAILQ_INIT(&thr->rtr_queue);
2036 		STAILQ_INIT(&thr->done_queue);
2037 		STAILQ_INIT(&thr->isc_queue);
2038 
2039 		error = kproc_kthread_add(ctl_work_thread, thr,
2040 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
2041 		if (error != 0) {
2042 			printf("error creating CTL work thread!\n");
2043 			return (error);
2044 		}
2045 	}
2046 	error = kproc_kthread_add(ctl_thresh_thread, softc,
2047 	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
2048 	if (error != 0) {
2049 		printf("error creating CTL threshold thread!\n");
2050 		return (error);
2051 	}
2052 
2053 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
2054 	    OID_AUTO, "ha_role",
2055 	    CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
2056 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
2057 
2058 	if (softc->is_single == 0) {
2059 		if (ctl_frontend_register(&ha_frontend) != 0)
2060 			softc->is_single = 1;
2061 	}
2062 	return (0);
2063 }
2064 
2065 static int
2066 ctl_shutdown(void)
2067 {
2068 	struct ctl_softc *softc = control_softc;
2069 	int i;
2070 
2071 	if (softc->is_single == 0)
2072 		ctl_frontend_deregister(&ha_frontend);
2073 
2074 	destroy_dev(softc->dev);
2075 
2076 	/* Shutdown CTL threads. */
2077 	softc->shutdown = 1;
2078 	for (i = 0; i < worker_threads; i++) {
2079 		struct ctl_thread *thr = &softc->threads[i];
2080 		while (thr->thread != NULL) {
2081 			wakeup(thr);
2082 			if (thr->thread != NULL)
2083 				pause("CTL thr shutdown", 1);
2084 		}
2085 		mtx_destroy(&thr->queue_lock);
2086 	}
2087 	while (softc->thresh_thread != NULL) {
2088 		wakeup(softc->thresh_thread);
2089 		if (softc->thresh_thread != NULL)
2090 			pause("CTL thr shutdown", 1);
2091 	}
2092 
2093 	ctl_tpc_shutdown(softc);
2094 	uma_zdestroy(softc->io_zone);
2095 	mtx_destroy(&softc->ctl_lock);
2096 
2097 	free(softc->ctl_luns, M_DEVBUF);
2098 	free(softc->ctl_lun_mask, M_DEVBUF);
2099 	free(softc->ctl_port_mask, M_DEVBUF);
2100 	free(softc->ctl_ports, M_DEVBUF);
2101 
2102 	sysctl_ctx_free(&softc->sysctl_ctx);
2103 
2104 	free(softc, M_DEVBUF);
2105 	control_softc = NULL;
2106 	return (0);
2107 }
2108 
2109 static int
2110 ctl_module_event_handler(module_t mod, int what, void *arg)
2111 {
2112 
2113 	switch (what) {
2114 	case MOD_LOAD:
2115 		return (ctl_init());
2116 	case MOD_UNLOAD:
2117 		return (ctl_shutdown());
2118 	default:
2119 		return (EOPNOTSUPP);
2120 	}
2121 }
2122 
2123 /*
2124  * XXX KDM should we do some access checks here?  Bump a reference count to
2125  * prevent a CTL module from being unloaded while someone has it open?
2126  */
2127 static int
2128 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2129 {
2130 	return (0);
2131 }
2132 
2133 static int
2134 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2135 {
2136 	return (0);
2137 }
2138 
2139 /*
2140  * Remove an initiator by port number and initiator ID.
2141  * Returns 0 for success, -1 for failure.
2142  */
2143 int
2144 ctl_remove_initiator(struct ctl_port *port, int iid)
2145 {
2146 	struct ctl_softc *softc = port->ctl_softc;
2147 	int last;
2148 
2149 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2150 
2151 	if (iid > CTL_MAX_INIT_PER_PORT) {
2152 		printf("%s: initiator ID %u > maximun %u!\n",
2153 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2154 		return (-1);
2155 	}
2156 
2157 	mtx_lock(&softc->ctl_lock);
2158 	last = (--port->wwpn_iid[iid].in_use == 0);
2159 	port->wwpn_iid[iid].last_use = time_uptime;
2160 	mtx_unlock(&softc->ctl_lock);
2161 	if (last)
2162 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2163 	ctl_isc_announce_iid(port, iid);
2164 
2165 	return (0);
2166 }
2167 
2168 /*
2169  * Add an initiator to the initiator map.
2170  * Returns iid for success, < 0 for failure.
2171  */
2172 int
2173 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2174 {
2175 	struct ctl_softc *softc = port->ctl_softc;
2176 	time_t best_time;
2177 	int i, best;
2178 
2179 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2180 
2181 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2182 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2183 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2184 		free(name, M_CTL);
2185 		return (-1);
2186 	}
2187 
2188 	mtx_lock(&softc->ctl_lock);
2189 
2190 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2191 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2192 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2193 				iid = i;
2194 				break;
2195 			}
2196 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2197 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2198 				iid = i;
2199 				break;
2200 			}
2201 		}
2202 	}
2203 
2204 	if (iid < 0) {
2205 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2206 			if (port->wwpn_iid[i].in_use == 0 &&
2207 			    port->wwpn_iid[i].wwpn == 0 &&
2208 			    port->wwpn_iid[i].name == NULL) {
2209 				iid = i;
2210 				break;
2211 			}
2212 		}
2213 	}
2214 
2215 	if (iid < 0) {
2216 		best = -1;
2217 		best_time = INT32_MAX;
2218 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2219 			if (port->wwpn_iid[i].in_use == 0) {
2220 				if (port->wwpn_iid[i].last_use < best_time) {
2221 					best = i;
2222 					best_time = port->wwpn_iid[i].last_use;
2223 				}
2224 			}
2225 		}
2226 		iid = best;
2227 	}
2228 
2229 	if (iid < 0) {
2230 		mtx_unlock(&softc->ctl_lock);
2231 		free(name, M_CTL);
2232 		return (-2);
2233 	}
2234 
2235 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2236 		/*
2237 		 * This is not an error yet.
2238 		 */
2239 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2240 #if 0
2241 			printf("%s: port %d iid %u WWPN %#jx arrived"
2242 			    " again\n", __func__, port->targ_port,
2243 			    iid, (uintmax_t)wwpn);
2244 #endif
2245 			goto take;
2246 		}
2247 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2248 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2249 #if 0
2250 			printf("%s: port %d iid %u name '%s' arrived"
2251 			    " again\n", __func__, port->targ_port,
2252 			    iid, name);
2253 #endif
2254 			goto take;
2255 		}
2256 
2257 		/*
2258 		 * This is an error, but what do we do about it?  The
2259 		 * driver is telling us we have a new WWPN for this
2260 		 * initiator ID, so we pretty much need to use it.
2261 		 */
2262 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2263 		    " but WWPN %#jx '%s' is still at that address\n",
2264 		    __func__, port->targ_port, iid, wwpn, name,
2265 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2266 		    port->wwpn_iid[iid].name);
2267 	}
2268 take:
2269 	free(port->wwpn_iid[iid].name, M_CTL);
2270 	port->wwpn_iid[iid].name = name;
2271 	port->wwpn_iid[iid].wwpn = wwpn;
2272 	port->wwpn_iid[iid].in_use++;
2273 	mtx_unlock(&softc->ctl_lock);
2274 	ctl_isc_announce_iid(port, iid);
2275 
2276 	return (iid);
2277 }
2278 
2279 static int
2280 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2281 {
2282 	int len;
2283 
2284 	switch (port->port_type) {
2285 	case CTL_PORT_FC:
2286 	{
2287 		struct scsi_transportid_fcp *id =
2288 		    (struct scsi_transportid_fcp *)buf;
2289 		if (port->wwpn_iid[iid].wwpn == 0)
2290 			return (0);
2291 		memset(id, 0, sizeof(*id));
2292 		id->format_protocol = SCSI_PROTO_FC;
2293 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2294 		return (sizeof(*id));
2295 	}
2296 	case CTL_PORT_ISCSI:
2297 	{
2298 		struct scsi_transportid_iscsi_port *id =
2299 		    (struct scsi_transportid_iscsi_port *)buf;
2300 		if (port->wwpn_iid[iid].name == NULL)
2301 			return (0);
2302 		memset(id, 0, 256);
2303 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2304 		    SCSI_PROTO_ISCSI;
2305 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2306 		len = roundup2(min(len, 252), 4);
2307 		scsi_ulto2b(len, id->additional_length);
2308 		return (sizeof(*id) + len);
2309 	}
2310 	case CTL_PORT_SAS:
2311 	{
2312 		struct scsi_transportid_sas *id =
2313 		    (struct scsi_transportid_sas *)buf;
2314 		if (port->wwpn_iid[iid].wwpn == 0)
2315 			return (0);
2316 		memset(id, 0, sizeof(*id));
2317 		id->format_protocol = SCSI_PROTO_SAS;
2318 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2319 		return (sizeof(*id));
2320 	}
2321 	default:
2322 	{
2323 		struct scsi_transportid_spi *id =
2324 		    (struct scsi_transportid_spi *)buf;
2325 		memset(id, 0, sizeof(*id));
2326 		id->format_protocol = SCSI_PROTO_SPI;
2327 		scsi_ulto2b(iid, id->scsi_addr);
2328 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2329 		return (sizeof(*id));
2330 	}
2331 	}
2332 }
2333 
2334 /*
2335  * Serialize a command that went down the "wrong" side, and so was sent to
2336  * this controller for execution.  The logic is a little different than the
2337  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2338  * sent back to the other side, but in the success case, we execute the
2339  * command on this side (XFER mode) or tell the other side to execute it
2340  * (SER_ONLY mode).
2341  */
2342 static void
2343 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2344 {
2345 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2346 	struct ctl_port *port = CTL_PORT(ctsio);
2347 	union ctl_ha_msg msg_info;
2348 	struct ctl_lun *lun;
2349 	const struct ctl_cmd_entry *entry;
2350 	union ctl_io *bio;
2351 	uint32_t targ_lun;
2352 
2353 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2354 
2355 	/* Make sure that we know about this port. */
2356 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2357 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2358 					 /*retry_count*/ 1);
2359 		goto badjuju;
2360 	}
2361 
2362 	/* Make sure that we know about this LUN. */
2363 	mtx_lock(&softc->ctl_lock);
2364 	if (targ_lun >= ctl_max_luns ||
2365 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2366 		mtx_unlock(&softc->ctl_lock);
2367 
2368 		/*
2369 		 * The other node would not send this request to us unless
2370 		 * received announce that we are primary node for this LUN.
2371 		 * If this LUN does not exist now, it is probably result of
2372 		 * a race, so respond to initiator in the most opaque way.
2373 		 */
2374 		ctl_set_busy(ctsio);
2375 		goto badjuju;
2376 	}
2377 	mtx_lock(&lun->lun_lock);
2378 	mtx_unlock(&softc->ctl_lock);
2379 
2380 	/*
2381 	 * If the LUN is invalid, pretend that it doesn't exist.
2382 	 * It will go away as soon as all pending I/Os completed.
2383 	 */
2384 	if (lun->flags & CTL_LUN_DISABLED) {
2385 		mtx_unlock(&lun->lun_lock);
2386 		ctl_set_busy(ctsio);
2387 		goto badjuju;
2388 	}
2389 
2390 	entry = ctl_get_cmd_entry(ctsio, NULL);
2391 	ctsio->seridx = entry->seridx;
2392 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2393 		mtx_unlock(&lun->lun_lock);
2394 		goto badjuju;
2395 	}
2396 
2397 	CTL_LUN(ctsio) = lun;
2398 	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2399 
2400 	/*
2401 	 * Every I/O goes into the OOA queue for a
2402 	 * particular LUN, and stays there until completion.
2403 	 */
2404 #ifdef CTL_TIME_IO
2405 	if (LIST_EMPTY(&lun->ooa_queue))
2406 		lun->idle_time += getsbinuptime() - lun->last_busy;
2407 #endif
2408 	LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2409 
2410 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
2411 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
2412 	case CTL_ACTION_PASS:
2413 	case CTL_ACTION_SKIP:
2414 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2415 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2416 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2417 			mtx_unlock(&lun->lun_lock);
2418 		} else {
2419 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2420 			mtx_unlock(&lun->lun_lock);
2421 
2422 			/* send msg back to other side */
2423 			msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2424 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2425 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2426 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2427 			    sizeof(msg_info.hdr), M_WAITOK);
2428 		}
2429 		break;
2430 	case CTL_ACTION_BLOCK:
2431 		ctsio->io_hdr.blocker = bio;
2432 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
2433 				  blocked_links);
2434 		mtx_unlock(&lun->lun_lock);
2435 		break;
2436 	case CTL_ACTION_OVERLAP:
2437 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2438 		mtx_unlock(&lun->lun_lock);
2439 		ctl_set_overlapped_cmd(ctsio);
2440 		goto badjuju;
2441 	case CTL_ACTION_OVERLAP_TAG:
2442 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2443 		mtx_unlock(&lun->lun_lock);
2444 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
2445 badjuju:
2446 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2447 		msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2448 		msg_info.hdr.serializing_sc = NULL;
2449 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2450 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2451 		    sizeof(msg_info.scsi), M_WAITOK);
2452 		ctl_free_io((union ctl_io *)ctsio);
2453 		break;
2454 	default:
2455 		__assert_unreachable();
2456 	}
2457 }
2458 
2459 /*
2460  * Returns 0 for success, errno for failure.
2461  */
2462 static void
2463 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2464 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2465 {
2466 	struct ctl_io_hdr *ioh;
2467 
2468 	mtx_lock(&lun->lun_lock);
2469 	ioh = LIST_FIRST(&lun->ooa_queue);
2470 	if (ioh == NULL) {
2471 		mtx_unlock(&lun->lun_lock);
2472 		return;
2473 	}
2474 	while (LIST_NEXT(ioh, ooa_links) != NULL)
2475 		ioh = LIST_NEXT(ioh, ooa_links);
2476 	for ( ; ioh; ioh = LIST_PREV(ioh, &lun->ooa_queue, ctl_io_hdr, ooa_links)) {
2477 		union ctl_io *io = (union ctl_io *)ioh;
2478 		struct ctl_ooa_entry *entry;
2479 
2480 		/*
2481 		 * If we've got more than we can fit, just count the
2482 		 * remaining entries.
2483 		 */
2484 		if (*cur_fill_num >= ooa_hdr->alloc_num) {
2485 			(*cur_fill_num)++;
2486 			continue;
2487 		}
2488 
2489 		entry = &kern_entries[*cur_fill_num];
2490 
2491 		entry->tag_num = io->scsiio.tag_num;
2492 		entry->tag_type = io->scsiio.tag_type;
2493 		entry->lun_num = lun->lun;
2494 #ifdef CTL_TIME_IO
2495 		entry->start_bt = io->io_hdr.start_bt;
2496 #endif
2497 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2498 		entry->cdb_len = io->scsiio.cdb_len;
2499 		if (io->io_hdr.blocker != NULL)
2500 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2501 
2502 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2503 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2504 
2505 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2506 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2507 
2508 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2509 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2510 
2511 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2512 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2513 
2514 		if (io->io_hdr.flags & CTL_FLAG_STATUS_QUEUED)
2515 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_QUEUED;
2516 
2517 		if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT)
2518 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_SENT;
2519 		(*cur_fill_num)++;
2520 	}
2521 	mtx_unlock(&lun->lun_lock);
2522 }
2523 
2524 /*
2525  * Escape characters that are illegal or not recommended in XML.
2526  */
2527 int
2528 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2529 {
2530 	char *end = str + size;
2531 	int retval;
2532 
2533 	retval = 0;
2534 
2535 	for (; *str && str < end; str++) {
2536 		switch (*str) {
2537 		case '&':
2538 			retval = sbuf_printf(sb, "&amp;");
2539 			break;
2540 		case '>':
2541 			retval = sbuf_printf(sb, "&gt;");
2542 			break;
2543 		case '<':
2544 			retval = sbuf_printf(sb, "&lt;");
2545 			break;
2546 		default:
2547 			retval = sbuf_putc(sb, *str);
2548 			break;
2549 		}
2550 
2551 		if (retval != 0)
2552 			break;
2553 	}
2554 
2555 	return (retval);
2556 }
2557 
2558 static void
2559 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2560 {
2561 	struct scsi_vpd_id_descriptor *desc;
2562 	int i;
2563 
2564 	if (id == NULL || id->len < 4)
2565 		return;
2566 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2567 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2568 	case SVPD_ID_TYPE_T10:
2569 		sbuf_printf(sb, "t10.");
2570 		break;
2571 	case SVPD_ID_TYPE_EUI64:
2572 		sbuf_printf(sb, "eui.");
2573 		break;
2574 	case SVPD_ID_TYPE_NAA:
2575 		sbuf_printf(sb, "naa.");
2576 		break;
2577 	case SVPD_ID_TYPE_SCSI_NAME:
2578 		break;
2579 	}
2580 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2581 	case SVPD_ID_CODESET_BINARY:
2582 		for (i = 0; i < desc->length; i++)
2583 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2584 		break;
2585 	case SVPD_ID_CODESET_ASCII:
2586 		sbuf_printf(sb, "%.*s", (int)desc->length,
2587 		    (char *)desc->identifier);
2588 		break;
2589 	case SVPD_ID_CODESET_UTF8:
2590 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2591 		break;
2592 	}
2593 }
2594 
2595 static int
2596 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2597 	  struct thread *td)
2598 {
2599 	struct ctl_softc *softc = dev->si_drv1;
2600 	struct ctl_port *port;
2601 	struct ctl_lun *lun;
2602 	int retval;
2603 
2604 	retval = 0;
2605 
2606 	switch (cmd) {
2607 	case CTL_IO:
2608 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2609 		break;
2610 	case CTL_ENABLE_PORT:
2611 	case CTL_DISABLE_PORT:
2612 	case CTL_SET_PORT_WWNS: {
2613 		struct ctl_port *port;
2614 		struct ctl_port_entry *entry;
2615 
2616 		entry = (struct ctl_port_entry *)addr;
2617 
2618 		mtx_lock(&softc->ctl_lock);
2619 		STAILQ_FOREACH(port, &softc->port_list, links) {
2620 			int action, done;
2621 
2622 			if (port->targ_port < softc->port_min ||
2623 			    port->targ_port >= softc->port_max)
2624 				continue;
2625 
2626 			action = 0;
2627 			done = 0;
2628 			if ((entry->port_type == CTL_PORT_NONE)
2629 			 && (entry->targ_port == port->targ_port)) {
2630 				/*
2631 				 * If the user only wants to enable or
2632 				 * disable or set WWNs on a specific port,
2633 				 * do the operation and we're done.
2634 				 */
2635 				action = 1;
2636 				done = 1;
2637 			} else if (entry->port_type & port->port_type) {
2638 				/*
2639 				 * Compare the user's type mask with the
2640 				 * particular frontend type to see if we
2641 				 * have a match.
2642 				 */
2643 				action = 1;
2644 				done = 0;
2645 
2646 				/*
2647 				 * Make sure the user isn't trying to set
2648 				 * WWNs on multiple ports at the same time.
2649 				 */
2650 				if (cmd == CTL_SET_PORT_WWNS) {
2651 					printf("%s: Can't set WWNs on "
2652 					       "multiple ports\n", __func__);
2653 					retval = EINVAL;
2654 					break;
2655 				}
2656 			}
2657 			if (action == 0)
2658 				continue;
2659 
2660 			/*
2661 			 * XXX KDM we have to drop the lock here, because
2662 			 * the online/offline operations can potentially
2663 			 * block.  We need to reference count the frontends
2664 			 * so they can't go away,
2665 			 */
2666 			if (cmd == CTL_ENABLE_PORT) {
2667 				mtx_unlock(&softc->ctl_lock);
2668 				ctl_port_online(port);
2669 				mtx_lock(&softc->ctl_lock);
2670 			} else if (cmd == CTL_DISABLE_PORT) {
2671 				mtx_unlock(&softc->ctl_lock);
2672 				ctl_port_offline(port);
2673 				mtx_lock(&softc->ctl_lock);
2674 			} else if (cmd == CTL_SET_PORT_WWNS) {
2675 				ctl_port_set_wwns(port,
2676 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2677 				    1 : 0, entry->wwnn,
2678 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2679 				    1 : 0, entry->wwpn);
2680 			}
2681 			if (done != 0)
2682 				break;
2683 		}
2684 		mtx_unlock(&softc->ctl_lock);
2685 		break;
2686 	}
2687 	case CTL_GET_OOA: {
2688 		struct ctl_ooa *ooa_hdr;
2689 		struct ctl_ooa_entry *entries;
2690 		uint32_t cur_fill_num;
2691 
2692 		ooa_hdr = (struct ctl_ooa *)addr;
2693 
2694 		if ((ooa_hdr->alloc_len == 0)
2695 		 || (ooa_hdr->alloc_num == 0)) {
2696 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2697 			       "must be non-zero\n", __func__,
2698 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2699 			retval = EINVAL;
2700 			break;
2701 		}
2702 
2703 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2704 		    sizeof(struct ctl_ooa_entry))) {
2705 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2706 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2707 			       __func__, ooa_hdr->alloc_len,
2708 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2709 			retval = EINVAL;
2710 			break;
2711 		}
2712 
2713 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2714 		if (entries == NULL) {
2715 			printf("%s: could not allocate %d bytes for OOA "
2716 			       "dump\n", __func__, ooa_hdr->alloc_len);
2717 			retval = ENOMEM;
2718 			break;
2719 		}
2720 
2721 		mtx_lock(&softc->ctl_lock);
2722 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2723 		    (ooa_hdr->lun_num >= ctl_max_luns ||
2724 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2725 			mtx_unlock(&softc->ctl_lock);
2726 			free(entries, M_CTL);
2727 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2728 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2729 			retval = EINVAL;
2730 			break;
2731 		}
2732 
2733 		cur_fill_num = 0;
2734 
2735 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2736 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2737 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2738 				    ooa_hdr, entries);
2739 			}
2740 		} else {
2741 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2742 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2743 			    entries);
2744 		}
2745 		mtx_unlock(&softc->ctl_lock);
2746 
2747 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2748 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2749 			sizeof(struct ctl_ooa_entry);
2750 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2751 		if (retval != 0) {
2752 			printf("%s: error copying out %d bytes for OOA dump\n",
2753 			       __func__, ooa_hdr->fill_len);
2754 		}
2755 
2756 		getbinuptime(&ooa_hdr->cur_bt);
2757 
2758 		if (cur_fill_num > ooa_hdr->alloc_num) {
2759 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2760 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2761 		} else {
2762 			ooa_hdr->dropped_num = 0;
2763 			ooa_hdr->status = CTL_OOA_OK;
2764 		}
2765 
2766 		free(entries, M_CTL);
2767 		break;
2768 	}
2769 	case CTL_DELAY_IO: {
2770 		struct ctl_io_delay_info *delay_info;
2771 
2772 		delay_info = (struct ctl_io_delay_info *)addr;
2773 
2774 #ifdef CTL_IO_DELAY
2775 		mtx_lock(&softc->ctl_lock);
2776 		if (delay_info->lun_id >= ctl_max_luns ||
2777 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2778 			mtx_unlock(&softc->ctl_lock);
2779 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2780 			break;
2781 		}
2782 		mtx_lock(&lun->lun_lock);
2783 		mtx_unlock(&softc->ctl_lock);
2784 		delay_info->status = CTL_DELAY_STATUS_OK;
2785 		switch (delay_info->delay_type) {
2786 		case CTL_DELAY_TYPE_CONT:
2787 		case CTL_DELAY_TYPE_ONESHOT:
2788 			break;
2789 		default:
2790 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2791 			break;
2792 		}
2793 		switch (delay_info->delay_loc) {
2794 		case CTL_DELAY_LOC_DATAMOVE:
2795 			lun->delay_info.datamove_type = delay_info->delay_type;
2796 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2797 			break;
2798 		case CTL_DELAY_LOC_DONE:
2799 			lun->delay_info.done_type = delay_info->delay_type;
2800 			lun->delay_info.done_delay = delay_info->delay_secs;
2801 			break;
2802 		default:
2803 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2804 			break;
2805 		}
2806 		mtx_unlock(&lun->lun_lock);
2807 #else
2808 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2809 #endif /* CTL_IO_DELAY */
2810 		break;
2811 	}
2812 	case CTL_ERROR_INJECT: {
2813 		struct ctl_error_desc *err_desc, *new_err_desc;
2814 
2815 		err_desc = (struct ctl_error_desc *)addr;
2816 
2817 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2818 				      M_WAITOK | M_ZERO);
2819 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2820 
2821 		mtx_lock(&softc->ctl_lock);
2822 		if (err_desc->lun_id >= ctl_max_luns ||
2823 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2824 			mtx_unlock(&softc->ctl_lock);
2825 			free(new_err_desc, M_CTL);
2826 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2827 			       __func__, (uintmax_t)err_desc->lun_id);
2828 			retval = EINVAL;
2829 			break;
2830 		}
2831 		mtx_lock(&lun->lun_lock);
2832 		mtx_unlock(&softc->ctl_lock);
2833 
2834 		/*
2835 		 * We could do some checking here to verify the validity
2836 		 * of the request, but given the complexity of error
2837 		 * injection requests, the checking logic would be fairly
2838 		 * complex.
2839 		 *
2840 		 * For now, if the request is invalid, it just won't get
2841 		 * executed and might get deleted.
2842 		 */
2843 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2844 
2845 		/*
2846 		 * XXX KDM check to make sure the serial number is unique,
2847 		 * in case we somehow manage to wrap.  That shouldn't
2848 		 * happen for a very long time, but it's the right thing to
2849 		 * do.
2850 		 */
2851 		new_err_desc->serial = lun->error_serial;
2852 		err_desc->serial = lun->error_serial;
2853 		lun->error_serial++;
2854 
2855 		mtx_unlock(&lun->lun_lock);
2856 		break;
2857 	}
2858 	case CTL_ERROR_INJECT_DELETE: {
2859 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2860 		int delete_done;
2861 
2862 		delete_desc = (struct ctl_error_desc *)addr;
2863 		delete_done = 0;
2864 
2865 		mtx_lock(&softc->ctl_lock);
2866 		if (delete_desc->lun_id >= ctl_max_luns ||
2867 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2868 			mtx_unlock(&softc->ctl_lock);
2869 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2870 			       __func__, (uintmax_t)delete_desc->lun_id);
2871 			retval = EINVAL;
2872 			break;
2873 		}
2874 		mtx_lock(&lun->lun_lock);
2875 		mtx_unlock(&softc->ctl_lock);
2876 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2877 			if (desc->serial != delete_desc->serial)
2878 				continue;
2879 
2880 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2881 				      links);
2882 			free(desc, M_CTL);
2883 			delete_done = 1;
2884 		}
2885 		mtx_unlock(&lun->lun_lock);
2886 		if (delete_done == 0) {
2887 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2888 			       "error serial %ju on LUN %u\n", __func__,
2889 			       delete_desc->serial, delete_desc->lun_id);
2890 			retval = EINVAL;
2891 			break;
2892 		}
2893 		break;
2894 	}
2895 	case CTL_DUMP_STRUCTS: {
2896 		int j, k;
2897 		struct ctl_port *port;
2898 		struct ctl_frontend *fe;
2899 
2900 		mtx_lock(&softc->ctl_lock);
2901 		printf("CTL Persistent Reservation information start:\n");
2902 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2903 			mtx_lock(&lun->lun_lock);
2904 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2905 				mtx_unlock(&lun->lun_lock);
2906 				continue;
2907 			}
2908 
2909 			for (j = 0; j < ctl_max_ports; j++) {
2910 				if (lun->pr_keys[j] == NULL)
2911 					continue;
2912 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2913 					if (lun->pr_keys[j][k] == 0)
2914 						continue;
2915 					printf("  LUN %ju port %d iid %d key "
2916 					       "%#jx\n", lun->lun, j, k,
2917 					       (uintmax_t)lun->pr_keys[j][k]);
2918 				}
2919 			}
2920 			mtx_unlock(&lun->lun_lock);
2921 		}
2922 		printf("CTL Persistent Reservation information end\n");
2923 		printf("CTL Ports:\n");
2924 		STAILQ_FOREACH(port, &softc->port_list, links) {
2925 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2926 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2927 			       port->frontend->name, port->port_type,
2928 			       port->physical_port, port->virtual_port,
2929 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2930 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2931 				if (port->wwpn_iid[j].in_use == 0 &&
2932 				    port->wwpn_iid[j].wwpn == 0 &&
2933 				    port->wwpn_iid[j].name == NULL)
2934 					continue;
2935 
2936 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2937 				    j, port->wwpn_iid[j].in_use,
2938 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2939 				    port->wwpn_iid[j].name);
2940 			}
2941 		}
2942 		printf("CTL Port information end\n");
2943 		mtx_unlock(&softc->ctl_lock);
2944 		/*
2945 		 * XXX KDM calling this without a lock.  We'd likely want
2946 		 * to drop the lock before calling the frontend's dump
2947 		 * routine anyway.
2948 		 */
2949 		printf("CTL Frontends:\n");
2950 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2951 			printf("  Frontend '%s'\n", fe->name);
2952 			if (fe->fe_dump != NULL)
2953 				fe->fe_dump();
2954 		}
2955 		printf("CTL Frontend information end\n");
2956 		break;
2957 	}
2958 	case CTL_LUN_REQ: {
2959 		struct ctl_lun_req *lun_req;
2960 		struct ctl_backend_driver *backend;
2961 		void *packed;
2962 		nvlist_t *tmp_args_nvl;
2963 		size_t packed_len;
2964 
2965 		lun_req = (struct ctl_lun_req *)addr;
2966 		tmp_args_nvl = lun_req->args_nvl;
2967 
2968 		backend = ctl_backend_find(lun_req->backend);
2969 		if (backend == NULL) {
2970 			lun_req->status = CTL_LUN_ERROR;
2971 			snprintf(lun_req->error_str,
2972 				 sizeof(lun_req->error_str),
2973 				 "Backend \"%s\" not found.",
2974 				 lun_req->backend);
2975 			break;
2976 		}
2977 
2978 		if (lun_req->args != NULL) {
2979 			if (lun_req->args_len > CTL_MAX_ARGS_LEN) {
2980 				lun_req->status = CTL_LUN_ERROR;
2981 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2982 				    "Too big args.");
2983 				break;
2984 			}
2985 			packed = malloc(lun_req->args_len, M_CTL, M_WAITOK);
2986 			if (copyin(lun_req->args, packed, lun_req->args_len) != 0) {
2987 				free(packed, M_CTL);
2988 				lun_req->status = CTL_LUN_ERROR;
2989 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2990 				    "Cannot copyin args.");
2991 				break;
2992 			}
2993 			lun_req->args_nvl = nvlist_unpack(packed,
2994 			    lun_req->args_len, 0);
2995 			free(packed, M_CTL);
2996 
2997 			if (lun_req->args_nvl == NULL) {
2998 				lun_req->status = CTL_LUN_ERROR;
2999 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
3000 				    "Cannot unpack args nvlist.");
3001 				break;
3002 			}
3003 		} else
3004 			lun_req->args_nvl = nvlist_create(0);
3005 
3006 		lun_req->result_nvl = NULL;
3007 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3008 		nvlist_destroy(lun_req->args_nvl);
3009 		lun_req->args_nvl = tmp_args_nvl;
3010 
3011 		if (lun_req->result_nvl != NULL) {
3012 			if (lun_req->result != NULL) {
3013 				packed = nvlist_pack(lun_req->result_nvl,
3014 				    &packed_len);
3015 				if (packed == NULL) {
3016 					lun_req->status = CTL_LUN_ERROR;
3017 					snprintf(lun_req->error_str,
3018 					    sizeof(lun_req->error_str),
3019 					    "Cannot pack result nvlist.");
3020 					break;
3021 				}
3022 
3023 				if (packed_len > lun_req->result_len) {
3024 					lun_req->status = CTL_LUN_ERROR;
3025 					snprintf(lun_req->error_str,
3026 					    sizeof(lun_req->error_str),
3027 					    "Result nvlist too large.");
3028 					free(packed, M_NVLIST);
3029 					break;
3030 				}
3031 
3032 				if (copyout(packed, lun_req->result, packed_len)) {
3033 					lun_req->status = CTL_LUN_ERROR;
3034 					snprintf(lun_req->error_str,
3035 					    sizeof(lun_req->error_str),
3036 					    "Cannot copyout() the result.");
3037 					free(packed, M_NVLIST);
3038 					break;
3039 				}
3040 
3041 				lun_req->result_len = packed_len;
3042 				free(packed, M_NVLIST);
3043 			}
3044 
3045 			nvlist_destroy(lun_req->result_nvl);
3046 		}
3047 		break;
3048 	}
3049 	case CTL_LUN_LIST: {
3050 		struct sbuf *sb;
3051 		struct ctl_lun_list *list;
3052 		const char *name, *value;
3053 		void *cookie;
3054 		int type;
3055 
3056 		list = (struct ctl_lun_list *)addr;
3057 
3058 		/*
3059 		 * Allocate a fixed length sbuf here, based on the length
3060 		 * of the user's buffer.  We could allocate an auto-extending
3061 		 * buffer, and then tell the user how much larger our
3062 		 * amount of data is than his buffer, but that presents
3063 		 * some problems:
3064 		 *
3065 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3066 		 *     we can't hold a lock while calling them with an
3067 		 *     auto-extending buffer.
3068  		 *
3069 		 * 2.  There is not currently a LUN reference counting
3070 		 *     mechanism, outside of outstanding transactions on
3071 		 *     the LUN's OOA queue.  So a LUN could go away on us
3072 		 *     while we're getting the LUN number, backend-specific
3073 		 *     information, etc.  Thus, given the way things
3074 		 *     currently work, we need to hold the CTL lock while
3075 		 *     grabbing LUN information.
3076 		 *
3077 		 * So, from the user's standpoint, the best thing to do is
3078 		 * allocate what he thinks is a reasonable buffer length,
3079 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3080 		 * double the buffer length and try again.  (And repeat
3081 		 * that until he succeeds.)
3082 		 */
3083 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3084 		if (sb == NULL) {
3085 			list->status = CTL_LUN_LIST_ERROR;
3086 			snprintf(list->error_str, sizeof(list->error_str),
3087 				 "Unable to allocate %d bytes for LUN list",
3088 				 list->alloc_len);
3089 			break;
3090 		}
3091 
3092 		sbuf_printf(sb, "<ctllunlist>\n");
3093 
3094 		mtx_lock(&softc->ctl_lock);
3095 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3096 			mtx_lock(&lun->lun_lock);
3097 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3098 					     (uintmax_t)lun->lun);
3099 
3100 			/*
3101 			 * Bail out as soon as we see that we've overfilled
3102 			 * the buffer.
3103 			 */
3104 			if (retval != 0)
3105 				break;
3106 
3107 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3108 					     "</backend_type>\n",
3109 					     (lun->backend == NULL) ?  "none" :
3110 					     lun->backend->name);
3111 
3112 			if (retval != 0)
3113 				break;
3114 
3115 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3116 					     lun->be_lun->lun_type);
3117 
3118 			if (retval != 0)
3119 				break;
3120 
3121 			if (lun->backend == NULL) {
3122 				retval = sbuf_printf(sb, "</lun>\n");
3123 				if (retval != 0)
3124 					break;
3125 				continue;
3126 			}
3127 
3128 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3129 					     (lun->be_lun->maxlba > 0) ?
3130 					     lun->be_lun->maxlba + 1 : 0);
3131 
3132 			if (retval != 0)
3133 				break;
3134 
3135 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3136 					     lun->be_lun->blocksize);
3137 
3138 			if (retval != 0)
3139 				break;
3140 
3141 			retval = sbuf_printf(sb, "\t<serial_number>");
3142 
3143 			if (retval != 0)
3144 				break;
3145 
3146 			retval = ctl_sbuf_printf_esc(sb,
3147 			    lun->be_lun->serial_num,
3148 			    sizeof(lun->be_lun->serial_num));
3149 
3150 			if (retval != 0)
3151 				break;
3152 
3153 			retval = sbuf_printf(sb, "</serial_number>\n");
3154 
3155 			if (retval != 0)
3156 				break;
3157 
3158 			retval = sbuf_printf(sb, "\t<device_id>");
3159 
3160 			if (retval != 0)
3161 				break;
3162 
3163 			retval = ctl_sbuf_printf_esc(sb,
3164 			    lun->be_lun->device_id,
3165 			    sizeof(lun->be_lun->device_id));
3166 
3167 			if (retval != 0)
3168 				break;
3169 
3170 			retval = sbuf_printf(sb, "</device_id>\n");
3171 
3172 			if (retval != 0)
3173 				break;
3174 
3175 			if (lun->backend->lun_info != NULL) {
3176 				retval = lun->backend->lun_info(lun->be_lun, sb);
3177 				if (retval != 0)
3178 					break;
3179 			}
3180 
3181 			cookie = NULL;
3182 			while ((name = nvlist_next(lun->be_lun->options, &type,
3183 			    &cookie)) != NULL) {
3184 				sbuf_printf(sb, "\t<%s>", name);
3185 
3186 				if (type == NV_TYPE_STRING) {
3187 					value = dnvlist_get_string(
3188 					    lun->be_lun->options, name, NULL);
3189 					if (value != NULL)
3190 						sbuf_printf(sb, "%s", value);
3191 				}
3192 
3193 				sbuf_printf(sb, "</%s>\n", name);
3194 			}
3195 
3196 			retval = sbuf_printf(sb, "</lun>\n");
3197 
3198 			if (retval != 0)
3199 				break;
3200 			mtx_unlock(&lun->lun_lock);
3201 		}
3202 		if (lun != NULL)
3203 			mtx_unlock(&lun->lun_lock);
3204 		mtx_unlock(&softc->ctl_lock);
3205 
3206 		if ((retval != 0)
3207 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3208 			retval = 0;
3209 			sbuf_delete(sb);
3210 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3211 			snprintf(list->error_str, sizeof(list->error_str),
3212 				 "Out of space, %d bytes is too small",
3213 				 list->alloc_len);
3214 			break;
3215 		}
3216 
3217 		sbuf_finish(sb);
3218 
3219 		retval = copyout(sbuf_data(sb), list->lun_xml,
3220 				 sbuf_len(sb) + 1);
3221 
3222 		list->fill_len = sbuf_len(sb) + 1;
3223 		list->status = CTL_LUN_LIST_OK;
3224 		sbuf_delete(sb);
3225 		break;
3226 	}
3227 	case CTL_ISCSI: {
3228 		struct ctl_iscsi *ci;
3229 		struct ctl_frontend *fe;
3230 
3231 		ci = (struct ctl_iscsi *)addr;
3232 
3233 		fe = ctl_frontend_find("iscsi");
3234 		if (fe == NULL) {
3235 			ci->status = CTL_ISCSI_ERROR;
3236 			snprintf(ci->error_str, sizeof(ci->error_str),
3237 			    "Frontend \"iscsi\" not found.");
3238 			break;
3239 		}
3240 
3241 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3242 		break;
3243 	}
3244 	case CTL_PORT_REQ: {
3245 		struct ctl_req *req;
3246 		struct ctl_frontend *fe;
3247 		void *packed;
3248 		nvlist_t *tmp_args_nvl;
3249 		size_t packed_len;
3250 
3251 		req = (struct ctl_req *)addr;
3252 		tmp_args_nvl = req->args_nvl;
3253 
3254 		fe = ctl_frontend_find(req->driver);
3255 		if (fe == NULL) {
3256 			req->status = CTL_LUN_ERROR;
3257 			snprintf(req->error_str, sizeof(req->error_str),
3258 			    "Frontend \"%s\" not found.", req->driver);
3259 			break;
3260 		}
3261 
3262 		if (req->args != NULL) {
3263 			if (req->args_len > CTL_MAX_ARGS_LEN) {
3264 				req->status = CTL_LUN_ERROR;
3265 				snprintf(req->error_str, sizeof(req->error_str),
3266 				    "Too big args.");
3267 				break;
3268 			}
3269 			packed = malloc(req->args_len, M_CTL, M_WAITOK);
3270 			if (copyin(req->args, packed, req->args_len) != 0) {
3271 				free(packed, M_CTL);
3272 				req->status = CTL_LUN_ERROR;
3273 				snprintf(req->error_str, sizeof(req->error_str),
3274 				    "Cannot copyin args.");
3275 				break;
3276 			}
3277 			req->args_nvl = nvlist_unpack(packed,
3278 			    req->args_len, 0);
3279 			free(packed, M_CTL);
3280 
3281 			if (req->args_nvl == NULL) {
3282 				req->status = CTL_LUN_ERROR;
3283 				snprintf(req->error_str, sizeof(req->error_str),
3284 				    "Cannot unpack args nvlist.");
3285 				break;
3286 			}
3287 		} else
3288 			req->args_nvl = nvlist_create(0);
3289 
3290 		req->result_nvl = NULL;
3291 		if (fe->ioctl)
3292 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3293 		else
3294 			retval = ENODEV;
3295 
3296 		nvlist_destroy(req->args_nvl);
3297 		req->args_nvl = tmp_args_nvl;
3298 
3299 		if (req->result_nvl != NULL) {
3300 			if (req->result != NULL) {
3301 				packed = nvlist_pack(req->result_nvl,
3302 				    &packed_len);
3303 				if (packed == NULL) {
3304 					req->status = CTL_LUN_ERROR;
3305 					snprintf(req->error_str,
3306 					    sizeof(req->error_str),
3307 					    "Cannot pack result nvlist.");
3308 					break;
3309 				}
3310 
3311 				if (packed_len > req->result_len) {
3312 					req->status = CTL_LUN_ERROR;
3313 					snprintf(req->error_str,
3314 					    sizeof(req->error_str),
3315 					    "Result nvlist too large.");
3316 					free(packed, M_NVLIST);
3317 					break;
3318 				}
3319 
3320 				if (copyout(packed, req->result, packed_len)) {
3321 					req->status = CTL_LUN_ERROR;
3322 					snprintf(req->error_str,
3323 					    sizeof(req->error_str),
3324 					    "Cannot copyout() the result.");
3325 					free(packed, M_NVLIST);
3326 					break;
3327 				}
3328 
3329 				req->result_len = packed_len;
3330 				free(packed, M_NVLIST);
3331 			}
3332 
3333 			nvlist_destroy(req->result_nvl);
3334 		}
3335 		break;
3336 	}
3337 	case CTL_PORT_LIST: {
3338 		struct sbuf *sb;
3339 		struct ctl_port *port;
3340 		struct ctl_lun_list *list;
3341 		const char *name, *value;
3342 		void *cookie;
3343 		int j, type;
3344 		uint32_t plun;
3345 
3346 		list = (struct ctl_lun_list *)addr;
3347 
3348 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3349 		if (sb == NULL) {
3350 			list->status = CTL_LUN_LIST_ERROR;
3351 			snprintf(list->error_str, sizeof(list->error_str),
3352 				 "Unable to allocate %d bytes for LUN list",
3353 				 list->alloc_len);
3354 			break;
3355 		}
3356 
3357 		sbuf_printf(sb, "<ctlportlist>\n");
3358 
3359 		mtx_lock(&softc->ctl_lock);
3360 		STAILQ_FOREACH(port, &softc->port_list, links) {
3361 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3362 					     (uintmax_t)port->targ_port);
3363 
3364 			/*
3365 			 * Bail out as soon as we see that we've overfilled
3366 			 * the buffer.
3367 			 */
3368 			if (retval != 0)
3369 				break;
3370 
3371 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3372 			    "</frontend_type>\n", port->frontend->name);
3373 			if (retval != 0)
3374 				break;
3375 
3376 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3377 					     port->port_type);
3378 			if (retval != 0)
3379 				break;
3380 
3381 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3382 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3383 			if (retval != 0)
3384 				break;
3385 
3386 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3387 			    port->port_name);
3388 			if (retval != 0)
3389 				break;
3390 
3391 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3392 			    port->physical_port);
3393 			if (retval != 0)
3394 				break;
3395 
3396 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3397 			    port->virtual_port);
3398 			if (retval != 0)
3399 				break;
3400 
3401 			if (port->target_devid != NULL) {
3402 				sbuf_printf(sb, "\t<target>");
3403 				ctl_id_sbuf(port->target_devid, sb);
3404 				sbuf_printf(sb, "</target>\n");
3405 			}
3406 
3407 			if (port->port_devid != NULL) {
3408 				sbuf_printf(sb, "\t<port>");
3409 				ctl_id_sbuf(port->port_devid, sb);
3410 				sbuf_printf(sb, "</port>\n");
3411 			}
3412 
3413 			if (port->port_info != NULL) {
3414 				retval = port->port_info(port->onoff_arg, sb);
3415 				if (retval != 0)
3416 					break;
3417 			}
3418 
3419 			cookie = NULL;
3420 			while ((name = nvlist_next(port->options, &type,
3421 			    &cookie)) != NULL) {
3422 				sbuf_printf(sb, "\t<%s>", name);
3423 
3424 				if (type == NV_TYPE_STRING) {
3425 					value = dnvlist_get_string(port->options,
3426 					    name, NULL);
3427 					if (value != NULL)
3428 						sbuf_printf(sb, "%s", value);
3429 				}
3430 
3431 				sbuf_printf(sb, "</%s>\n", name);
3432 			}
3433 
3434 			if (port->lun_map != NULL) {
3435 				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3436 				for (j = 0; j < port->lun_map_size; j++) {
3437 					plun = ctl_lun_map_from_port(port, j);
3438 					if (plun == UINT32_MAX)
3439 						continue;
3440 					sbuf_printf(sb,
3441 					    "\t<lun id=\"%u\">%u</lun>\n",
3442 					    j, plun);
3443 				}
3444 			}
3445 
3446 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3447 				if (port->wwpn_iid[j].in_use == 0 ||
3448 				    (port->wwpn_iid[j].wwpn == 0 &&
3449 				     port->wwpn_iid[j].name == NULL))
3450 					continue;
3451 
3452 				if (port->wwpn_iid[j].name != NULL)
3453 					retval = sbuf_printf(sb,
3454 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3455 					    j, port->wwpn_iid[j].name);
3456 				else
3457 					retval = sbuf_printf(sb,
3458 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3459 					    j, port->wwpn_iid[j].wwpn);
3460 				if (retval != 0)
3461 					break;
3462 			}
3463 			if (retval != 0)
3464 				break;
3465 
3466 			retval = sbuf_printf(sb, "</targ_port>\n");
3467 			if (retval != 0)
3468 				break;
3469 		}
3470 		mtx_unlock(&softc->ctl_lock);
3471 
3472 		if ((retval != 0)
3473 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3474 			retval = 0;
3475 			sbuf_delete(sb);
3476 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3477 			snprintf(list->error_str, sizeof(list->error_str),
3478 				 "Out of space, %d bytes is too small",
3479 				 list->alloc_len);
3480 			break;
3481 		}
3482 
3483 		sbuf_finish(sb);
3484 
3485 		retval = copyout(sbuf_data(sb), list->lun_xml,
3486 				 sbuf_len(sb) + 1);
3487 
3488 		list->fill_len = sbuf_len(sb) + 1;
3489 		list->status = CTL_LUN_LIST_OK;
3490 		sbuf_delete(sb);
3491 		break;
3492 	}
3493 	case CTL_LUN_MAP: {
3494 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3495 		struct ctl_port *port;
3496 
3497 		mtx_lock(&softc->ctl_lock);
3498 		if (lm->port < softc->port_min ||
3499 		    lm->port >= softc->port_max ||
3500 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3501 			mtx_unlock(&softc->ctl_lock);
3502 			return (ENXIO);
3503 		}
3504 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3505 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3506 				if (ctl_lun_map_to_port(port, lun->lun) ==
3507 				    UINT32_MAX)
3508 					continue;
3509 				mtx_lock(&lun->lun_lock);
3510 				ctl_est_ua_port(lun, lm->port, -1,
3511 				    CTL_UA_LUN_CHANGE);
3512 				mtx_unlock(&lun->lun_lock);
3513 			}
3514 		}
3515 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3516 		if (lm->plun != UINT32_MAX) {
3517 			if (lm->lun == UINT32_MAX)
3518 				retval = ctl_lun_map_unset(port, lm->plun);
3519 			else if (lm->lun < ctl_max_luns &&
3520 			    softc->ctl_luns[lm->lun] != NULL)
3521 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3522 			else
3523 				return (ENXIO);
3524 		} else {
3525 			if (lm->lun == UINT32_MAX)
3526 				retval = ctl_lun_map_deinit(port);
3527 			else
3528 				retval = ctl_lun_map_init(port);
3529 		}
3530 		if (port->status & CTL_PORT_STATUS_ONLINE)
3531 			ctl_isc_announce_port(port);
3532 		break;
3533 	}
3534 	case CTL_GET_LUN_STATS: {
3535 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3536 		int i;
3537 
3538 		/*
3539 		 * XXX KDM no locking here.  If the LUN list changes,
3540 		 * things can blow up.
3541 		 */
3542 		i = 0;
3543 		stats->status = CTL_SS_OK;
3544 		stats->fill_len = 0;
3545 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3546 			if (lun->lun < stats->first_item)
3547 				continue;
3548 			if (stats->fill_len + sizeof(lun->stats) >
3549 			    stats->alloc_len) {
3550 				stats->status = CTL_SS_NEED_MORE_SPACE;
3551 				break;
3552 			}
3553 			retval = copyout(&lun->stats, &stats->stats[i++],
3554 					 sizeof(lun->stats));
3555 			if (retval != 0)
3556 				break;
3557 			stats->fill_len += sizeof(lun->stats);
3558 		}
3559 		stats->num_items = softc->num_luns;
3560 		stats->flags = CTL_STATS_FLAG_NONE;
3561 #ifdef CTL_TIME_IO
3562 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3563 #endif
3564 		getnanouptime(&stats->timestamp);
3565 		break;
3566 	}
3567 	case CTL_GET_PORT_STATS: {
3568 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3569 		int i;
3570 
3571 		/*
3572 		 * XXX KDM no locking here.  If the LUN list changes,
3573 		 * things can blow up.
3574 		 */
3575 		i = 0;
3576 		stats->status = CTL_SS_OK;
3577 		stats->fill_len = 0;
3578 		STAILQ_FOREACH(port, &softc->port_list, links) {
3579 			if (port->targ_port < stats->first_item)
3580 				continue;
3581 			if (stats->fill_len + sizeof(port->stats) >
3582 			    stats->alloc_len) {
3583 				stats->status = CTL_SS_NEED_MORE_SPACE;
3584 				break;
3585 			}
3586 			retval = copyout(&port->stats, &stats->stats[i++],
3587 					 sizeof(port->stats));
3588 			if (retval != 0)
3589 				break;
3590 			stats->fill_len += sizeof(port->stats);
3591 		}
3592 		stats->num_items = softc->num_ports;
3593 		stats->flags = CTL_STATS_FLAG_NONE;
3594 #ifdef CTL_TIME_IO
3595 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3596 #endif
3597 		getnanouptime(&stats->timestamp);
3598 		break;
3599 	}
3600 	default: {
3601 		/* XXX KDM should we fix this? */
3602 #if 0
3603 		struct ctl_backend_driver *backend;
3604 		unsigned int type;
3605 		int found;
3606 
3607 		found = 0;
3608 
3609 		/*
3610 		 * We encode the backend type as the ioctl type for backend
3611 		 * ioctls.  So parse it out here, and then search for a
3612 		 * backend of this type.
3613 		 */
3614 		type = _IOC_TYPE(cmd);
3615 
3616 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3617 			if (backend->type == type) {
3618 				found = 1;
3619 				break;
3620 			}
3621 		}
3622 		if (found == 0) {
3623 			printf("ctl: unknown ioctl command %#lx or backend "
3624 			       "%d\n", cmd, type);
3625 			retval = EINVAL;
3626 			break;
3627 		}
3628 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3629 #endif
3630 		retval = ENOTTY;
3631 		break;
3632 	}
3633 	}
3634 	return (retval);
3635 }
3636 
3637 uint32_t
3638 ctl_get_initindex(struct ctl_nexus *nexus)
3639 {
3640 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3641 }
3642 
3643 int
3644 ctl_lun_map_init(struct ctl_port *port)
3645 {
3646 	struct ctl_softc *softc = port->ctl_softc;
3647 	struct ctl_lun *lun;
3648 	int size = ctl_lun_map_size;
3649 	uint32_t i;
3650 
3651 	if (port->lun_map == NULL || port->lun_map_size < size) {
3652 		port->lun_map_size = 0;
3653 		free(port->lun_map, M_CTL);
3654 		port->lun_map = malloc(size * sizeof(uint32_t),
3655 		    M_CTL, M_NOWAIT);
3656 	}
3657 	if (port->lun_map == NULL)
3658 		return (ENOMEM);
3659 	for (i = 0; i < size; i++)
3660 		port->lun_map[i] = UINT32_MAX;
3661 	port->lun_map_size = size;
3662 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3663 		if (port->lun_disable != NULL) {
3664 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3665 				port->lun_disable(port->targ_lun_arg, lun->lun);
3666 		}
3667 		ctl_isc_announce_port(port);
3668 	}
3669 	return (0);
3670 }
3671 
3672 int
3673 ctl_lun_map_deinit(struct ctl_port *port)
3674 {
3675 	struct ctl_softc *softc = port->ctl_softc;
3676 	struct ctl_lun *lun;
3677 
3678 	if (port->lun_map == NULL)
3679 		return (0);
3680 	port->lun_map_size = 0;
3681 	free(port->lun_map, M_CTL);
3682 	port->lun_map = NULL;
3683 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3684 		if (port->lun_enable != NULL) {
3685 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3686 				port->lun_enable(port->targ_lun_arg, lun->lun);
3687 		}
3688 		ctl_isc_announce_port(port);
3689 	}
3690 	return (0);
3691 }
3692 
3693 int
3694 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3695 {
3696 	int status;
3697 	uint32_t old;
3698 
3699 	if (port->lun_map == NULL) {
3700 		status = ctl_lun_map_init(port);
3701 		if (status != 0)
3702 			return (status);
3703 	}
3704 	if (plun >= port->lun_map_size)
3705 		return (EINVAL);
3706 	old = port->lun_map[plun];
3707 	port->lun_map[plun] = glun;
3708 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3709 		if (port->lun_enable != NULL)
3710 			port->lun_enable(port->targ_lun_arg, plun);
3711 		ctl_isc_announce_port(port);
3712 	}
3713 	return (0);
3714 }
3715 
3716 int
3717 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3718 {
3719 	uint32_t old;
3720 
3721 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3722 		return (0);
3723 	old = port->lun_map[plun];
3724 	port->lun_map[plun] = UINT32_MAX;
3725 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3726 		if (port->lun_disable != NULL)
3727 			port->lun_disable(port->targ_lun_arg, plun);
3728 		ctl_isc_announce_port(port);
3729 	}
3730 	return (0);
3731 }
3732 
3733 uint32_t
3734 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3735 {
3736 
3737 	if (port == NULL)
3738 		return (UINT32_MAX);
3739 	if (port->lun_map == NULL)
3740 		return (lun_id);
3741 	if (lun_id > port->lun_map_size)
3742 		return (UINT32_MAX);
3743 	return (port->lun_map[lun_id]);
3744 }
3745 
3746 uint32_t
3747 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3748 {
3749 	uint32_t i;
3750 
3751 	if (port == NULL)
3752 		return (UINT32_MAX);
3753 	if (port->lun_map == NULL)
3754 		return (lun_id);
3755 	for (i = 0; i < port->lun_map_size; i++) {
3756 		if (port->lun_map[i] == lun_id)
3757 			return (i);
3758 	}
3759 	return (UINT32_MAX);
3760 }
3761 
3762 uint32_t
3763 ctl_decode_lun(uint64_t encoded)
3764 {
3765 	uint8_t lun[8];
3766 	uint32_t result = 0xffffffff;
3767 
3768 	be64enc(lun, encoded);
3769 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3770 	case RPL_LUNDATA_ATYP_PERIPH:
3771 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3772 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3773 			result = lun[1];
3774 		break;
3775 	case RPL_LUNDATA_ATYP_FLAT:
3776 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3777 		    lun[6] == 0 && lun[7] == 0)
3778 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3779 		break;
3780 	case RPL_LUNDATA_ATYP_EXTLUN:
3781 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3782 		case 0x02:
3783 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3784 			case 0x00:
3785 				result = lun[1];
3786 				break;
3787 			case 0x10:
3788 				result = (lun[1] << 16) + (lun[2] << 8) +
3789 				    lun[3];
3790 				break;
3791 			case 0x20:
3792 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3793 					result = (lun[2] << 24) +
3794 					    (lun[3] << 16) + (lun[4] << 8) +
3795 					    lun[5];
3796 				break;
3797 			}
3798 			break;
3799 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3800 			result = 0xffffffff;
3801 			break;
3802 		}
3803 		break;
3804 	}
3805 	return (result);
3806 }
3807 
3808 uint64_t
3809 ctl_encode_lun(uint32_t decoded)
3810 {
3811 	uint64_t l = decoded;
3812 
3813 	if (l <= 0xff)
3814 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3815 	if (l <= 0x3fff)
3816 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3817 	if (l <= 0xffffff)
3818 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3819 		    (l << 32));
3820 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3821 }
3822 
3823 int
3824 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3825 {
3826 	int i;
3827 
3828 	for (i = first; i < last; i++) {
3829 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3830 			return (i);
3831 	}
3832 	return (-1);
3833 }
3834 
3835 int
3836 ctl_set_mask(uint32_t *mask, uint32_t bit)
3837 {
3838 	uint32_t chunk, piece;
3839 
3840 	chunk = bit >> 5;
3841 	piece = bit % (sizeof(uint32_t) * 8);
3842 
3843 	if ((mask[chunk] & (1 << piece)) != 0)
3844 		return (-1);
3845 	else
3846 		mask[chunk] |= (1 << piece);
3847 
3848 	return (0);
3849 }
3850 
3851 int
3852 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3853 {
3854 	uint32_t chunk, piece;
3855 
3856 	chunk = bit >> 5;
3857 	piece = bit % (sizeof(uint32_t) * 8);
3858 
3859 	if ((mask[chunk] & (1 << piece)) == 0)
3860 		return (-1);
3861 	else
3862 		mask[chunk] &= ~(1 << piece);
3863 
3864 	return (0);
3865 }
3866 
3867 int
3868 ctl_is_set(uint32_t *mask, uint32_t bit)
3869 {
3870 	uint32_t chunk, piece;
3871 
3872 	chunk = bit >> 5;
3873 	piece = bit % (sizeof(uint32_t) * 8);
3874 
3875 	if ((mask[chunk] & (1 << piece)) == 0)
3876 		return (0);
3877 	else
3878 		return (1);
3879 }
3880 
3881 static uint64_t
3882 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3883 {
3884 	uint64_t *t;
3885 
3886 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3887 	if (t == NULL)
3888 		return (0);
3889 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3890 }
3891 
3892 static void
3893 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3894 {
3895 	uint64_t *t;
3896 
3897 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3898 	if (t == NULL)
3899 		return;
3900 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3901 }
3902 
3903 static void
3904 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3905 {
3906 	uint64_t *p;
3907 	u_int i;
3908 
3909 	i = residx/CTL_MAX_INIT_PER_PORT;
3910 	if (lun->pr_keys[i] != NULL)
3911 		return;
3912 	mtx_unlock(&lun->lun_lock);
3913 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3914 	    M_WAITOK | M_ZERO);
3915 	mtx_lock(&lun->lun_lock);
3916 	if (lun->pr_keys[i] == NULL)
3917 		lun->pr_keys[i] = p;
3918 	else
3919 		free(p, M_CTL);
3920 }
3921 
3922 static void
3923 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3924 {
3925 	uint64_t *t;
3926 
3927 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3928 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3929 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3930 }
3931 
3932 /*
3933  * ctl_softc, pool_name, total_ctl_io are passed in.
3934  * npool is passed out.
3935  */
3936 int
3937 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3938 		uint32_t total_ctl_io, void **npool)
3939 {
3940 	struct ctl_io_pool *pool;
3941 
3942 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3943 					    M_NOWAIT | M_ZERO);
3944 	if (pool == NULL)
3945 		return (ENOMEM);
3946 
3947 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3948 	pool->ctl_softc = ctl_softc;
3949 #ifdef IO_POOLS
3950 	pool->zone = uma_zsecond_create(pool->name, NULL,
3951 	    NULL, NULL, NULL, ctl_softc->io_zone);
3952 	/* uma_prealloc(pool->zone, total_ctl_io); */
3953 #else
3954 	pool->zone = ctl_softc->io_zone;
3955 #endif
3956 
3957 	*npool = pool;
3958 	return (0);
3959 }
3960 
3961 void
3962 ctl_pool_free(struct ctl_io_pool *pool)
3963 {
3964 
3965 	if (pool == NULL)
3966 		return;
3967 
3968 #ifdef IO_POOLS
3969 	uma_zdestroy(pool->zone);
3970 #endif
3971 	free(pool, M_CTL);
3972 }
3973 
3974 union ctl_io *
3975 ctl_alloc_io(void *pool_ref)
3976 {
3977 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3978 	union ctl_io *io;
3979 
3980 	io = uma_zalloc(pool->zone, M_WAITOK);
3981 	if (io != NULL) {
3982 		io->io_hdr.pool = pool_ref;
3983 		CTL_SOFTC(io) = pool->ctl_softc;
3984 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3985 	}
3986 	return (io);
3987 }
3988 
3989 union ctl_io *
3990 ctl_alloc_io_nowait(void *pool_ref)
3991 {
3992 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3993 	union ctl_io *io;
3994 
3995 	io = uma_zalloc(pool->zone, M_NOWAIT);
3996 	if (io != NULL) {
3997 		io->io_hdr.pool = pool_ref;
3998 		CTL_SOFTC(io) = pool->ctl_softc;
3999 		TAILQ_INIT(&io->io_hdr.blocked_queue);
4000 	}
4001 	return (io);
4002 }
4003 
4004 void
4005 ctl_free_io(union ctl_io *io)
4006 {
4007 	struct ctl_io_pool *pool;
4008 
4009 	if (io == NULL)
4010 		return;
4011 
4012 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
4013 	uma_zfree(pool->zone, io);
4014 }
4015 
4016 void
4017 ctl_zero_io(union ctl_io *io)
4018 {
4019 	struct ctl_io_pool *pool;
4020 
4021 	if (io == NULL)
4022 		return;
4023 
4024 	/*
4025 	 * May need to preserve linked list pointers at some point too.
4026 	 */
4027 	pool = io->io_hdr.pool;
4028 	memset(io, 0, sizeof(*io));
4029 	io->io_hdr.pool = pool;
4030 	CTL_SOFTC(io) = pool->ctl_softc;
4031 	TAILQ_INIT(&io->io_hdr.blocked_queue);
4032 }
4033 
4034 int
4035 ctl_expand_number(const char *buf, uint64_t *num)
4036 {
4037 	char *endptr;
4038 	uint64_t number;
4039 	unsigned shift;
4040 
4041 	number = strtoq(buf, &endptr, 0);
4042 
4043 	switch (tolower((unsigned char)*endptr)) {
4044 	case 'e':
4045 		shift = 60;
4046 		break;
4047 	case 'p':
4048 		shift = 50;
4049 		break;
4050 	case 't':
4051 		shift = 40;
4052 		break;
4053 	case 'g':
4054 		shift = 30;
4055 		break;
4056 	case 'm':
4057 		shift = 20;
4058 		break;
4059 	case 'k':
4060 		shift = 10;
4061 		break;
4062 	case 'b':
4063 	case '\0': /* No unit. */
4064 		*num = number;
4065 		return (0);
4066 	default:
4067 		/* Unrecognized unit. */
4068 		return (-1);
4069 	}
4070 
4071 	if ((number << shift) >> shift != number) {
4072 		/* Overflow */
4073 		return (-1);
4074 	}
4075 	*num = number << shift;
4076 	return (0);
4077 }
4078 
4079 /*
4080  * This routine could be used in the future to load default and/or saved
4081  * mode page parameters for a particuar lun.
4082  */
4083 static int
4084 ctl_init_page_index(struct ctl_lun *lun)
4085 {
4086 	int i, page_code;
4087 	struct ctl_page_index *page_index;
4088 	const char *value;
4089 	uint64_t ival;
4090 
4091 	memcpy(&lun->mode_pages.index, page_index_template,
4092 	       sizeof(page_index_template));
4093 
4094 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4095 		page_index = &lun->mode_pages.index[i];
4096 		if (lun->be_lun->lun_type == T_DIRECT &&
4097 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4098 			continue;
4099 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4100 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4101 			continue;
4102 		if (lun->be_lun->lun_type == T_CDROM &&
4103 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4104 			continue;
4105 
4106 		page_code = page_index->page_code & SMPH_PC_MASK;
4107 		switch (page_code) {
4108 		case SMS_RW_ERROR_RECOVERY_PAGE: {
4109 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4110 			    ("subpage %#x for page %#x is incorrect!",
4111 			    page_index->subpage, page_code));
4112 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4113 			       &rw_er_page_default,
4114 			       sizeof(rw_er_page_default));
4115 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4116 			       &rw_er_page_changeable,
4117 			       sizeof(rw_er_page_changeable));
4118 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4119 			       &rw_er_page_default,
4120 			       sizeof(rw_er_page_default));
4121 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4122 			       &rw_er_page_default,
4123 			       sizeof(rw_er_page_default));
4124 			page_index->page_data =
4125 				(uint8_t *)lun->mode_pages.rw_er_page;
4126 			break;
4127 		}
4128 		case SMS_FORMAT_DEVICE_PAGE: {
4129 			struct scsi_format_page *format_page;
4130 
4131 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4132 			    ("subpage %#x for page %#x is incorrect!",
4133 			    page_index->subpage, page_code));
4134 
4135 			/*
4136 			 * Sectors per track are set above.  Bytes per
4137 			 * sector need to be set here on a per-LUN basis.
4138 			 */
4139 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4140 			       &format_page_default,
4141 			       sizeof(format_page_default));
4142 			memcpy(&lun->mode_pages.format_page[
4143 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4144 			       sizeof(format_page_changeable));
4145 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4146 			       &format_page_default,
4147 			       sizeof(format_page_default));
4148 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4149 			       &format_page_default,
4150 			       sizeof(format_page_default));
4151 
4152 			format_page = &lun->mode_pages.format_page[
4153 				CTL_PAGE_CURRENT];
4154 			scsi_ulto2b(lun->be_lun->blocksize,
4155 				    format_page->bytes_per_sector);
4156 
4157 			format_page = &lun->mode_pages.format_page[
4158 				CTL_PAGE_DEFAULT];
4159 			scsi_ulto2b(lun->be_lun->blocksize,
4160 				    format_page->bytes_per_sector);
4161 
4162 			format_page = &lun->mode_pages.format_page[
4163 				CTL_PAGE_SAVED];
4164 			scsi_ulto2b(lun->be_lun->blocksize,
4165 				    format_page->bytes_per_sector);
4166 
4167 			page_index->page_data =
4168 				(uint8_t *)lun->mode_pages.format_page;
4169 			break;
4170 		}
4171 		case SMS_RIGID_DISK_PAGE: {
4172 			struct scsi_rigid_disk_page *rigid_disk_page;
4173 			uint32_t sectors_per_cylinder;
4174 			uint64_t cylinders;
4175 #ifndef	__XSCALE__
4176 			int shift;
4177 #endif /* !__XSCALE__ */
4178 
4179 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4180 			    ("subpage %#x for page %#x is incorrect!",
4181 			    page_index->subpage, page_code));
4182 
4183 			/*
4184 			 * Rotation rate and sectors per track are set
4185 			 * above.  We calculate the cylinders here based on
4186 			 * capacity.  Due to the number of heads and
4187 			 * sectors per track we're using, smaller arrays
4188 			 * may turn out to have 0 cylinders.  Linux and
4189 			 * FreeBSD don't pay attention to these mode pages
4190 			 * to figure out capacity, but Solaris does.  It
4191 			 * seems to deal with 0 cylinders just fine, and
4192 			 * works out a fake geometry based on the capacity.
4193 			 */
4194 			memcpy(&lun->mode_pages.rigid_disk_page[
4195 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4196 			       sizeof(rigid_disk_page_default));
4197 			memcpy(&lun->mode_pages.rigid_disk_page[
4198 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4199 			       sizeof(rigid_disk_page_changeable));
4200 
4201 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4202 				CTL_DEFAULT_HEADS;
4203 
4204 			/*
4205 			 * The divide method here will be more accurate,
4206 			 * probably, but results in floating point being
4207 			 * used in the kernel on i386 (__udivdi3()).  On the
4208 			 * XScale, though, __udivdi3() is implemented in
4209 			 * software.
4210 			 *
4211 			 * The shift method for cylinder calculation is
4212 			 * accurate if sectors_per_cylinder is a power of
4213 			 * 2.  Otherwise it might be slightly off -- you
4214 			 * might have a bit of a truncation problem.
4215 			 */
4216 #ifdef	__XSCALE__
4217 			cylinders = (lun->be_lun->maxlba + 1) /
4218 				sectors_per_cylinder;
4219 #else
4220 			for (shift = 31; shift > 0; shift--) {
4221 				if (sectors_per_cylinder & (1 << shift))
4222 					break;
4223 			}
4224 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4225 #endif
4226 
4227 			/*
4228 			 * We've basically got 3 bytes, or 24 bits for the
4229 			 * cylinder size in the mode page.  If we're over,
4230 			 * just round down to 2^24.
4231 			 */
4232 			if (cylinders > 0xffffff)
4233 				cylinders = 0xffffff;
4234 
4235 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4236 				CTL_PAGE_DEFAULT];
4237 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4238 
4239 			if ((value = dnvlist_get_string(lun->be_lun->options,
4240 			    "rpm", NULL)) != NULL) {
4241 				scsi_ulto2b(strtol(value, NULL, 0),
4242 				     rigid_disk_page->rotation_rate);
4243 			}
4244 
4245 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4246 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4247 			       sizeof(rigid_disk_page_default));
4248 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4249 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4250 			       sizeof(rigid_disk_page_default));
4251 
4252 			page_index->page_data =
4253 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4254 			break;
4255 		}
4256 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4257 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4258 			    ("subpage %#x for page %#x is incorrect!",
4259 			    page_index->subpage, page_code));
4260 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4261 			       &verify_er_page_default,
4262 			       sizeof(verify_er_page_default));
4263 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4264 			       &verify_er_page_changeable,
4265 			       sizeof(verify_er_page_changeable));
4266 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4267 			       &verify_er_page_default,
4268 			       sizeof(verify_er_page_default));
4269 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4270 			       &verify_er_page_default,
4271 			       sizeof(verify_er_page_default));
4272 			page_index->page_data =
4273 				(uint8_t *)lun->mode_pages.verify_er_page;
4274 			break;
4275 		}
4276 		case SMS_CACHING_PAGE: {
4277 			struct scsi_caching_page *caching_page;
4278 
4279 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4280 			    ("subpage %#x for page %#x is incorrect!",
4281 			    page_index->subpage, page_code));
4282 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4283 			       &caching_page_default,
4284 			       sizeof(caching_page_default));
4285 			memcpy(&lun->mode_pages.caching_page[
4286 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4287 			       sizeof(caching_page_changeable));
4288 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4289 			       &caching_page_default,
4290 			       sizeof(caching_page_default));
4291 			caching_page = &lun->mode_pages.caching_page[
4292 			    CTL_PAGE_SAVED];
4293 			value = dnvlist_get_string(lun->be_lun->options,
4294 			    "writecache", NULL);
4295 			if (value != NULL && strcmp(value, "off") == 0)
4296 				caching_page->flags1 &= ~SCP_WCE;
4297 			value = dnvlist_get_string(lun->be_lun->options,
4298 			    "readcache", NULL);
4299 			if (value != NULL && strcmp(value, "off") == 0)
4300 				caching_page->flags1 |= SCP_RCD;
4301 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4302 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4303 			       sizeof(caching_page_default));
4304 			page_index->page_data =
4305 				(uint8_t *)lun->mode_pages.caching_page;
4306 			break;
4307 		}
4308 		case SMS_CONTROL_MODE_PAGE: {
4309 			switch (page_index->subpage) {
4310 			case SMS_SUBPAGE_PAGE_0: {
4311 				struct scsi_control_page *control_page;
4312 
4313 				memcpy(&lun->mode_pages.control_page[
4314 				    CTL_PAGE_DEFAULT],
4315 				       &control_page_default,
4316 				       sizeof(control_page_default));
4317 				memcpy(&lun->mode_pages.control_page[
4318 				    CTL_PAGE_CHANGEABLE],
4319 				       &control_page_changeable,
4320 				       sizeof(control_page_changeable));
4321 				memcpy(&lun->mode_pages.control_page[
4322 				    CTL_PAGE_SAVED],
4323 				       &control_page_default,
4324 				       sizeof(control_page_default));
4325 				control_page = &lun->mode_pages.control_page[
4326 				    CTL_PAGE_SAVED];
4327 				value = dnvlist_get_string(lun->be_lun->options,
4328 				    "reordering", NULL);
4329 				if (value != NULL &&
4330 				    strcmp(value, "unrestricted") == 0) {
4331 					control_page->queue_flags &=
4332 					    ~SCP_QUEUE_ALG_MASK;
4333 					control_page->queue_flags |=
4334 					    SCP_QUEUE_ALG_UNRESTRICTED;
4335 				}
4336 				memcpy(&lun->mode_pages.control_page[
4337 				    CTL_PAGE_CURRENT],
4338 				       &lun->mode_pages.control_page[
4339 				    CTL_PAGE_SAVED],
4340 				       sizeof(control_page_default));
4341 				page_index->page_data =
4342 				    (uint8_t *)lun->mode_pages.control_page;
4343 				break;
4344 			}
4345 			case 0x01:
4346 				memcpy(&lun->mode_pages.control_ext_page[
4347 				    CTL_PAGE_DEFAULT],
4348 				       &control_ext_page_default,
4349 				       sizeof(control_ext_page_default));
4350 				memcpy(&lun->mode_pages.control_ext_page[
4351 				    CTL_PAGE_CHANGEABLE],
4352 				       &control_ext_page_changeable,
4353 				       sizeof(control_ext_page_changeable));
4354 				memcpy(&lun->mode_pages.control_ext_page[
4355 				    CTL_PAGE_SAVED],
4356 				       &control_ext_page_default,
4357 				       sizeof(control_ext_page_default));
4358 				memcpy(&lun->mode_pages.control_ext_page[
4359 				    CTL_PAGE_CURRENT],
4360 				       &lun->mode_pages.control_ext_page[
4361 				    CTL_PAGE_SAVED],
4362 				       sizeof(control_ext_page_default));
4363 				page_index->page_data =
4364 				    (uint8_t *)lun->mode_pages.control_ext_page;
4365 				break;
4366 			default:
4367 				panic("subpage %#x for page %#x is incorrect!",
4368 				      page_index->subpage, page_code);
4369 			}
4370 			break;
4371 		}
4372 		case SMS_INFO_EXCEPTIONS_PAGE: {
4373 			switch (page_index->subpage) {
4374 			case SMS_SUBPAGE_PAGE_0:
4375 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4376 				       &ie_page_default,
4377 				       sizeof(ie_page_default));
4378 				memcpy(&lun->mode_pages.ie_page[
4379 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4380 				       sizeof(ie_page_changeable));
4381 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4382 				       &ie_page_default,
4383 				       sizeof(ie_page_default));
4384 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4385 				       &ie_page_default,
4386 				       sizeof(ie_page_default));
4387 				page_index->page_data =
4388 					(uint8_t *)lun->mode_pages.ie_page;
4389 				break;
4390 			case 0x02: {
4391 				struct ctl_logical_block_provisioning_page *page;
4392 
4393 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4394 				       &lbp_page_default,
4395 				       sizeof(lbp_page_default));
4396 				memcpy(&lun->mode_pages.lbp_page[
4397 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4398 				       sizeof(lbp_page_changeable));
4399 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4400 				       &lbp_page_default,
4401 				       sizeof(lbp_page_default));
4402 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4403 				value = dnvlist_get_string(lun->be_lun->options,
4404 				    "avail-threshold", NULL);
4405 				if (value != NULL &&
4406 				    ctl_expand_number(value, &ival) == 0) {
4407 					page->descr[0].flags |= SLBPPD_ENABLED |
4408 					    SLBPPD_ARMING_DEC;
4409 					if (lun->be_lun->blocksize)
4410 						ival /= lun->be_lun->blocksize;
4411 					else
4412 						ival /= 512;
4413 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4414 					    page->descr[0].count);
4415 				}
4416 				value = dnvlist_get_string(lun->be_lun->options,
4417 				    "used-threshold", NULL);
4418 				if (value != NULL &&
4419 				    ctl_expand_number(value, &ival) == 0) {
4420 					page->descr[1].flags |= SLBPPD_ENABLED |
4421 					    SLBPPD_ARMING_INC;
4422 					if (lun->be_lun->blocksize)
4423 						ival /= lun->be_lun->blocksize;
4424 					else
4425 						ival /= 512;
4426 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4427 					    page->descr[1].count);
4428 				}
4429 				value = dnvlist_get_string(lun->be_lun->options,
4430 				    "pool-avail-threshold", NULL);
4431 				if (value != NULL &&
4432 				    ctl_expand_number(value, &ival) == 0) {
4433 					page->descr[2].flags |= SLBPPD_ENABLED |
4434 					    SLBPPD_ARMING_DEC;
4435 					if (lun->be_lun->blocksize)
4436 						ival /= lun->be_lun->blocksize;
4437 					else
4438 						ival /= 512;
4439 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4440 					    page->descr[2].count);
4441 				}
4442 				value = dnvlist_get_string(lun->be_lun->options,
4443 				    "pool-used-threshold", NULL);
4444 				if (value != NULL &&
4445 				    ctl_expand_number(value, &ival) == 0) {
4446 					page->descr[3].flags |= SLBPPD_ENABLED |
4447 					    SLBPPD_ARMING_INC;
4448 					if (lun->be_lun->blocksize)
4449 						ival /= lun->be_lun->blocksize;
4450 					else
4451 						ival /= 512;
4452 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4453 					    page->descr[3].count);
4454 				}
4455 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4456 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4457 				       sizeof(lbp_page_default));
4458 				page_index->page_data =
4459 					(uint8_t *)lun->mode_pages.lbp_page;
4460 				break;
4461 			}
4462 			default:
4463 				panic("subpage %#x for page %#x is incorrect!",
4464 				      page_index->subpage, page_code);
4465 			}
4466 			break;
4467 		}
4468 		case SMS_CDDVD_CAPS_PAGE:{
4469 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4470 			    ("subpage %#x for page %#x is incorrect!",
4471 			    page_index->subpage, page_code));
4472 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4473 			       &cddvd_page_default,
4474 			       sizeof(cddvd_page_default));
4475 			memcpy(&lun->mode_pages.cddvd_page[
4476 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4477 			       sizeof(cddvd_page_changeable));
4478 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4479 			       &cddvd_page_default,
4480 			       sizeof(cddvd_page_default));
4481 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4482 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4483 			       sizeof(cddvd_page_default));
4484 			page_index->page_data =
4485 				(uint8_t *)lun->mode_pages.cddvd_page;
4486 			break;
4487 		}
4488 		default:
4489 			panic("invalid page code value %#x", page_code);
4490 		}
4491 	}
4492 
4493 	return (CTL_RETVAL_COMPLETE);
4494 }
4495 
4496 static int
4497 ctl_init_log_page_index(struct ctl_lun *lun)
4498 {
4499 	struct ctl_page_index *page_index;
4500 	int i, j, k, prev;
4501 
4502 	memcpy(&lun->log_pages.index, log_page_index_template,
4503 	       sizeof(log_page_index_template));
4504 
4505 	prev = -1;
4506 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4507 		page_index = &lun->log_pages.index[i];
4508 		if (lun->be_lun->lun_type == T_DIRECT &&
4509 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4510 			continue;
4511 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4512 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4513 			continue;
4514 		if (lun->be_lun->lun_type == T_CDROM &&
4515 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4516 			continue;
4517 
4518 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4519 		    lun->backend->lun_attr == NULL)
4520 			continue;
4521 
4522 		if (page_index->page_code != prev) {
4523 			lun->log_pages.pages_page[j] = page_index->page_code;
4524 			prev = page_index->page_code;
4525 			j++;
4526 		}
4527 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4528 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4529 		k++;
4530 	}
4531 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4532 	lun->log_pages.index[0].page_len = j;
4533 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4534 	lun->log_pages.index[1].page_len = k * 2;
4535 	lun->log_pages.index[2].page_data = (uint8_t *)&lun->log_pages.temp_page;
4536 	lun->log_pages.index[2].page_len = sizeof(lun->log_pages.temp_page);
4537 	lun->log_pages.index[3].page_data = &lun->log_pages.lbp_page[0];
4538 	lun->log_pages.index[3].page_len = 12*CTL_NUM_LBP_PARAMS;
4539 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.stat_page;
4540 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.stat_page);
4541 	lun->log_pages.index[5].page_data = (uint8_t *)&lun->log_pages.ie_page;
4542 	lun->log_pages.index[5].page_len = sizeof(lun->log_pages.ie_page);
4543 
4544 	return (CTL_RETVAL_COMPLETE);
4545 }
4546 
4547 static int
4548 hex2bin(const char *str, uint8_t *buf, int buf_size)
4549 {
4550 	int i;
4551 	u_char c;
4552 
4553 	memset(buf, 0, buf_size);
4554 	while (isspace(str[0]))
4555 		str++;
4556 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4557 		str += 2;
4558 	buf_size *= 2;
4559 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4560 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4561 			str++;
4562 		c = str[i];
4563 		if (isdigit(c))
4564 			c -= '0';
4565 		else if (isalpha(c))
4566 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4567 		else
4568 			break;
4569 		if (c >= 16)
4570 			break;
4571 		if ((i & 1) == 0)
4572 			buf[i / 2] |= (c << 4);
4573 		else
4574 			buf[i / 2] |= c;
4575 	}
4576 	return ((i + 1) / 2);
4577 }
4578 
4579 /*
4580  * Add LUN.
4581  *
4582  * Returns 0 for success, non-zero (errno) for failure.
4583  */
4584 int
4585 ctl_add_lun(struct ctl_be_lun *be_lun)
4586 {
4587 	struct ctl_softc *ctl_softc = control_softc;
4588 	struct ctl_lun *nlun, *lun;
4589 	struct scsi_vpd_id_descriptor *desc;
4590 	struct scsi_vpd_id_t10 *t10id;
4591 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4592 	int lun_number;
4593 	int devidlen, idlen1, idlen2 = 0, len;
4594 
4595 	/*
4596 	 * We support only Direct Access, CD-ROM or Processor LUN types.
4597 	 */
4598 	switch (be_lun->lun_type) {
4599 	case T_DIRECT:
4600 	case T_PROCESSOR:
4601 	case T_CDROM:
4602 		break;
4603 	case T_SEQUENTIAL:
4604 	case T_CHANGER:
4605 	default:
4606 		return (EINVAL);
4607 	}
4608 	lun = malloc(sizeof(*lun), M_CTL, M_WAITOK | M_ZERO);
4609 
4610 	lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4611 	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4612 	lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4613 	    M_DEVBUF, M_WAITOK | M_ZERO);
4614 	lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4615 	    M_DEVBUF, M_WAITOK | M_ZERO);
4616 
4617 	/* Generate LUN ID. */
4618 	devidlen = max(CTL_DEVID_MIN_LEN,
4619 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4620 	idlen1 = sizeof(*t10id) + devidlen;
4621 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4622 	scsiname = dnvlist_get_string(be_lun->options, "scsiname", NULL);
4623 	if (scsiname != NULL) {
4624 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4625 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4626 	}
4627 	eui = dnvlist_get_string(be_lun->options, "eui", NULL);
4628 	if (eui != NULL) {
4629 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4630 	}
4631 	naa = dnvlist_get_string(be_lun->options, "naa", NULL);
4632 	if (naa != NULL) {
4633 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4634 	}
4635 	uuid = dnvlist_get_string(be_lun->options, "uuid", NULL);
4636 	if (uuid != NULL) {
4637 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4638 	}
4639 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4640 	    M_CTL, M_WAITOK | M_ZERO);
4641 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4642 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4643 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4644 	desc->length = idlen1;
4645 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4646 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4647 	if ((vendor = dnvlist_get_string(be_lun->options, "vendor", NULL)) == NULL) {
4648 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4649 	} else {
4650 		strncpy(t10id->vendor, vendor,
4651 		    min(sizeof(t10id->vendor), strlen(vendor)));
4652 	}
4653 	strncpy((char *)t10id->vendor_spec_id,
4654 	    (char *)be_lun->device_id, devidlen);
4655 	if (scsiname != NULL) {
4656 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4657 		    desc->length);
4658 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4659 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4660 		    SVPD_ID_TYPE_SCSI_NAME;
4661 		desc->length = idlen2;
4662 		strlcpy(desc->identifier, scsiname, idlen2);
4663 	}
4664 	if (eui != NULL) {
4665 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4666 		    desc->length);
4667 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4668 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4669 		    SVPD_ID_TYPE_EUI64;
4670 		desc->length = hex2bin(eui, desc->identifier, 16);
4671 		desc->length = desc->length > 12 ? 16 :
4672 		    (desc->length > 8 ? 12 : 8);
4673 		len -= 16 - desc->length;
4674 	}
4675 	if (naa != NULL) {
4676 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4677 		    desc->length);
4678 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4679 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4680 		    SVPD_ID_TYPE_NAA;
4681 		desc->length = hex2bin(naa, desc->identifier, 16);
4682 		desc->length = desc->length > 8 ? 16 : 8;
4683 		len -= 16 - desc->length;
4684 	}
4685 	if (uuid != NULL) {
4686 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4687 		    desc->length);
4688 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4689 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4690 		    SVPD_ID_TYPE_UUID;
4691 		desc->identifier[0] = 0x10;
4692 		hex2bin(uuid, &desc->identifier[2], 16);
4693 		desc->length = 18;
4694 	}
4695 	lun->lun_devid->len = len;
4696 
4697 	mtx_lock(&ctl_softc->ctl_lock);
4698 	/*
4699 	 * See if the caller requested a particular LUN number.  If so, see
4700 	 * if it is available.  Otherwise, allocate the first available LUN.
4701 	 */
4702 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4703 		if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4704 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4705 			mtx_unlock(&ctl_softc->ctl_lock);
4706 			if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4707 				printf("ctl: requested LUN ID %d is higher "
4708 				       "than ctl_max_luns - 1 (%d)\n",
4709 				       be_lun->req_lun_id, ctl_max_luns - 1);
4710 			} else {
4711 				/*
4712 				 * XXX KDM return an error, or just assign
4713 				 * another LUN ID in this case??
4714 				 */
4715 				printf("ctl: requested LUN ID %d is already "
4716 				       "in use\n", be_lun->req_lun_id);
4717 			}
4718 fail:
4719 			free(lun->lun_devid, M_CTL);
4720 			free(lun, M_CTL);
4721 			return (ENOSPC);
4722 		}
4723 		lun_number = be_lun->req_lun_id;
4724 	} else {
4725 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4726 		if (lun_number == -1) {
4727 			mtx_unlock(&ctl_softc->ctl_lock);
4728 			printf("ctl: can't allocate LUN, out of LUNs\n");
4729 			goto fail;
4730 		}
4731 	}
4732 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4733 	mtx_unlock(&ctl_softc->ctl_lock);
4734 
4735 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4736 	lun->lun = lun_number;
4737 	lun->be_lun = be_lun;
4738 	/*
4739 	 * The processor LUN is always enabled.  Disk LUNs come on line
4740 	 * disabled, and must be enabled by the backend.
4741 	 */
4742 	lun->flags |= CTL_LUN_DISABLED;
4743 	lun->backend = be_lun->be;
4744 	be_lun->ctl_lun = lun;
4745 	be_lun->lun_id = lun_number;
4746 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4747 		lun->flags |= CTL_LUN_EJECTED;
4748 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4749 		lun->flags |= CTL_LUN_NO_MEDIA;
4750 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4751 		lun->flags |= CTL_LUN_STOPPED;
4752 
4753 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4754 		lun->flags |= CTL_LUN_PRIMARY_SC;
4755 
4756 	value = dnvlist_get_string(be_lun->options, "removable", NULL);
4757 	if (value != NULL) {
4758 		if (strcmp(value, "on") == 0)
4759 			lun->flags |= CTL_LUN_REMOVABLE;
4760 	} else if (be_lun->lun_type == T_CDROM)
4761 		lun->flags |= CTL_LUN_REMOVABLE;
4762 
4763 	lun->ctl_softc = ctl_softc;
4764 #ifdef CTL_TIME_IO
4765 	lun->last_busy = getsbinuptime();
4766 #endif
4767 	LIST_INIT(&lun->ooa_queue);
4768 	STAILQ_INIT(&lun->error_list);
4769 	lun->ie_reported = 1;
4770 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4771 	ctl_tpc_lun_init(lun);
4772 	if (lun->flags & CTL_LUN_REMOVABLE) {
4773 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4774 		    M_CTL, M_WAITOK);
4775 	}
4776 
4777 	/*
4778 	 * Initialize the mode and log page index.
4779 	 */
4780 	ctl_init_page_index(lun);
4781 	ctl_init_log_page_index(lun);
4782 
4783 	/* Setup statistics gathering */
4784 	lun->stats.item = lun_number;
4785 
4786 	/*
4787 	 * Now, before we insert this lun on the lun list, set the lun
4788 	 * inventory changed UA for all other luns.
4789 	 */
4790 	mtx_lock(&ctl_softc->ctl_lock);
4791 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4792 		mtx_lock(&nlun->lun_lock);
4793 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4794 		mtx_unlock(&nlun->lun_lock);
4795 	}
4796 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4797 	ctl_softc->ctl_luns[lun_number] = lun;
4798 	ctl_softc->num_luns++;
4799 	mtx_unlock(&ctl_softc->ctl_lock);
4800 
4801 	/*
4802 	 * We successfully added the LUN, attempt to enable it.
4803 	 */
4804 	if (ctl_enable_lun(lun) != 0) {
4805 		printf("%s: ctl_enable_lun() failed!\n", __func__);
4806 		mtx_lock(&ctl_softc->ctl_lock);
4807 		STAILQ_REMOVE(&ctl_softc->lun_list, lun, ctl_lun, links);
4808 		ctl_clear_mask(ctl_softc->ctl_lun_mask, lun_number);
4809 		ctl_softc->ctl_luns[lun_number] = NULL;
4810 		ctl_softc->num_luns--;
4811 		mtx_unlock(&ctl_softc->ctl_lock);
4812 		free(lun->lun_devid, M_CTL);
4813 		free(lun, M_CTL);
4814 		return (EIO);
4815 	}
4816 
4817 	return (0);
4818 }
4819 
4820 /*
4821  * Free LUN that has no active requests.
4822  */
4823 static int
4824 ctl_free_lun(struct ctl_lun *lun)
4825 {
4826 	struct ctl_softc *softc = lun->ctl_softc;
4827 	struct ctl_lun *nlun;
4828 	int i;
4829 
4830 	KASSERT(LIST_EMPTY(&lun->ooa_queue),
4831 	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4832 
4833 	mtx_lock(&softc->ctl_lock);
4834 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4835 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4836 	softc->ctl_luns[lun->lun] = NULL;
4837 	softc->num_luns--;
4838 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4839 		mtx_lock(&nlun->lun_lock);
4840 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4841 		mtx_unlock(&nlun->lun_lock);
4842 	}
4843 	mtx_unlock(&softc->ctl_lock);
4844 
4845 	/*
4846 	 * Tell the backend to free resources, if this LUN has a backend.
4847 	 */
4848 	lun->be_lun->lun_shutdown(lun->be_lun);
4849 
4850 	lun->ie_reportcnt = UINT32_MAX;
4851 	callout_drain(&lun->ie_callout);
4852 	ctl_tpc_lun_shutdown(lun);
4853 	mtx_destroy(&lun->lun_lock);
4854 	free(lun->lun_devid, M_CTL);
4855 	for (i = 0; i < ctl_max_ports; i++)
4856 		free(lun->pending_ua[i], M_CTL);
4857 	free(lun->pending_ua, M_DEVBUF);
4858 	for (i = 0; i < ctl_max_ports; i++)
4859 		free(lun->pr_keys[i], M_CTL);
4860 	free(lun->pr_keys, M_DEVBUF);
4861 	free(lun->write_buffer, M_CTL);
4862 	free(lun->prevent, M_CTL);
4863 	free(lun, M_CTL);
4864 
4865 	return (0);
4866 }
4867 
4868 static int
4869 ctl_enable_lun(struct ctl_lun *lun)
4870 {
4871 	struct ctl_softc *softc;
4872 	struct ctl_port *port, *nport;
4873 	int retval;
4874 
4875 	softc = lun->ctl_softc;
4876 
4877 	mtx_lock(&softc->ctl_lock);
4878 	mtx_lock(&lun->lun_lock);
4879 	KASSERT((lun->flags & CTL_LUN_DISABLED) != 0,
4880 	    ("%s: LUN not disabled", __func__));
4881 	lun->flags &= ~CTL_LUN_DISABLED;
4882 	mtx_unlock(&lun->lun_lock);
4883 
4884 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4885 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4886 		    port->lun_map != NULL || port->lun_enable == NULL)
4887 			continue;
4888 
4889 		/*
4890 		 * Drop the lock while we call the FETD's enable routine.
4891 		 * This can lead to a callback into CTL (at least in the
4892 		 * case of the internal initiator frontend.
4893 		 */
4894 		mtx_unlock(&softc->ctl_lock);
4895 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4896 		mtx_lock(&softc->ctl_lock);
4897 		if (retval != 0) {
4898 			printf("%s: FETD %s port %d returned error "
4899 			       "%d for lun_enable on lun %jd\n",
4900 			       __func__, port->port_name, port->targ_port,
4901 			       retval, (intmax_t)lun->lun);
4902 		}
4903 	}
4904 
4905 	mtx_unlock(&softc->ctl_lock);
4906 	ctl_isc_announce_lun(lun);
4907 
4908 	return (0);
4909 }
4910 
4911 static int
4912 ctl_disable_lun(struct ctl_lun *lun)
4913 {
4914 	struct ctl_softc *softc;
4915 	struct ctl_port *port;
4916 	int retval;
4917 
4918 	softc = lun->ctl_softc;
4919 
4920 	mtx_lock(&softc->ctl_lock);
4921 	mtx_lock(&lun->lun_lock);
4922 	KASSERT((lun->flags & CTL_LUN_DISABLED) == 0,
4923 	    ("%s: LUN not enabled", __func__));
4924 	lun->flags |= CTL_LUN_DISABLED;
4925 	mtx_unlock(&lun->lun_lock);
4926 
4927 	STAILQ_FOREACH(port, &softc->port_list, links) {
4928 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4929 		    port->lun_map != NULL || port->lun_disable == NULL)
4930 			continue;
4931 
4932 		/*
4933 		 * Drop the lock before we call the frontend's disable
4934 		 * routine, to avoid lock order reversals.
4935 		 *
4936 		 * XXX KDM what happens if the frontend list changes while
4937 		 * we're traversing it?  It's unlikely, but should be handled.
4938 		 */
4939 		mtx_unlock(&softc->ctl_lock);
4940 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4941 		mtx_lock(&softc->ctl_lock);
4942 		if (retval != 0) {
4943 			printf("%s: FETD %s port %d returned error "
4944 			       "%d for lun_disable on lun %jd\n",
4945 			       __func__, port->port_name, port->targ_port,
4946 			       retval, (intmax_t)lun->lun);
4947 		}
4948 	}
4949 
4950 	mtx_unlock(&softc->ctl_lock);
4951 	ctl_isc_announce_lun(lun);
4952 
4953 	return (0);
4954 }
4955 
4956 int
4957 ctl_start_lun(struct ctl_be_lun *be_lun)
4958 {
4959 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4960 
4961 	mtx_lock(&lun->lun_lock);
4962 	lun->flags &= ~CTL_LUN_STOPPED;
4963 	mtx_unlock(&lun->lun_lock);
4964 	return (0);
4965 }
4966 
4967 int
4968 ctl_stop_lun(struct ctl_be_lun *be_lun)
4969 {
4970 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4971 
4972 	mtx_lock(&lun->lun_lock);
4973 	lun->flags |= CTL_LUN_STOPPED;
4974 	mtx_unlock(&lun->lun_lock);
4975 	return (0);
4976 }
4977 
4978 int
4979 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4980 {
4981 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4982 
4983 	mtx_lock(&lun->lun_lock);
4984 	lun->flags |= CTL_LUN_NO_MEDIA;
4985 	mtx_unlock(&lun->lun_lock);
4986 	return (0);
4987 }
4988 
4989 int
4990 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4991 {
4992 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4993 	union ctl_ha_msg msg;
4994 
4995 	mtx_lock(&lun->lun_lock);
4996 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4997 	if (lun->flags & CTL_LUN_REMOVABLE)
4998 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4999 	mtx_unlock(&lun->lun_lock);
5000 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
5001 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5002 		bzero(&msg.ua, sizeof(msg.ua));
5003 		msg.hdr.msg_type = CTL_MSG_UA;
5004 		msg.hdr.nexus.initid = -1;
5005 		msg.hdr.nexus.targ_port = -1;
5006 		msg.hdr.nexus.targ_lun = lun->lun;
5007 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5008 		msg.ua.ua_all = 1;
5009 		msg.ua.ua_set = 1;
5010 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
5011 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5012 		    M_WAITOK);
5013 	}
5014 	return (0);
5015 }
5016 
5017 int
5018 ctl_lun_ejected(struct ctl_be_lun *be_lun)
5019 {
5020 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5021 
5022 	mtx_lock(&lun->lun_lock);
5023 	lun->flags |= CTL_LUN_EJECTED;
5024 	mtx_unlock(&lun->lun_lock);
5025 	return (0);
5026 }
5027 
5028 int
5029 ctl_lun_primary(struct ctl_be_lun *be_lun)
5030 {
5031 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5032 
5033 	mtx_lock(&lun->lun_lock);
5034 	lun->flags |= CTL_LUN_PRIMARY_SC;
5035 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5036 	mtx_unlock(&lun->lun_lock);
5037 	ctl_isc_announce_lun(lun);
5038 	return (0);
5039 }
5040 
5041 int
5042 ctl_lun_secondary(struct ctl_be_lun *be_lun)
5043 {
5044 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5045 
5046 	mtx_lock(&lun->lun_lock);
5047 	lun->flags &= ~CTL_LUN_PRIMARY_SC;
5048 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5049 	mtx_unlock(&lun->lun_lock);
5050 	ctl_isc_announce_lun(lun);
5051 	return (0);
5052 }
5053 
5054 /*
5055  * Remove LUN.  If there are active requests, wait for completion.
5056  *
5057  * Returns 0 for success, non-zero (errno) for failure.
5058  * Completion is reported to backed via the lun_shutdown() method.
5059  */
5060 int
5061 ctl_remove_lun(struct ctl_be_lun *be_lun)
5062 {
5063 	struct ctl_lun *lun;
5064 
5065 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5066 
5067 	ctl_disable_lun(lun);
5068 
5069 	mtx_lock(&lun->lun_lock);
5070 	lun->flags |= CTL_LUN_INVALID;
5071 
5072 	/*
5073 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5074 	 * If we have something in the OOA queue, we'll free it when the
5075 	 * last I/O completes.
5076 	 */
5077 	if (LIST_EMPTY(&lun->ooa_queue)) {
5078 		mtx_unlock(&lun->lun_lock);
5079 		ctl_free_lun(lun);
5080 	} else
5081 		mtx_unlock(&lun->lun_lock);
5082 
5083 	return (0);
5084 }
5085 
5086 void
5087 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5088 {
5089 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5090 	union ctl_ha_msg msg;
5091 
5092 	mtx_lock(&lun->lun_lock);
5093 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5094 	mtx_unlock(&lun->lun_lock);
5095 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5096 		/* Send msg to other side. */
5097 		bzero(&msg.ua, sizeof(msg.ua));
5098 		msg.hdr.msg_type = CTL_MSG_UA;
5099 		msg.hdr.nexus.initid = -1;
5100 		msg.hdr.nexus.targ_port = -1;
5101 		msg.hdr.nexus.targ_lun = lun->lun;
5102 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5103 		msg.ua.ua_all = 1;
5104 		msg.ua.ua_set = 1;
5105 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5106 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5107 		    M_WAITOK);
5108 	}
5109 }
5110 
5111 /*
5112  * Backend "memory move is complete" callback for requests that never
5113  * make it down to say RAIDCore's configuration code.
5114  */
5115 int
5116 ctl_config_move_done(union ctl_io *io, bool samethr)
5117 {
5118 	int retval;
5119 
5120 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5121 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5122 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
5123 
5124 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5125 		ctl_data_print(io);
5126 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5127 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5128 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5129 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5130 		/*
5131 		 * XXX KDM just assuming a single pointer here, and not a
5132 		 * S/G list.  If we start using S/G lists for config data,
5133 		 * we'll need to know how to clean them up here as well.
5134 		 */
5135 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5136 			free(io->scsiio.kern_data_ptr, M_CTL);
5137 		ctl_done(io);
5138 		retval = CTL_RETVAL_COMPLETE;
5139 	} else {
5140 		/*
5141 		 * XXX KDM now we need to continue data movement.  Some
5142 		 * options:
5143 		 * - call ctl_scsiio() again?  We don't do this for data
5144 		 *   writes, because for those at least we know ahead of
5145 		 *   time where the write will go and how long it is.  For
5146 		 *   config writes, though, that information is largely
5147 		 *   contained within the write itself, thus we need to
5148 		 *   parse out the data again.
5149 		 *
5150 		 * - Call some other function once the data is in?
5151 		 */
5152 
5153 		/*
5154 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5155 		 * bits to see whether we're allocated or not.
5156 		 */
5157 		retval = ctl_scsiio(&io->scsiio);
5158 	}
5159 	return (retval);
5160 }
5161 
5162 /*
5163  * This gets called by a backend driver when it is done with a
5164  * data_submit method.
5165  */
5166 void
5167 ctl_data_submit_done(union ctl_io *io)
5168 {
5169 	/*
5170 	 * If the IO_CONT flag is set, we need to call the supplied
5171 	 * function to continue processing the I/O, instead of completing
5172 	 * the I/O just yet.
5173 	 *
5174 	 * If there is an error, though, we don't want to keep processing.
5175 	 * Instead, just send status back to the initiator.
5176 	 */
5177 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5178 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5179 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5180 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5181 		io->scsiio.io_cont(io);
5182 		return;
5183 	}
5184 	ctl_done(io);
5185 }
5186 
5187 /*
5188  * This gets called by a backend driver when it is done with a
5189  * configuration write.
5190  */
5191 void
5192 ctl_config_write_done(union ctl_io *io)
5193 {
5194 	uint8_t *buf;
5195 
5196 	/*
5197 	 * If the IO_CONT flag is set, we need to call the supplied
5198 	 * function to continue processing the I/O, instead of completing
5199 	 * the I/O just yet.
5200 	 *
5201 	 * If there is an error, though, we don't want to keep processing.
5202 	 * Instead, just send status back to the initiator.
5203 	 */
5204 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5205 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5206 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5207 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5208 		io->scsiio.io_cont(io);
5209 		return;
5210 	}
5211 	/*
5212 	 * Since a configuration write can be done for commands that actually
5213 	 * have data allocated, like write buffer, and commands that have
5214 	 * no data, like start/stop unit, we need to check here.
5215 	 */
5216 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5217 		buf = io->scsiio.kern_data_ptr;
5218 	else
5219 		buf = NULL;
5220 	ctl_done(io);
5221 	if (buf)
5222 		free(buf, M_CTL);
5223 }
5224 
5225 void
5226 ctl_config_read_done(union ctl_io *io)
5227 {
5228 	uint8_t *buf;
5229 
5230 	/*
5231 	 * If there is some error -- we are done, skip data transfer.
5232 	 */
5233 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5234 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5235 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5236 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5237 			buf = io->scsiio.kern_data_ptr;
5238 		else
5239 			buf = NULL;
5240 		ctl_done(io);
5241 		if (buf)
5242 			free(buf, M_CTL);
5243 		return;
5244 	}
5245 
5246 	/*
5247 	 * If the IO_CONT flag is set, we need to call the supplied
5248 	 * function to continue processing the I/O, instead of completing
5249 	 * the I/O just yet.
5250 	 */
5251 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5252 		io->scsiio.io_cont(io);
5253 		return;
5254 	}
5255 
5256 	ctl_datamove(io);
5257 }
5258 
5259 /*
5260  * SCSI release command.
5261  */
5262 int
5263 ctl_scsi_release(struct ctl_scsiio *ctsio)
5264 {
5265 	struct ctl_lun *lun = CTL_LUN(ctsio);
5266 	uint32_t residx;
5267 
5268 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5269 
5270 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5271 
5272 	/*
5273 	 * XXX KDM right now, we only support LUN reservation.  We don't
5274 	 * support 3rd party reservations, or extent reservations, which
5275 	 * might actually need the parameter list.  If we've gotten this
5276 	 * far, we've got a LUN reservation.  Anything else got kicked out
5277 	 * above.  So, according to SPC, ignore the length.
5278 	 */
5279 
5280 	mtx_lock(&lun->lun_lock);
5281 
5282 	/*
5283 	 * According to SPC, it is not an error for an intiator to attempt
5284 	 * to release a reservation on a LUN that isn't reserved, or that
5285 	 * is reserved by another initiator.  The reservation can only be
5286 	 * released, though, by the initiator who made it or by one of
5287 	 * several reset type events.
5288 	 */
5289 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5290 			lun->flags &= ~CTL_LUN_RESERVED;
5291 
5292 	mtx_unlock(&lun->lun_lock);
5293 
5294 	ctl_set_success(ctsio);
5295 	ctl_done((union ctl_io *)ctsio);
5296 	return (CTL_RETVAL_COMPLETE);
5297 }
5298 
5299 int
5300 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5301 {
5302 	struct ctl_lun *lun = CTL_LUN(ctsio);
5303 	uint32_t residx;
5304 
5305 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5306 
5307 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5308 
5309 	/*
5310 	 * XXX KDM right now, we only support LUN reservation.  We don't
5311 	 * support 3rd party reservations, or extent reservations, which
5312 	 * might actually need the parameter list.  If we've gotten this
5313 	 * far, we've got a LUN reservation.  Anything else got kicked out
5314 	 * above.  So, according to SPC, ignore the length.
5315 	 */
5316 
5317 	mtx_lock(&lun->lun_lock);
5318 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5319 		ctl_set_reservation_conflict(ctsio);
5320 		goto bailout;
5321 	}
5322 
5323 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5324 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5325 		ctl_set_success(ctsio);
5326 		goto bailout;
5327 	}
5328 
5329 	lun->flags |= CTL_LUN_RESERVED;
5330 	lun->res_idx = residx;
5331 	ctl_set_success(ctsio);
5332 
5333 bailout:
5334 	mtx_unlock(&lun->lun_lock);
5335 	ctl_done((union ctl_io *)ctsio);
5336 	return (CTL_RETVAL_COMPLETE);
5337 }
5338 
5339 int
5340 ctl_start_stop(struct ctl_scsiio *ctsio)
5341 {
5342 	struct ctl_lun *lun = CTL_LUN(ctsio);
5343 	struct scsi_start_stop_unit *cdb;
5344 	int retval;
5345 
5346 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5347 
5348 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5349 
5350 	if ((cdb->how & SSS_PC_MASK) == 0) {
5351 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5352 		    (cdb->how & SSS_START) == 0) {
5353 			uint32_t residx;
5354 
5355 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5356 			if (ctl_get_prkey(lun, residx) == 0 ||
5357 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5358 				ctl_set_reservation_conflict(ctsio);
5359 				ctl_done((union ctl_io *)ctsio);
5360 				return (CTL_RETVAL_COMPLETE);
5361 			}
5362 		}
5363 
5364 		if ((cdb->how & SSS_LOEJ) &&
5365 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5366 			ctl_set_invalid_field(ctsio,
5367 					      /*sks_valid*/ 1,
5368 					      /*command*/ 1,
5369 					      /*field*/ 4,
5370 					      /*bit_valid*/ 1,
5371 					      /*bit*/ 1);
5372 			ctl_done((union ctl_io *)ctsio);
5373 			return (CTL_RETVAL_COMPLETE);
5374 		}
5375 
5376 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5377 		    lun->prevent_count > 0) {
5378 			/* "Medium removal prevented" */
5379 			ctl_set_sense(ctsio, /*current_error*/ 1,
5380 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5381 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5382 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5383 			ctl_done((union ctl_io *)ctsio);
5384 			return (CTL_RETVAL_COMPLETE);
5385 		}
5386 	}
5387 
5388 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5389 	return (retval);
5390 }
5391 
5392 int
5393 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5394 {
5395 	struct ctl_lun *lun = CTL_LUN(ctsio);
5396 	struct scsi_prevent *cdb;
5397 	int retval;
5398 	uint32_t initidx;
5399 
5400 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5401 
5402 	cdb = (struct scsi_prevent *)ctsio->cdb;
5403 
5404 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5405 		ctl_set_invalid_opcode(ctsio);
5406 		ctl_done((union ctl_io *)ctsio);
5407 		return (CTL_RETVAL_COMPLETE);
5408 	}
5409 
5410 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5411 	mtx_lock(&lun->lun_lock);
5412 	if ((cdb->how & PR_PREVENT) &&
5413 	    ctl_is_set(lun->prevent, initidx) == 0) {
5414 		ctl_set_mask(lun->prevent, initidx);
5415 		lun->prevent_count++;
5416 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5417 	    ctl_is_set(lun->prevent, initidx)) {
5418 		ctl_clear_mask(lun->prevent, initidx);
5419 		lun->prevent_count--;
5420 	}
5421 	mtx_unlock(&lun->lun_lock);
5422 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5423 	return (retval);
5424 }
5425 
5426 /*
5427  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5428  * we don't really do anything with the LBA and length fields if the user
5429  * passes them in.  Instead we'll just flush out the cache for the entire
5430  * LUN.
5431  */
5432 int
5433 ctl_sync_cache(struct ctl_scsiio *ctsio)
5434 {
5435 	struct ctl_lun *lun = CTL_LUN(ctsio);
5436 	struct ctl_lba_len_flags *lbalen;
5437 	uint64_t starting_lba;
5438 	uint32_t block_count;
5439 	int retval;
5440 	uint8_t byte2;
5441 
5442 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5443 
5444 	retval = 0;
5445 
5446 	switch (ctsio->cdb[0]) {
5447 	case SYNCHRONIZE_CACHE: {
5448 		struct scsi_sync_cache *cdb;
5449 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5450 
5451 		starting_lba = scsi_4btoul(cdb->begin_lba);
5452 		block_count = scsi_2btoul(cdb->lb_count);
5453 		byte2 = cdb->byte2;
5454 		break;
5455 	}
5456 	case SYNCHRONIZE_CACHE_16: {
5457 		struct scsi_sync_cache_16 *cdb;
5458 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5459 
5460 		starting_lba = scsi_8btou64(cdb->begin_lba);
5461 		block_count = scsi_4btoul(cdb->lb_count);
5462 		byte2 = cdb->byte2;
5463 		break;
5464 	}
5465 	default:
5466 		ctl_set_invalid_opcode(ctsio);
5467 		ctl_done((union ctl_io *)ctsio);
5468 		goto bailout;
5469 		break; /* NOTREACHED */
5470 	}
5471 
5472 	/*
5473 	 * We check the LBA and length, but don't do anything with them.
5474 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5475 	 * get flushed.  This check will just help satisfy anyone who wants
5476 	 * to see an error for an out of range LBA.
5477 	 */
5478 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5479 		ctl_set_lba_out_of_range(ctsio,
5480 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5481 		ctl_done((union ctl_io *)ctsio);
5482 		goto bailout;
5483 	}
5484 
5485 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5486 	lbalen->lba = starting_lba;
5487 	lbalen->len = block_count;
5488 	lbalen->flags = byte2;
5489 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5490 
5491 bailout:
5492 	return (retval);
5493 }
5494 
5495 int
5496 ctl_format(struct ctl_scsiio *ctsio)
5497 {
5498 	struct scsi_format *cdb;
5499 	int length, defect_list_len;
5500 
5501 	CTL_DEBUG_PRINT(("ctl_format\n"));
5502 
5503 	cdb = (struct scsi_format *)ctsio->cdb;
5504 
5505 	length = 0;
5506 	if (cdb->byte2 & SF_FMTDATA) {
5507 		if (cdb->byte2 & SF_LONGLIST)
5508 			length = sizeof(struct scsi_format_header_long);
5509 		else
5510 			length = sizeof(struct scsi_format_header_short);
5511 	}
5512 
5513 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5514 	 && (length > 0)) {
5515 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5516 		ctsio->kern_data_len = length;
5517 		ctsio->kern_total_len = length;
5518 		ctsio->kern_rel_offset = 0;
5519 		ctsio->kern_sg_entries = 0;
5520 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5521 		ctsio->be_move_done = ctl_config_move_done;
5522 		ctl_datamove((union ctl_io *)ctsio);
5523 
5524 		return (CTL_RETVAL_COMPLETE);
5525 	}
5526 
5527 	defect_list_len = 0;
5528 
5529 	if (cdb->byte2 & SF_FMTDATA) {
5530 		if (cdb->byte2 & SF_LONGLIST) {
5531 			struct scsi_format_header_long *header;
5532 
5533 			header = (struct scsi_format_header_long *)
5534 				ctsio->kern_data_ptr;
5535 
5536 			defect_list_len = scsi_4btoul(header->defect_list_len);
5537 			if (defect_list_len != 0) {
5538 				ctl_set_invalid_field(ctsio,
5539 						      /*sks_valid*/ 1,
5540 						      /*command*/ 0,
5541 						      /*field*/ 2,
5542 						      /*bit_valid*/ 0,
5543 						      /*bit*/ 0);
5544 				goto bailout;
5545 			}
5546 		} else {
5547 			struct scsi_format_header_short *header;
5548 
5549 			header = (struct scsi_format_header_short *)
5550 				ctsio->kern_data_ptr;
5551 
5552 			defect_list_len = scsi_2btoul(header->defect_list_len);
5553 			if (defect_list_len != 0) {
5554 				ctl_set_invalid_field(ctsio,
5555 						      /*sks_valid*/ 1,
5556 						      /*command*/ 0,
5557 						      /*field*/ 2,
5558 						      /*bit_valid*/ 0,
5559 						      /*bit*/ 0);
5560 				goto bailout;
5561 			}
5562 		}
5563 	}
5564 
5565 	ctl_set_success(ctsio);
5566 bailout:
5567 
5568 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5569 		free(ctsio->kern_data_ptr, M_CTL);
5570 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5571 	}
5572 
5573 	ctl_done((union ctl_io *)ctsio);
5574 	return (CTL_RETVAL_COMPLETE);
5575 }
5576 
5577 int
5578 ctl_read_buffer(struct ctl_scsiio *ctsio)
5579 {
5580 	struct ctl_lun *lun = CTL_LUN(ctsio);
5581 	uint64_t buffer_offset;
5582 	uint32_t len;
5583 	uint8_t byte2;
5584 	static uint8_t descr[4];
5585 	static uint8_t echo_descr[4] = { 0 };
5586 
5587 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5588 
5589 	switch (ctsio->cdb[0]) {
5590 	case READ_BUFFER: {
5591 		struct scsi_read_buffer *cdb;
5592 
5593 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5594 		buffer_offset = scsi_3btoul(cdb->offset);
5595 		len = scsi_3btoul(cdb->length);
5596 		byte2 = cdb->byte2;
5597 		break;
5598 	}
5599 	case READ_BUFFER_16: {
5600 		struct scsi_read_buffer_16 *cdb;
5601 
5602 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5603 		buffer_offset = scsi_8btou64(cdb->offset);
5604 		len = scsi_4btoul(cdb->length);
5605 		byte2 = cdb->byte2;
5606 		break;
5607 	}
5608 	default: /* This shouldn't happen. */
5609 		ctl_set_invalid_opcode(ctsio);
5610 		ctl_done((union ctl_io *)ctsio);
5611 		return (CTL_RETVAL_COMPLETE);
5612 	}
5613 
5614 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5615 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5616 		ctl_set_invalid_field(ctsio,
5617 				      /*sks_valid*/ 1,
5618 				      /*command*/ 1,
5619 				      /*field*/ 6,
5620 				      /*bit_valid*/ 0,
5621 				      /*bit*/ 0);
5622 		ctl_done((union ctl_io *)ctsio);
5623 		return (CTL_RETVAL_COMPLETE);
5624 	}
5625 
5626 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5627 		descr[0] = 0;
5628 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5629 		ctsio->kern_data_ptr = descr;
5630 		len = min(len, sizeof(descr));
5631 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5632 		ctsio->kern_data_ptr = echo_descr;
5633 		len = min(len, sizeof(echo_descr));
5634 	} else {
5635 		if (lun->write_buffer == NULL) {
5636 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5637 			    M_CTL, M_WAITOK | M_ZERO);
5638 		}
5639 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5640 	}
5641 	ctsio->kern_data_len = len;
5642 	ctsio->kern_total_len = len;
5643 	ctsio->kern_rel_offset = 0;
5644 	ctsio->kern_sg_entries = 0;
5645 	ctl_set_success(ctsio);
5646 	ctsio->be_move_done = ctl_config_move_done;
5647 	ctl_datamove((union ctl_io *)ctsio);
5648 	return (CTL_RETVAL_COMPLETE);
5649 }
5650 
5651 int
5652 ctl_write_buffer(struct ctl_scsiio *ctsio)
5653 {
5654 	struct ctl_lun *lun = CTL_LUN(ctsio);
5655 	struct scsi_write_buffer *cdb;
5656 	int buffer_offset, len;
5657 
5658 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5659 
5660 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5661 
5662 	len = scsi_3btoul(cdb->length);
5663 	buffer_offset = scsi_3btoul(cdb->offset);
5664 
5665 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5666 		ctl_set_invalid_field(ctsio,
5667 				      /*sks_valid*/ 1,
5668 				      /*command*/ 1,
5669 				      /*field*/ 6,
5670 				      /*bit_valid*/ 0,
5671 				      /*bit*/ 0);
5672 		ctl_done((union ctl_io *)ctsio);
5673 		return (CTL_RETVAL_COMPLETE);
5674 	}
5675 
5676 	if (lun->write_buffer == NULL) {
5677 		lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5678 			    M_CTL, M_WAITOK | M_ZERO);
5679 	}
5680 
5681 	/*
5682 	 * If this kernel request hasn't started yet, initialize the data
5683 	 * buffer to the correct region of the LUN's write buffer.  Note that
5684 	 * this doesn't set CTL_FLAG_ALLOCATED since this points into a
5685 	 * persistent buffer belonging to the LUN rather than a buffer
5686 	 * dedicated to this request.
5687 	 */
5688 	if (ctsio->kern_data_ptr == NULL) {
5689 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5690 		ctsio->kern_data_len = len;
5691 		ctsio->kern_total_len = len;
5692 		ctsio->kern_rel_offset = 0;
5693 		ctsio->kern_sg_entries = 0;
5694 		ctsio->be_move_done = ctl_config_move_done;
5695 		ctl_datamove((union ctl_io *)ctsio);
5696 
5697 		return (CTL_RETVAL_COMPLETE);
5698 	}
5699 
5700 	ctl_set_success(ctsio);
5701 	ctl_done((union ctl_io *)ctsio);
5702 	return (CTL_RETVAL_COMPLETE);
5703 }
5704 
5705 static int
5706 ctl_write_same_cont(union ctl_io *io)
5707 {
5708 	struct ctl_lun *lun = CTL_LUN(io);
5709 	struct ctl_scsiio *ctsio;
5710 	struct ctl_lba_len_flags *lbalen;
5711 	int retval;
5712 
5713 	ctsio = &io->scsiio;
5714 	ctsio->io_hdr.status = CTL_STATUS_NONE;
5715 	lbalen = (struct ctl_lba_len_flags *)
5716 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5717 	lbalen->lba += lbalen->len;
5718 	if ((lun->be_lun->maxlba + 1) - lbalen->lba <= UINT32_MAX) {
5719 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
5720 		lbalen->len = (lun->be_lun->maxlba + 1) - lbalen->lba;
5721 	}
5722 
5723 	CTL_DEBUG_PRINT(("ctl_write_same_cont: calling config_write()\n"));
5724 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5725 	return (retval);
5726 }
5727 
5728 int
5729 ctl_write_same(struct ctl_scsiio *ctsio)
5730 {
5731 	struct ctl_lun *lun = CTL_LUN(ctsio);
5732 	struct ctl_lba_len_flags *lbalen;
5733 	const char *val;
5734 	uint64_t lba, ival;
5735 	uint32_t num_blocks;
5736 	int len, retval;
5737 	uint8_t byte2;
5738 
5739 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5740 
5741 	switch (ctsio->cdb[0]) {
5742 	case WRITE_SAME_10: {
5743 		struct scsi_write_same_10 *cdb;
5744 
5745 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5746 
5747 		lba = scsi_4btoul(cdb->addr);
5748 		num_blocks = scsi_2btoul(cdb->length);
5749 		byte2 = cdb->byte2;
5750 		break;
5751 	}
5752 	case WRITE_SAME_16: {
5753 		struct scsi_write_same_16 *cdb;
5754 
5755 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5756 
5757 		lba = scsi_8btou64(cdb->addr);
5758 		num_blocks = scsi_4btoul(cdb->length);
5759 		byte2 = cdb->byte2;
5760 		break;
5761 	}
5762 	default:
5763 		/*
5764 		 * We got a command we don't support.  This shouldn't
5765 		 * happen, commands should be filtered out above us.
5766 		 */
5767 		ctl_set_invalid_opcode(ctsio);
5768 		ctl_done((union ctl_io *)ctsio);
5769 
5770 		return (CTL_RETVAL_COMPLETE);
5771 		break; /* NOTREACHED */
5772 	}
5773 
5774 	/* ANCHOR flag can be used only together with UNMAP */
5775 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5776 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5777 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5778 		ctl_done((union ctl_io *)ctsio);
5779 		return (CTL_RETVAL_COMPLETE);
5780 	}
5781 
5782 	/*
5783 	 * The first check is to make sure we're in bounds, the second
5784 	 * check is to catch wrap-around problems.  If the lba + num blocks
5785 	 * is less than the lba, then we've wrapped around and the block
5786 	 * range is invalid anyway.
5787 	 */
5788 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5789 	 || ((lba + num_blocks) < lba)) {
5790 		ctl_set_lba_out_of_range(ctsio,
5791 		    MAX(lba, lun->be_lun->maxlba + 1));
5792 		ctl_done((union ctl_io *)ctsio);
5793 		return (CTL_RETVAL_COMPLETE);
5794 	}
5795 
5796 	/* Zero number of blocks means "to the last logical block" */
5797 	if (num_blocks == 0) {
5798 		ival = UINT64_MAX;
5799 		val = dnvlist_get_string(lun->be_lun->options,
5800 		    "write_same_max_lba", NULL);
5801 		if (val != NULL)
5802 			ctl_expand_number(val, &ival);
5803 		if ((lun->be_lun->maxlba + 1) - lba > ival) {
5804 			ctl_set_invalid_field(ctsio,
5805 			    /*sks_valid*/ 1, /*command*/ 1,
5806 			    /*field*/ ctsio->cdb[0] == WRITE_SAME_10 ? 7 : 10,
5807 			    /*bit_valid*/ 0, /*bit*/ 0);
5808 			ctl_done((union ctl_io *)ctsio);
5809 			return (CTL_RETVAL_COMPLETE);
5810 		}
5811 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5812 			ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
5813 			ctsio->io_cont = ctl_write_same_cont;
5814 			num_blocks = 1 << 31;
5815 		} else
5816 			num_blocks = (lun->be_lun->maxlba + 1) - lba;
5817 	}
5818 
5819 	len = lun->be_lun->blocksize;
5820 
5821 	/*
5822 	 * If we've got a kernel request that hasn't been malloced yet,
5823 	 * malloc it and tell the caller the data buffer is here.
5824 	 */
5825 	if ((byte2 & SWS_NDOB) == 0 &&
5826 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5827 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5828 		ctsio->kern_data_len = len;
5829 		ctsio->kern_total_len = len;
5830 		ctsio->kern_rel_offset = 0;
5831 		ctsio->kern_sg_entries = 0;
5832 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5833 		ctsio->be_move_done = ctl_config_move_done;
5834 		ctl_datamove((union ctl_io *)ctsio);
5835 
5836 		return (CTL_RETVAL_COMPLETE);
5837 	}
5838 
5839 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5840 	lbalen->lba = lba;
5841 	lbalen->len = num_blocks;
5842 	lbalen->flags = byte2;
5843 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5844 
5845 	return (retval);
5846 }
5847 
5848 int
5849 ctl_unmap(struct ctl_scsiio *ctsio)
5850 {
5851 	struct ctl_lun *lun = CTL_LUN(ctsio);
5852 	struct scsi_unmap *cdb;
5853 	struct ctl_ptr_len_flags *ptrlen;
5854 	struct scsi_unmap_header *hdr;
5855 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5856 	uint64_t lba;
5857 	uint32_t num_blocks;
5858 	int len, retval;
5859 	uint8_t byte2;
5860 
5861 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5862 
5863 	cdb = (struct scsi_unmap *)ctsio->cdb;
5864 	len = scsi_2btoul(cdb->length);
5865 	byte2 = cdb->byte2;
5866 
5867 	/*
5868 	 * If we've got a kernel request that hasn't been malloced yet,
5869 	 * malloc it and tell the caller the data buffer is here.
5870 	 */
5871 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5872 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5873 		ctsio->kern_data_len = len;
5874 		ctsio->kern_total_len = len;
5875 		ctsio->kern_rel_offset = 0;
5876 		ctsio->kern_sg_entries = 0;
5877 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5878 		ctsio->be_move_done = ctl_config_move_done;
5879 		ctl_datamove((union ctl_io *)ctsio);
5880 
5881 		return (CTL_RETVAL_COMPLETE);
5882 	}
5883 
5884 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5885 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5886 	if (len < sizeof (*hdr) ||
5887 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5888 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5889 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5890 		ctl_set_invalid_field(ctsio,
5891 				      /*sks_valid*/ 0,
5892 				      /*command*/ 0,
5893 				      /*field*/ 0,
5894 				      /*bit_valid*/ 0,
5895 				      /*bit*/ 0);
5896 		goto done;
5897 	}
5898 	len = scsi_2btoul(hdr->desc_length);
5899 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5900 	end = buf + len / sizeof(*buf);
5901 
5902 	endnz = buf;
5903 	for (range = buf; range < end; range++) {
5904 		lba = scsi_8btou64(range->lba);
5905 		num_blocks = scsi_4btoul(range->length);
5906 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5907 		 || ((lba + num_blocks) < lba)) {
5908 			ctl_set_lba_out_of_range(ctsio,
5909 			    MAX(lba, lun->be_lun->maxlba + 1));
5910 			ctl_done((union ctl_io *)ctsio);
5911 			return (CTL_RETVAL_COMPLETE);
5912 		}
5913 		if (num_blocks != 0)
5914 			endnz = range + 1;
5915 	}
5916 
5917 	/*
5918 	 * Block backend can not handle zero last range.
5919 	 * Filter it out and return if there is nothing left.
5920 	 */
5921 	len = (uint8_t *)endnz - (uint8_t *)buf;
5922 	if (len == 0) {
5923 		ctl_set_success(ctsio);
5924 		goto done;
5925 	}
5926 
5927 	mtx_lock(&lun->lun_lock);
5928 	ptrlen = (struct ctl_ptr_len_flags *)
5929 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5930 	ptrlen->ptr = (void *)buf;
5931 	ptrlen->len = len;
5932 	ptrlen->flags = byte2;
5933 	ctl_try_unblock_others(lun, (union ctl_io *)ctsio, FALSE);
5934 	mtx_unlock(&lun->lun_lock);
5935 
5936 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5937 	return (retval);
5938 
5939 done:
5940 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5941 		free(ctsio->kern_data_ptr, M_CTL);
5942 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5943 	}
5944 	ctl_done((union ctl_io *)ctsio);
5945 	return (CTL_RETVAL_COMPLETE);
5946 }
5947 
5948 int
5949 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5950 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5951 {
5952 	struct ctl_lun *lun = CTL_LUN(ctsio);
5953 	uint8_t *current_cp;
5954 	int set_ua;
5955 	uint32_t initidx;
5956 
5957 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5958 	set_ua = 0;
5959 
5960 	current_cp = (page_index->page_data + (page_index->page_len *
5961 	    CTL_PAGE_CURRENT));
5962 
5963 	mtx_lock(&lun->lun_lock);
5964 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5965 		memcpy(current_cp, page_ptr, page_index->page_len);
5966 		set_ua = 1;
5967 	}
5968 	if (set_ua != 0)
5969 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5970 	mtx_unlock(&lun->lun_lock);
5971 	if (set_ua) {
5972 		ctl_isc_announce_mode(lun,
5973 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5974 		    page_index->page_code, page_index->subpage);
5975 	}
5976 	return (CTL_RETVAL_COMPLETE);
5977 }
5978 
5979 static void
5980 ctl_ie_timer(void *arg)
5981 {
5982 	struct ctl_lun *lun = arg;
5983 	uint64_t t;
5984 
5985 	if (lun->ie_asc == 0)
5986 		return;
5987 
5988 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5989 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5990 	else
5991 		lun->ie_reported = 0;
5992 
5993 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5994 		lun->ie_reportcnt++;
5995 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5996 		if (t == 0 || t == UINT32_MAX)
5997 			t = 3000;  /* 5 min */
5998 		callout_schedule_sbt(&lun->ie_callout, SBT_1S / 10 * t,
5999 		    SBT_1S / 10, 0);
6000 	}
6001 }
6002 
6003 int
6004 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
6005 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6006 {
6007 	struct ctl_lun *lun = CTL_LUN(ctsio);
6008 	struct scsi_info_exceptions_page *pg;
6009 	uint64_t t;
6010 
6011 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
6012 
6013 	pg = (struct scsi_info_exceptions_page *)page_ptr;
6014 	mtx_lock(&lun->lun_lock);
6015 	if (pg->info_flags & SIEP_FLAGS_TEST) {
6016 		lun->ie_asc = 0x5d;
6017 		lun->ie_ascq = 0xff;
6018 		if (pg->mrie == SIEP_MRIE_UA) {
6019 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
6020 			lun->ie_reported = 1;
6021 		} else {
6022 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
6023 			lun->ie_reported = -1;
6024 		}
6025 		lun->ie_reportcnt = 1;
6026 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
6027 			lun->ie_reportcnt++;
6028 			t = scsi_4btoul(pg->interval_timer);
6029 			if (t == 0 || t == UINT32_MAX)
6030 				t = 3000;  /* 5 min */
6031 			callout_reset_sbt(&lun->ie_callout, SBT_1S / 10 * t,
6032 			    SBT_1S / 10, ctl_ie_timer, lun, 0);
6033 		}
6034 	} else {
6035 		lun->ie_asc = 0;
6036 		lun->ie_ascq = 0;
6037 		lun->ie_reported = 1;
6038 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
6039 		lun->ie_reportcnt = UINT32_MAX;
6040 		callout_stop(&lun->ie_callout);
6041 	}
6042 	mtx_unlock(&lun->lun_lock);
6043 	return (CTL_RETVAL_COMPLETE);
6044 }
6045 
6046 static int
6047 ctl_do_mode_select(union ctl_io *io)
6048 {
6049 	struct ctl_lun *lun = CTL_LUN(io);
6050 	struct scsi_mode_page_header *page_header;
6051 	struct ctl_page_index *page_index;
6052 	struct ctl_scsiio *ctsio;
6053 	int page_len, page_len_offset, page_len_size;
6054 	union ctl_modepage_info *modepage_info;
6055 	uint16_t *len_left, *len_used;
6056 	int retval, i;
6057 
6058 	ctsio = &io->scsiio;
6059 	page_index = NULL;
6060 	page_len = 0;
6061 
6062 	modepage_info = (union ctl_modepage_info *)
6063 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6064 	len_left = &modepage_info->header.len_left;
6065 	len_used = &modepage_info->header.len_used;
6066 
6067 do_next_page:
6068 
6069 	page_header = (struct scsi_mode_page_header *)
6070 		(ctsio->kern_data_ptr + *len_used);
6071 
6072 	if (*len_left == 0) {
6073 		free(ctsio->kern_data_ptr, M_CTL);
6074 		ctl_set_success(ctsio);
6075 		ctl_done((union ctl_io *)ctsio);
6076 		return (CTL_RETVAL_COMPLETE);
6077 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6078 		free(ctsio->kern_data_ptr, M_CTL);
6079 		ctl_set_param_len_error(ctsio);
6080 		ctl_done((union ctl_io *)ctsio);
6081 		return (CTL_RETVAL_COMPLETE);
6082 
6083 	} else if ((page_header->page_code & SMPH_SPF)
6084 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6085 		free(ctsio->kern_data_ptr, M_CTL);
6086 		ctl_set_param_len_error(ctsio);
6087 		ctl_done((union ctl_io *)ctsio);
6088 		return (CTL_RETVAL_COMPLETE);
6089 	}
6090 
6091 	/*
6092 	 * XXX KDM should we do something with the block descriptor?
6093 	 */
6094 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6095 		page_index = &lun->mode_pages.index[i];
6096 		if (lun->be_lun->lun_type == T_DIRECT &&
6097 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6098 			continue;
6099 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6100 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6101 			continue;
6102 		if (lun->be_lun->lun_type == T_CDROM &&
6103 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6104 			continue;
6105 
6106 		if ((page_index->page_code & SMPH_PC_MASK) !=
6107 		    (page_header->page_code & SMPH_PC_MASK))
6108 			continue;
6109 
6110 		/*
6111 		 * If neither page has a subpage code, then we've got a
6112 		 * match.
6113 		 */
6114 		if (((page_index->page_code & SMPH_SPF) == 0)
6115 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6116 			page_len = page_header->page_length;
6117 			break;
6118 		}
6119 
6120 		/*
6121 		 * If both pages have subpages, then the subpage numbers
6122 		 * have to match.
6123 		 */
6124 		if ((page_index->page_code & SMPH_SPF)
6125 		  && (page_header->page_code & SMPH_SPF)) {
6126 			struct scsi_mode_page_header_sp *sph;
6127 
6128 			sph = (struct scsi_mode_page_header_sp *)page_header;
6129 			if (page_index->subpage == sph->subpage) {
6130 				page_len = scsi_2btoul(sph->page_length);
6131 				break;
6132 			}
6133 		}
6134 	}
6135 
6136 	/*
6137 	 * If we couldn't find the page, or if we don't have a mode select
6138 	 * handler for it, send back an error to the user.
6139 	 */
6140 	if ((i >= CTL_NUM_MODE_PAGES)
6141 	 || (page_index->select_handler == NULL)) {
6142 		ctl_set_invalid_field(ctsio,
6143 				      /*sks_valid*/ 1,
6144 				      /*command*/ 0,
6145 				      /*field*/ *len_used,
6146 				      /*bit_valid*/ 0,
6147 				      /*bit*/ 0);
6148 		free(ctsio->kern_data_ptr, M_CTL);
6149 		ctl_done((union ctl_io *)ctsio);
6150 		return (CTL_RETVAL_COMPLETE);
6151 	}
6152 
6153 	if (page_index->page_code & SMPH_SPF) {
6154 		page_len_offset = 2;
6155 		page_len_size = 2;
6156 	} else {
6157 		page_len_size = 1;
6158 		page_len_offset = 1;
6159 	}
6160 
6161 	/*
6162 	 * If the length the initiator gives us isn't the one we specify in
6163 	 * the mode page header, or if they didn't specify enough data in
6164 	 * the CDB to avoid truncating this page, kick out the request.
6165 	 */
6166 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6167 		ctl_set_invalid_field(ctsio,
6168 				      /*sks_valid*/ 1,
6169 				      /*command*/ 0,
6170 				      /*field*/ *len_used + page_len_offset,
6171 				      /*bit_valid*/ 0,
6172 				      /*bit*/ 0);
6173 		free(ctsio->kern_data_ptr, M_CTL);
6174 		ctl_done((union ctl_io *)ctsio);
6175 		return (CTL_RETVAL_COMPLETE);
6176 	}
6177 	if (*len_left < page_index->page_len) {
6178 		free(ctsio->kern_data_ptr, M_CTL);
6179 		ctl_set_param_len_error(ctsio);
6180 		ctl_done((union ctl_io *)ctsio);
6181 		return (CTL_RETVAL_COMPLETE);
6182 	}
6183 
6184 	/*
6185 	 * Run through the mode page, checking to make sure that the bits
6186 	 * the user changed are actually legal for him to change.
6187 	 */
6188 	for (i = 0; i < page_index->page_len; i++) {
6189 		uint8_t *user_byte, *change_mask, *current_byte;
6190 		int bad_bit;
6191 		int j;
6192 
6193 		user_byte = (uint8_t *)page_header + i;
6194 		change_mask = page_index->page_data +
6195 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6196 		current_byte = page_index->page_data +
6197 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6198 
6199 		/*
6200 		 * Check to see whether the user set any bits in this byte
6201 		 * that he is not allowed to set.
6202 		 */
6203 		if ((*user_byte & ~(*change_mask)) ==
6204 		    (*current_byte & ~(*change_mask)))
6205 			continue;
6206 
6207 		/*
6208 		 * Go through bit by bit to determine which one is illegal.
6209 		 */
6210 		bad_bit = 0;
6211 		for (j = 7; j >= 0; j--) {
6212 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6213 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6214 				bad_bit = i;
6215 				break;
6216 			}
6217 		}
6218 		ctl_set_invalid_field(ctsio,
6219 				      /*sks_valid*/ 1,
6220 				      /*command*/ 0,
6221 				      /*field*/ *len_used + i,
6222 				      /*bit_valid*/ 1,
6223 				      /*bit*/ bad_bit);
6224 		free(ctsio->kern_data_ptr, M_CTL);
6225 		ctl_done((union ctl_io *)ctsio);
6226 		return (CTL_RETVAL_COMPLETE);
6227 	}
6228 
6229 	/*
6230 	 * Decrement these before we call the page handler, since we may
6231 	 * end up getting called back one way or another before the handler
6232 	 * returns to this context.
6233 	 */
6234 	*len_left -= page_index->page_len;
6235 	*len_used += page_index->page_len;
6236 
6237 	retval = page_index->select_handler(ctsio, page_index,
6238 					    (uint8_t *)page_header);
6239 
6240 	/*
6241 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6242 	 * wait until this queued command completes to finish processing
6243 	 * the mode page.  If it returns anything other than
6244 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6245 	 * already set the sense information, freed the data pointer, and
6246 	 * completed the io for us.
6247 	 */
6248 	if (retval != CTL_RETVAL_COMPLETE)
6249 		goto bailout_no_done;
6250 
6251 	/*
6252 	 * If the initiator sent us more than one page, parse the next one.
6253 	 */
6254 	if (*len_left > 0)
6255 		goto do_next_page;
6256 
6257 	ctl_set_success(ctsio);
6258 	free(ctsio->kern_data_ptr, M_CTL);
6259 	ctl_done((union ctl_io *)ctsio);
6260 
6261 bailout_no_done:
6262 
6263 	return (CTL_RETVAL_COMPLETE);
6264 
6265 }
6266 
6267 int
6268 ctl_mode_select(struct ctl_scsiio *ctsio)
6269 {
6270 	struct ctl_lun *lun = CTL_LUN(ctsio);
6271 	union ctl_modepage_info *modepage_info;
6272 	int bd_len, i, header_size, param_len, rtd;
6273 	uint32_t initidx;
6274 
6275 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6276 	switch (ctsio->cdb[0]) {
6277 	case MODE_SELECT_6: {
6278 		struct scsi_mode_select_6 *cdb;
6279 
6280 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6281 
6282 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6283 		param_len = cdb->length;
6284 		header_size = sizeof(struct scsi_mode_header_6);
6285 		break;
6286 	}
6287 	case MODE_SELECT_10: {
6288 		struct scsi_mode_select_10 *cdb;
6289 
6290 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6291 
6292 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6293 		param_len = scsi_2btoul(cdb->length);
6294 		header_size = sizeof(struct scsi_mode_header_10);
6295 		break;
6296 	}
6297 	default:
6298 		ctl_set_invalid_opcode(ctsio);
6299 		ctl_done((union ctl_io *)ctsio);
6300 		return (CTL_RETVAL_COMPLETE);
6301 	}
6302 
6303 	if (rtd) {
6304 		if (param_len != 0) {
6305 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6306 			    /*command*/ 1, /*field*/ 0,
6307 			    /*bit_valid*/ 0, /*bit*/ 0);
6308 			ctl_done((union ctl_io *)ctsio);
6309 			return (CTL_RETVAL_COMPLETE);
6310 		}
6311 
6312 		/* Revert to defaults. */
6313 		ctl_init_page_index(lun);
6314 		mtx_lock(&lun->lun_lock);
6315 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6316 		mtx_unlock(&lun->lun_lock);
6317 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6318 			ctl_isc_announce_mode(lun, -1,
6319 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6320 			    lun->mode_pages.index[i].subpage);
6321 		}
6322 		ctl_set_success(ctsio);
6323 		ctl_done((union ctl_io *)ctsio);
6324 		return (CTL_RETVAL_COMPLETE);
6325 	}
6326 
6327 	/*
6328 	 * From SPC-3:
6329 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6330 	 * shall be empty. This condition shall not be considered as an error."
6331 	 */
6332 	if (param_len == 0) {
6333 		ctl_set_success(ctsio);
6334 		ctl_done((union ctl_io *)ctsio);
6335 		return (CTL_RETVAL_COMPLETE);
6336 	}
6337 
6338 	/*
6339 	 * Since we'll hit this the first time through, prior to
6340 	 * allocation, we don't need to free a data buffer here.
6341 	 */
6342 	if (param_len < header_size) {
6343 		ctl_set_param_len_error(ctsio);
6344 		ctl_done((union ctl_io *)ctsio);
6345 		return (CTL_RETVAL_COMPLETE);
6346 	}
6347 
6348 	/*
6349 	 * Allocate the data buffer and grab the user's data.  In theory,
6350 	 * we shouldn't have to sanity check the parameter list length here
6351 	 * because the maximum size is 64K.  We should be able to malloc
6352 	 * that much without too many problems.
6353 	 */
6354 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6355 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6356 		ctsio->kern_data_len = param_len;
6357 		ctsio->kern_total_len = param_len;
6358 		ctsio->kern_rel_offset = 0;
6359 		ctsio->kern_sg_entries = 0;
6360 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6361 		ctsio->be_move_done = ctl_config_move_done;
6362 		ctl_datamove((union ctl_io *)ctsio);
6363 
6364 		return (CTL_RETVAL_COMPLETE);
6365 	}
6366 
6367 	switch (ctsio->cdb[0]) {
6368 	case MODE_SELECT_6: {
6369 		struct scsi_mode_header_6 *mh6;
6370 
6371 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6372 		bd_len = mh6->blk_desc_len;
6373 		break;
6374 	}
6375 	case MODE_SELECT_10: {
6376 		struct scsi_mode_header_10 *mh10;
6377 
6378 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6379 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6380 		break;
6381 	}
6382 	default:
6383 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6384 	}
6385 
6386 	if (param_len < (header_size + bd_len)) {
6387 		free(ctsio->kern_data_ptr, M_CTL);
6388 		ctl_set_param_len_error(ctsio);
6389 		ctl_done((union ctl_io *)ctsio);
6390 		return (CTL_RETVAL_COMPLETE);
6391 	}
6392 
6393 	/*
6394 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6395 	 * ctl_config_write_done(), it'll get passed back to
6396 	 * ctl_do_mode_select() for further processing, or completion if
6397 	 * we're all done.
6398 	 */
6399 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6400 	ctsio->io_cont = ctl_do_mode_select;
6401 
6402 	modepage_info = (union ctl_modepage_info *)
6403 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6404 	memset(modepage_info, 0, sizeof(*modepage_info));
6405 	modepage_info->header.len_left = param_len - header_size - bd_len;
6406 	modepage_info->header.len_used = header_size + bd_len;
6407 
6408 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6409 }
6410 
6411 int
6412 ctl_mode_sense(struct ctl_scsiio *ctsio)
6413 {
6414 	struct ctl_lun *lun = CTL_LUN(ctsio);
6415 	int pc, page_code, llba, subpage;
6416 	int alloc_len, page_len, header_len, bd_len, total_len;
6417 	void *block_desc;
6418 	struct ctl_page_index *page_index;
6419 
6420 	llba = 0;
6421 
6422 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6423 
6424 	switch (ctsio->cdb[0]) {
6425 	case MODE_SENSE_6: {
6426 		struct scsi_mode_sense_6 *cdb;
6427 
6428 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6429 
6430 		header_len = sizeof(struct scsi_mode_hdr_6);
6431 		if (cdb->byte2 & SMS_DBD)
6432 			bd_len = 0;
6433 		else
6434 			bd_len = sizeof(struct scsi_mode_block_descr);
6435 		header_len += bd_len;
6436 
6437 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6438 		page_code = cdb->page & SMS_PAGE_CODE;
6439 		subpage = cdb->subpage;
6440 		alloc_len = cdb->length;
6441 		break;
6442 	}
6443 	case MODE_SENSE_10: {
6444 		struct scsi_mode_sense_10 *cdb;
6445 
6446 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6447 
6448 		header_len = sizeof(struct scsi_mode_hdr_10);
6449 		if (cdb->byte2 & SMS_DBD) {
6450 			bd_len = 0;
6451 		} else if (lun->be_lun->lun_type == T_DIRECT) {
6452 			if (cdb->byte2 & SMS10_LLBAA) {
6453 				llba = 1;
6454 				bd_len = sizeof(struct scsi_mode_block_descr_dlong);
6455 			} else
6456 				bd_len = sizeof(struct scsi_mode_block_descr_dshort);
6457 		} else
6458 			bd_len = sizeof(struct scsi_mode_block_descr);
6459 		header_len += bd_len;
6460 
6461 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6462 		page_code = cdb->page & SMS_PAGE_CODE;
6463 		subpage = cdb->subpage;
6464 		alloc_len = scsi_2btoul(cdb->length);
6465 		break;
6466 	}
6467 	default:
6468 		ctl_set_invalid_opcode(ctsio);
6469 		ctl_done((union ctl_io *)ctsio);
6470 		return (CTL_RETVAL_COMPLETE);
6471 		break; /* NOTREACHED */
6472 	}
6473 
6474 	/*
6475 	 * We have to make a first pass through to calculate the size of
6476 	 * the pages that match the user's query.  Then we allocate enough
6477 	 * memory to hold it, and actually copy the data into the buffer.
6478 	 */
6479 	switch (page_code) {
6480 	case SMS_ALL_PAGES_PAGE: {
6481 		u_int i;
6482 
6483 		page_len = 0;
6484 
6485 		/*
6486 		 * At the moment, values other than 0 and 0xff here are
6487 		 * reserved according to SPC-3.
6488 		 */
6489 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6490 		 && (subpage != SMS_SUBPAGE_ALL)) {
6491 			ctl_set_invalid_field(ctsio,
6492 					      /*sks_valid*/ 1,
6493 					      /*command*/ 1,
6494 					      /*field*/ 3,
6495 					      /*bit_valid*/ 0,
6496 					      /*bit*/ 0);
6497 			ctl_done((union ctl_io *)ctsio);
6498 			return (CTL_RETVAL_COMPLETE);
6499 		}
6500 
6501 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6502 			page_index = &lun->mode_pages.index[i];
6503 
6504 			/* Make sure the page is supported for this dev type */
6505 			if (lun->be_lun->lun_type == T_DIRECT &&
6506 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6507 				continue;
6508 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6509 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6510 				continue;
6511 			if (lun->be_lun->lun_type == T_CDROM &&
6512 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6513 				continue;
6514 
6515 			/*
6516 			 * We don't use this subpage if the user didn't
6517 			 * request all subpages.
6518 			 */
6519 			if ((page_index->subpage != 0)
6520 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6521 				continue;
6522 
6523 			page_len += page_index->page_len;
6524 		}
6525 		break;
6526 	}
6527 	default: {
6528 		u_int i;
6529 
6530 		page_len = 0;
6531 
6532 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6533 			page_index = &lun->mode_pages.index[i];
6534 
6535 			/* Make sure the page is supported for this dev type */
6536 			if (lun->be_lun->lun_type == T_DIRECT &&
6537 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6538 				continue;
6539 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6540 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6541 				continue;
6542 			if (lun->be_lun->lun_type == T_CDROM &&
6543 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6544 				continue;
6545 
6546 			/* Look for the right page code */
6547 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6548 				continue;
6549 
6550 			/* Look for the right subpage or the subpage wildcard*/
6551 			if ((page_index->subpage != subpage)
6552 			 && (subpage != SMS_SUBPAGE_ALL))
6553 				continue;
6554 
6555 			page_len += page_index->page_len;
6556 		}
6557 
6558 		if (page_len == 0) {
6559 			ctl_set_invalid_field(ctsio,
6560 					      /*sks_valid*/ 1,
6561 					      /*command*/ 1,
6562 					      /*field*/ 2,
6563 					      /*bit_valid*/ 1,
6564 					      /*bit*/ 5);
6565 			ctl_done((union ctl_io *)ctsio);
6566 			return (CTL_RETVAL_COMPLETE);
6567 		}
6568 		break;
6569 	}
6570 	}
6571 
6572 	total_len = header_len + page_len;
6573 
6574 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6575 	ctsio->kern_sg_entries = 0;
6576 	ctsio->kern_rel_offset = 0;
6577 	ctsio->kern_data_len = min(total_len, alloc_len);
6578 	ctsio->kern_total_len = ctsio->kern_data_len;
6579 
6580 	switch (ctsio->cdb[0]) {
6581 	case MODE_SENSE_6: {
6582 		struct scsi_mode_hdr_6 *header;
6583 
6584 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6585 
6586 		header->datalen = MIN(total_len - 1, 254);
6587 		if (lun->be_lun->lun_type == T_DIRECT) {
6588 			header->dev_specific = 0x10; /* DPOFUA */
6589 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6590 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6591 				header->dev_specific |= 0x80; /* WP */
6592 		}
6593 		header->block_descr_len = bd_len;
6594 		block_desc = &header[1];
6595 		break;
6596 	}
6597 	case MODE_SENSE_10: {
6598 		struct scsi_mode_hdr_10 *header;
6599 		int datalen;
6600 
6601 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6602 
6603 		datalen = MIN(total_len - 2, 65533);
6604 		scsi_ulto2b(datalen, header->datalen);
6605 		if (lun->be_lun->lun_type == T_DIRECT) {
6606 			header->dev_specific = 0x10; /* DPOFUA */
6607 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6608 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6609 				header->dev_specific |= 0x80; /* WP */
6610 		}
6611 		if (llba)
6612 			header->flags |= SMH_LONGLBA;
6613 		scsi_ulto2b(bd_len, header->block_descr_len);
6614 		block_desc = &header[1];
6615 		break;
6616 	}
6617 	default:
6618 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6619 	}
6620 
6621 	/*
6622 	 * If we've got a disk, use its blocksize in the block
6623 	 * descriptor.  Otherwise, just set it to 0.
6624 	 */
6625 	if (bd_len > 0) {
6626 		if (lun->be_lun->lun_type == T_DIRECT) {
6627 			if (llba) {
6628 				struct scsi_mode_block_descr_dlong *bd = block_desc;
6629 				if (lun->be_lun->maxlba != 0)
6630 					scsi_u64to8b(lun->be_lun->maxlba + 1,
6631 					    bd->num_blocks);
6632 				scsi_ulto4b(lun->be_lun->blocksize,
6633 				    bd->block_len);
6634 			} else {
6635 				struct scsi_mode_block_descr_dshort *bd = block_desc;
6636 				if (lun->be_lun->maxlba != 0)
6637 					scsi_ulto4b(MIN(lun->be_lun->maxlba+1,
6638 					    UINT32_MAX), bd->num_blocks);
6639 				scsi_ulto3b(lun->be_lun->blocksize,
6640 				    bd->block_len);
6641 			}
6642 		} else {
6643 			struct scsi_mode_block_descr *bd = block_desc;
6644 			scsi_ulto3b(0, bd->block_len);
6645 		}
6646 	}
6647 
6648 	switch (page_code) {
6649 	case SMS_ALL_PAGES_PAGE: {
6650 		int i, data_used;
6651 
6652 		data_used = header_len;
6653 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6654 			struct ctl_page_index *page_index;
6655 
6656 			page_index = &lun->mode_pages.index[i];
6657 			if (lun->be_lun->lun_type == T_DIRECT &&
6658 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6659 				continue;
6660 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6661 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6662 				continue;
6663 			if (lun->be_lun->lun_type == T_CDROM &&
6664 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6665 				continue;
6666 
6667 			/*
6668 			 * We don't use this subpage if the user didn't
6669 			 * request all subpages.  We already checked (above)
6670 			 * to make sure the user only specified a subpage
6671 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6672 			 */
6673 			if ((page_index->subpage != 0)
6674 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6675 				continue;
6676 
6677 			/*
6678 			 * Call the handler, if it exists, to update the
6679 			 * page to the latest values.
6680 			 */
6681 			if (page_index->sense_handler != NULL)
6682 				page_index->sense_handler(ctsio, page_index,pc);
6683 
6684 			memcpy(ctsio->kern_data_ptr + data_used,
6685 			       page_index->page_data +
6686 			       (page_index->page_len * pc),
6687 			       page_index->page_len);
6688 			data_used += page_index->page_len;
6689 		}
6690 		break;
6691 	}
6692 	default: {
6693 		int i, data_used;
6694 
6695 		data_used = header_len;
6696 
6697 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6698 			struct ctl_page_index *page_index;
6699 
6700 			page_index = &lun->mode_pages.index[i];
6701 
6702 			/* Look for the right page code */
6703 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6704 				continue;
6705 
6706 			/* Look for the right subpage or the subpage wildcard*/
6707 			if ((page_index->subpage != subpage)
6708 			 && (subpage != SMS_SUBPAGE_ALL))
6709 				continue;
6710 
6711 			/* Make sure the page is supported for this dev type */
6712 			if (lun->be_lun->lun_type == T_DIRECT &&
6713 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6714 				continue;
6715 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6716 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6717 				continue;
6718 			if (lun->be_lun->lun_type == T_CDROM &&
6719 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6720 				continue;
6721 
6722 			/*
6723 			 * Call the handler, if it exists, to update the
6724 			 * page to the latest values.
6725 			 */
6726 			if (page_index->sense_handler != NULL)
6727 				page_index->sense_handler(ctsio, page_index,pc);
6728 
6729 			memcpy(ctsio->kern_data_ptr + data_used,
6730 			       page_index->page_data +
6731 			       (page_index->page_len * pc),
6732 			       page_index->page_len);
6733 			data_used += page_index->page_len;
6734 		}
6735 		break;
6736 	}
6737 	}
6738 
6739 	ctl_set_success(ctsio);
6740 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6741 	ctsio->be_move_done = ctl_config_move_done;
6742 	ctl_datamove((union ctl_io *)ctsio);
6743 	return (CTL_RETVAL_COMPLETE);
6744 }
6745 
6746 int
6747 ctl_temp_log_sense_handler(struct ctl_scsiio *ctsio,
6748 			       struct ctl_page_index *page_index,
6749 			       int pc)
6750 {
6751 	struct ctl_lun *lun = CTL_LUN(ctsio);
6752 	struct scsi_log_temperature *data;
6753 	const char *value;
6754 
6755 	data = (struct scsi_log_temperature *)page_index->page_data;
6756 
6757 	scsi_ulto2b(SLP_TEMPERATURE, data->hdr.param_code);
6758 	data->hdr.param_control = SLP_LBIN;
6759 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6760 	    sizeof(struct scsi_log_param_header);
6761 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6762 	    NULL)) != NULL)
6763 		data->temperature = strtol(value, NULL, 0);
6764 	else
6765 		data->temperature = 0xff;
6766 	data++;
6767 
6768 	scsi_ulto2b(SLP_REFTEMPERATURE, data->hdr.param_code);
6769 	data->hdr.param_control = SLP_LBIN;
6770 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6771 	    sizeof(struct scsi_log_param_header);
6772 	if ((value = dnvlist_get_string(lun->be_lun->options, "reftemperature",
6773 	    NULL)) != NULL)
6774 		data->temperature = strtol(value, NULL, 0);
6775 	else
6776 		data->temperature = 0xff;
6777 	return (0);
6778 }
6779 
6780 int
6781 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6782 			       struct ctl_page_index *page_index,
6783 			       int pc)
6784 {
6785 	struct ctl_lun *lun = CTL_LUN(ctsio);
6786 	struct scsi_log_param_header *phdr;
6787 	uint8_t *data;
6788 	uint64_t val;
6789 
6790 	data = page_index->page_data;
6791 
6792 	if (lun->backend->lun_attr != NULL &&
6793 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksavail"))
6794 	     != UINT64_MAX) {
6795 		phdr = (struct scsi_log_param_header *)data;
6796 		scsi_ulto2b(0x0001, phdr->param_code);
6797 		phdr->param_control = SLP_LBIN | SLP_LP;
6798 		phdr->param_len = 8;
6799 		data = (uint8_t *)(phdr + 1);
6800 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6801 		data[4] = 0x02; /* per-pool */
6802 		data += phdr->param_len;
6803 	}
6804 
6805 	if (lun->backend->lun_attr != NULL &&
6806 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksused"))
6807 	     != UINT64_MAX) {
6808 		phdr = (struct scsi_log_param_header *)data;
6809 		scsi_ulto2b(0x0002, phdr->param_code);
6810 		phdr->param_control = SLP_LBIN | SLP_LP;
6811 		phdr->param_len = 8;
6812 		data = (uint8_t *)(phdr + 1);
6813 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6814 		data[4] = 0x01; /* per-LUN */
6815 		data += phdr->param_len;
6816 	}
6817 
6818 	if (lun->backend->lun_attr != NULL &&
6819 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksavail"))
6820 	     != UINT64_MAX) {
6821 		phdr = (struct scsi_log_param_header *)data;
6822 		scsi_ulto2b(0x00f1, phdr->param_code);
6823 		phdr->param_control = SLP_LBIN | SLP_LP;
6824 		phdr->param_len = 8;
6825 		data = (uint8_t *)(phdr + 1);
6826 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6827 		data[4] = 0x02; /* per-pool */
6828 		data += phdr->param_len;
6829 	}
6830 
6831 	if (lun->backend->lun_attr != NULL &&
6832 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksused"))
6833 	     != UINT64_MAX) {
6834 		phdr = (struct scsi_log_param_header *)data;
6835 		scsi_ulto2b(0x00f2, phdr->param_code);
6836 		phdr->param_control = SLP_LBIN | SLP_LP;
6837 		phdr->param_len = 8;
6838 		data = (uint8_t *)(phdr + 1);
6839 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6840 		data[4] = 0x02; /* per-pool */
6841 		data += phdr->param_len;
6842 	}
6843 
6844 	page_index->page_len = data - page_index->page_data;
6845 	return (0);
6846 }
6847 
6848 int
6849 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6850 			       struct ctl_page_index *page_index,
6851 			       int pc)
6852 {
6853 	struct ctl_lun *lun = CTL_LUN(ctsio);
6854 	struct stat_page *data;
6855 	struct bintime *t;
6856 
6857 	data = (struct stat_page *)page_index->page_data;
6858 
6859 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6860 	data->sap.hdr.param_control = SLP_LBIN;
6861 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6862 	    sizeof(struct scsi_log_param_header);
6863 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6864 	    data->sap.read_num);
6865 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6866 	    data->sap.write_num);
6867 	if (lun->be_lun->blocksize > 0) {
6868 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6869 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6870 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6871 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6872 	}
6873 	t = &lun->stats.time[CTL_STATS_READ];
6874 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6875 	    data->sap.read_int);
6876 	t = &lun->stats.time[CTL_STATS_WRITE];
6877 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6878 	    data->sap.write_int);
6879 	scsi_u64to8b(0, data->sap.weighted_num);
6880 	scsi_u64to8b(0, data->sap.weighted_int);
6881 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6882 	data->it.hdr.param_control = SLP_LBIN;
6883 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6884 	    sizeof(struct scsi_log_param_header);
6885 #ifdef CTL_TIME_IO
6886 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6887 #endif
6888 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6889 	data->it.hdr.param_control = SLP_LBIN;
6890 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6891 	    sizeof(struct scsi_log_param_header);
6892 	scsi_ulto4b(3, data->ti.exponent);
6893 	scsi_ulto4b(1, data->ti.integer);
6894 	return (0);
6895 }
6896 
6897 int
6898 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6899 			       struct ctl_page_index *page_index,
6900 			       int pc)
6901 {
6902 	struct ctl_lun *lun = CTL_LUN(ctsio);
6903 	struct scsi_log_informational_exceptions *data;
6904 	const char *value;
6905 
6906 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6907 
6908 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6909 	data->hdr.param_control = SLP_LBIN;
6910 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6911 	    sizeof(struct scsi_log_param_header);
6912 	data->ie_asc = lun->ie_asc;
6913 	data->ie_ascq = lun->ie_ascq;
6914 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6915 	    NULL)) != NULL)
6916 		data->temperature = strtol(value, NULL, 0);
6917 	else
6918 		data->temperature = 0xff;
6919 	return (0);
6920 }
6921 
6922 int
6923 ctl_log_sense(struct ctl_scsiio *ctsio)
6924 {
6925 	struct ctl_lun *lun = CTL_LUN(ctsio);
6926 	int i, pc, page_code, subpage;
6927 	int alloc_len, total_len;
6928 	struct ctl_page_index *page_index;
6929 	struct scsi_log_sense *cdb;
6930 	struct scsi_log_header *header;
6931 
6932 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6933 
6934 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6935 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6936 	page_code = cdb->page & SLS_PAGE_CODE;
6937 	subpage = cdb->subpage;
6938 	alloc_len = scsi_2btoul(cdb->length);
6939 
6940 	page_index = NULL;
6941 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6942 		page_index = &lun->log_pages.index[i];
6943 
6944 		/* Look for the right page code */
6945 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6946 			continue;
6947 
6948 		/* Look for the right subpage or the subpage wildcard*/
6949 		if (page_index->subpage != subpage)
6950 			continue;
6951 
6952 		break;
6953 	}
6954 	if (i >= CTL_NUM_LOG_PAGES) {
6955 		ctl_set_invalid_field(ctsio,
6956 				      /*sks_valid*/ 1,
6957 				      /*command*/ 1,
6958 				      /*field*/ 2,
6959 				      /*bit_valid*/ 0,
6960 				      /*bit*/ 0);
6961 		ctl_done((union ctl_io *)ctsio);
6962 		return (CTL_RETVAL_COMPLETE);
6963 	}
6964 
6965 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6966 
6967 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6968 	ctsio->kern_sg_entries = 0;
6969 	ctsio->kern_rel_offset = 0;
6970 	ctsio->kern_data_len = min(total_len, alloc_len);
6971 	ctsio->kern_total_len = ctsio->kern_data_len;
6972 
6973 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6974 	header->page = page_index->page_code;
6975 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6976 		header->page |= SL_DS;
6977 	if (page_index->subpage) {
6978 		header->page |= SL_SPF;
6979 		header->subpage = page_index->subpage;
6980 	}
6981 	scsi_ulto2b(page_index->page_len, header->datalen);
6982 
6983 	/*
6984 	 * Call the handler, if it exists, to update the
6985 	 * page to the latest values.
6986 	 */
6987 	if (page_index->sense_handler != NULL)
6988 		page_index->sense_handler(ctsio, page_index, pc);
6989 
6990 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6991 
6992 	ctl_set_success(ctsio);
6993 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6994 	ctsio->be_move_done = ctl_config_move_done;
6995 	ctl_datamove((union ctl_io *)ctsio);
6996 	return (CTL_RETVAL_COMPLETE);
6997 }
6998 
6999 int
7000 ctl_read_capacity(struct ctl_scsiio *ctsio)
7001 {
7002 	struct ctl_lun *lun = CTL_LUN(ctsio);
7003 	struct scsi_read_capacity *cdb;
7004 	struct scsi_read_capacity_data *data;
7005 	uint32_t lba;
7006 
7007 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7008 
7009 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7010 
7011 	lba = scsi_4btoul(cdb->addr);
7012 	if (((cdb->pmi & SRC_PMI) == 0)
7013 	 && (lba != 0)) {
7014 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7015 				      /*sks_valid*/ 1,
7016 				      /*command*/ 1,
7017 				      /*field*/ 2,
7018 				      /*bit_valid*/ 0,
7019 				      /*bit*/ 0);
7020 		ctl_done((union ctl_io *)ctsio);
7021 		return (CTL_RETVAL_COMPLETE);
7022 	}
7023 
7024 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7025 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7026 	ctsio->kern_data_len = sizeof(*data);
7027 	ctsio->kern_total_len = sizeof(*data);
7028 	ctsio->kern_rel_offset = 0;
7029 	ctsio->kern_sg_entries = 0;
7030 
7031 	/*
7032 	 * If the maximum LBA is greater than 0xfffffffe, the user must
7033 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7034 	 * serivce action set.
7035 	 */
7036 	if (lun->be_lun->maxlba > 0xfffffffe)
7037 		scsi_ulto4b(0xffffffff, data->addr);
7038 	else
7039 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7040 
7041 	/*
7042 	 * XXX KDM this may not be 512 bytes...
7043 	 */
7044 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7045 
7046 	ctl_set_success(ctsio);
7047 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7048 	ctsio->be_move_done = ctl_config_move_done;
7049 	ctl_datamove((union ctl_io *)ctsio);
7050 	return (CTL_RETVAL_COMPLETE);
7051 }
7052 
7053 int
7054 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7055 {
7056 	struct ctl_lun *lun = CTL_LUN(ctsio);
7057 	struct scsi_read_capacity_16 *cdb;
7058 	struct scsi_read_capacity_data_long *data;
7059 	uint64_t lba;
7060 	uint32_t alloc_len;
7061 
7062 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7063 
7064 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7065 
7066 	alloc_len = scsi_4btoul(cdb->alloc_len);
7067 	lba = scsi_8btou64(cdb->addr);
7068 
7069 	if ((cdb->reladr & SRC16_PMI)
7070 	 && (lba != 0)) {
7071 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7072 				      /*sks_valid*/ 1,
7073 				      /*command*/ 1,
7074 				      /*field*/ 2,
7075 				      /*bit_valid*/ 0,
7076 				      /*bit*/ 0);
7077 		ctl_done((union ctl_io *)ctsio);
7078 		return (CTL_RETVAL_COMPLETE);
7079 	}
7080 
7081 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7082 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7083 	ctsio->kern_rel_offset = 0;
7084 	ctsio->kern_sg_entries = 0;
7085 	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
7086 	ctsio->kern_total_len = ctsio->kern_data_len;
7087 
7088 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7089 	/* XXX KDM this may not be 512 bytes... */
7090 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7091 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7092 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7093 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7094 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7095 
7096 	ctl_set_success(ctsio);
7097 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7098 	ctsio->be_move_done = ctl_config_move_done;
7099 	ctl_datamove((union ctl_io *)ctsio);
7100 	return (CTL_RETVAL_COMPLETE);
7101 }
7102 
7103 int
7104 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7105 {
7106 	struct ctl_lun *lun = CTL_LUN(ctsio);
7107 	struct scsi_get_lba_status *cdb;
7108 	struct scsi_get_lba_status_data *data;
7109 	struct ctl_lba_len_flags *lbalen;
7110 	uint64_t lba;
7111 	uint32_t alloc_len, total_len;
7112 	int retval;
7113 
7114 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7115 
7116 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7117 	lba = scsi_8btou64(cdb->addr);
7118 	alloc_len = scsi_4btoul(cdb->alloc_len);
7119 
7120 	if (lba > lun->be_lun->maxlba) {
7121 		ctl_set_lba_out_of_range(ctsio, lba);
7122 		ctl_done((union ctl_io *)ctsio);
7123 		return (CTL_RETVAL_COMPLETE);
7124 	}
7125 
7126 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7127 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7128 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7129 	ctsio->kern_rel_offset = 0;
7130 	ctsio->kern_sg_entries = 0;
7131 	ctsio->kern_data_len = min(total_len, alloc_len);
7132 	ctsio->kern_total_len = ctsio->kern_data_len;
7133 
7134 	/* Fill dummy data in case backend can't tell anything. */
7135 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7136 	scsi_u64to8b(lba, data->descr[0].addr);
7137 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7138 	    data->descr[0].length);
7139 	data->descr[0].status = 0; /* Mapped or unknown. */
7140 
7141 	ctl_set_success(ctsio);
7142 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7143 	ctsio->be_move_done = ctl_config_move_done;
7144 
7145 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7146 	lbalen->lba = lba;
7147 	lbalen->len = total_len;
7148 	lbalen->flags = 0;
7149 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7150 	return (retval);
7151 }
7152 
7153 int
7154 ctl_read_defect(struct ctl_scsiio *ctsio)
7155 {
7156 	struct scsi_read_defect_data_10 *ccb10;
7157 	struct scsi_read_defect_data_12 *ccb12;
7158 	struct scsi_read_defect_data_hdr_10 *data10;
7159 	struct scsi_read_defect_data_hdr_12 *data12;
7160 	uint32_t alloc_len, data_len;
7161 	uint8_t format;
7162 
7163 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7164 
7165 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7166 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7167 		format = ccb10->format;
7168 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7169 		data_len = sizeof(*data10);
7170 	} else {
7171 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7172 		format = ccb12->format;
7173 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7174 		data_len = sizeof(*data12);
7175 	}
7176 	if (alloc_len == 0) {
7177 		ctl_set_success(ctsio);
7178 		ctl_done((union ctl_io *)ctsio);
7179 		return (CTL_RETVAL_COMPLETE);
7180 	}
7181 
7182 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7183 	ctsio->kern_rel_offset = 0;
7184 	ctsio->kern_sg_entries = 0;
7185 	ctsio->kern_data_len = min(data_len, alloc_len);
7186 	ctsio->kern_total_len = ctsio->kern_data_len;
7187 
7188 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7189 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7190 		    ctsio->kern_data_ptr;
7191 		data10->format = format;
7192 		scsi_ulto2b(0, data10->length);
7193 	} else {
7194 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7195 		    ctsio->kern_data_ptr;
7196 		data12->format = format;
7197 		scsi_ulto2b(0, data12->generation);
7198 		scsi_ulto4b(0, data12->length);
7199 	}
7200 
7201 	ctl_set_success(ctsio);
7202 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7203 	ctsio->be_move_done = ctl_config_move_done;
7204 	ctl_datamove((union ctl_io *)ctsio);
7205 	return (CTL_RETVAL_COMPLETE);
7206 }
7207 
7208 int
7209 ctl_report_ident_info(struct ctl_scsiio *ctsio)
7210 {
7211 	struct ctl_lun *lun = CTL_LUN(ctsio);
7212 	struct scsi_report_ident_info *cdb;
7213 	struct scsi_report_ident_info_data *rii_ptr;
7214 	struct scsi_report_ident_info_descr *riid_ptr;
7215 	const char *oii, *otii;
7216 	int retval, alloc_len, total_len = 0, len = 0;
7217 
7218 	CTL_DEBUG_PRINT(("ctl_report_ident_info\n"));
7219 
7220 	cdb = (struct scsi_report_ident_info *)ctsio->cdb;
7221 	retval = CTL_RETVAL_COMPLETE;
7222 
7223 	total_len = sizeof(struct scsi_report_ident_info_data);
7224 	switch (cdb->type) {
7225 	case RII_LUII:
7226 		oii = dnvlist_get_string(lun->be_lun->options,
7227 		    "ident_info", NULL);
7228 		if (oii)
7229 			len = strlen(oii);	/* Approximately */
7230 		break;
7231 	case RII_LUTII:
7232 		otii = dnvlist_get_string(lun->be_lun->options,
7233 		    "text_ident_info", NULL);
7234 		if (otii)
7235 			len = strlen(otii) + 1;	/* NULL-terminated */
7236 		break;
7237 	case RII_IIS:
7238 		len = 2 * sizeof(struct scsi_report_ident_info_descr);
7239 		break;
7240 	default:
7241 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7242 				      /*sks_valid*/ 1,
7243 				      /*command*/ 1,
7244 				      /*field*/ 11,
7245 				      /*bit_valid*/ 1,
7246 				      /*bit*/ 2);
7247 		ctl_done((union ctl_io *)ctsio);
7248 		return(retval);
7249 	}
7250 	total_len += len;
7251 	alloc_len = scsi_4btoul(cdb->length);
7252 
7253 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7254 	ctsio->kern_sg_entries = 0;
7255 	ctsio->kern_rel_offset = 0;
7256 	ctsio->kern_data_len = min(total_len, alloc_len);
7257 	ctsio->kern_total_len = ctsio->kern_data_len;
7258 
7259 	rii_ptr = (struct scsi_report_ident_info_data *)ctsio->kern_data_ptr;
7260 	switch (cdb->type) {
7261 	case RII_LUII:
7262 		if (oii) {
7263 			if (oii[0] == '0' && oii[1] == 'x')
7264 				len = hex2bin(oii, (uint8_t *)(rii_ptr + 1), len);
7265 			else
7266 				strncpy((uint8_t *)(rii_ptr + 1), oii, len);
7267 		}
7268 		break;
7269 	case RII_LUTII:
7270 		if (otii)
7271 			strlcpy((uint8_t *)(rii_ptr + 1), otii, len);
7272 		break;
7273 	case RII_IIS:
7274 		riid_ptr = (struct scsi_report_ident_info_descr *)(rii_ptr + 1);
7275 		riid_ptr->type = RII_LUII;
7276 		scsi_ulto2b(0xffff, riid_ptr->length);
7277 		riid_ptr++;
7278 		riid_ptr->type = RII_LUTII;
7279 		scsi_ulto2b(0xffff, riid_ptr->length);
7280 	}
7281 	scsi_ulto2b(len, rii_ptr->length);
7282 
7283 	ctl_set_success(ctsio);
7284 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7285 	ctsio->be_move_done = ctl_config_move_done;
7286 	ctl_datamove((union ctl_io *)ctsio);
7287 	return(retval);
7288 }
7289 
7290 int
7291 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7292 {
7293 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7294 	struct ctl_lun *lun = CTL_LUN(ctsio);
7295 	struct scsi_maintenance_in *cdb;
7296 	int retval;
7297 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7298 	int num_ha_groups, num_target_ports, shared_group;
7299 	struct ctl_port *port;
7300 	struct scsi_target_group_data *rtg_ptr;
7301 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7302 	struct scsi_target_port_group_descriptor *tpg_desc;
7303 
7304 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7305 
7306 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7307 	retval = CTL_RETVAL_COMPLETE;
7308 
7309 	switch (cdb->byte2 & STG_PDF_MASK) {
7310 	case STG_PDF_LENGTH:
7311 		ext = 0;
7312 		break;
7313 	case STG_PDF_EXTENDED:
7314 		ext = 1;
7315 		break;
7316 	default:
7317 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7318 				      /*sks_valid*/ 1,
7319 				      /*command*/ 1,
7320 				      /*field*/ 2,
7321 				      /*bit_valid*/ 1,
7322 				      /*bit*/ 5);
7323 		ctl_done((union ctl_io *)ctsio);
7324 		return(retval);
7325 	}
7326 
7327 	num_target_ports = 0;
7328 	shared_group = (softc->is_single != 0);
7329 	mtx_lock(&softc->ctl_lock);
7330 	STAILQ_FOREACH(port, &softc->port_list, links) {
7331 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7332 			continue;
7333 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7334 			continue;
7335 		num_target_ports++;
7336 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7337 			shared_group = 1;
7338 	}
7339 	mtx_unlock(&softc->ctl_lock);
7340 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7341 
7342 	if (ext)
7343 		total_len = sizeof(struct scsi_target_group_data_extended);
7344 	else
7345 		total_len = sizeof(struct scsi_target_group_data);
7346 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7347 		(shared_group + num_ha_groups) +
7348 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7349 
7350 	alloc_len = scsi_4btoul(cdb->length);
7351 
7352 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7353 	ctsio->kern_sg_entries = 0;
7354 	ctsio->kern_rel_offset = 0;
7355 	ctsio->kern_data_len = min(total_len, alloc_len);
7356 	ctsio->kern_total_len = ctsio->kern_data_len;
7357 
7358 	if (ext) {
7359 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7360 		    ctsio->kern_data_ptr;
7361 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7362 		rtg_ext_ptr->format_type = 0x10;
7363 		rtg_ext_ptr->implicit_transition_time = 0;
7364 		tpg_desc = &rtg_ext_ptr->groups[0];
7365 	} else {
7366 		rtg_ptr = (struct scsi_target_group_data *)
7367 		    ctsio->kern_data_ptr;
7368 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7369 		tpg_desc = &rtg_ptr->groups[0];
7370 	}
7371 
7372 	mtx_lock(&softc->ctl_lock);
7373 	pg = softc->port_min / softc->port_cnt;
7374 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7375 		/* Some shelf is known to be primary. */
7376 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7377 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7378 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7379 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7380 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7381 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7382 		else
7383 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7384 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7385 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7386 		} else {
7387 			ts = os;
7388 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7389 		}
7390 	} else {
7391 		/* No known primary shelf. */
7392 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7393 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7394 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7395 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7396 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7397 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7398 		} else {
7399 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7400 		}
7401 	}
7402 	if (shared_group) {
7403 		tpg_desc->pref_state = ts;
7404 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7405 		    TPG_U_SUP | TPG_T_SUP;
7406 		scsi_ulto2b(1, tpg_desc->target_port_group);
7407 		tpg_desc->status = TPG_IMPLICIT;
7408 		pc = 0;
7409 		STAILQ_FOREACH(port, &softc->port_list, links) {
7410 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7411 				continue;
7412 			if (!softc->is_single &&
7413 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7414 				continue;
7415 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7416 				continue;
7417 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7418 			    relative_target_port_identifier);
7419 			pc++;
7420 		}
7421 		tpg_desc->target_port_count = pc;
7422 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7423 		    &tpg_desc->descriptors[pc];
7424 	}
7425 	for (g = 0; g < num_ha_groups; g++) {
7426 		tpg_desc->pref_state = (g == pg) ? ts : os;
7427 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7428 		    TPG_U_SUP | TPG_T_SUP;
7429 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7430 		tpg_desc->status = TPG_IMPLICIT;
7431 		pc = 0;
7432 		STAILQ_FOREACH(port, &softc->port_list, links) {
7433 			if (port->targ_port < g * softc->port_cnt ||
7434 			    port->targ_port >= (g + 1) * softc->port_cnt)
7435 				continue;
7436 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7437 				continue;
7438 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7439 				continue;
7440 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7441 				continue;
7442 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7443 			    relative_target_port_identifier);
7444 			pc++;
7445 		}
7446 		tpg_desc->target_port_count = pc;
7447 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7448 		    &tpg_desc->descriptors[pc];
7449 	}
7450 	mtx_unlock(&softc->ctl_lock);
7451 
7452 	ctl_set_success(ctsio);
7453 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7454 	ctsio->be_move_done = ctl_config_move_done;
7455 	ctl_datamove((union ctl_io *)ctsio);
7456 	return(retval);
7457 }
7458 
7459 int
7460 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7461 {
7462 	struct ctl_lun *lun = CTL_LUN(ctsio);
7463 	struct scsi_report_supported_opcodes *cdb;
7464 	const struct ctl_cmd_entry *entry, *sentry;
7465 	struct scsi_report_supported_opcodes_all *all;
7466 	struct scsi_report_supported_opcodes_descr *descr;
7467 	struct scsi_report_supported_opcodes_one *one;
7468 	int retval;
7469 	int alloc_len, total_len;
7470 	int opcode, service_action, i, j, num;
7471 
7472 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7473 
7474 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7475 	retval = CTL_RETVAL_COMPLETE;
7476 
7477 	opcode = cdb->requested_opcode;
7478 	service_action = scsi_2btoul(cdb->requested_service_action);
7479 	switch (cdb->options & RSO_OPTIONS_MASK) {
7480 	case RSO_OPTIONS_ALL:
7481 		num = 0;
7482 		for (i = 0; i < 256; i++) {
7483 			entry = &ctl_cmd_table[i];
7484 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7485 				for (j = 0; j < 32; j++) {
7486 					sentry = &((const struct ctl_cmd_entry *)
7487 					    entry->execute)[j];
7488 					if (ctl_cmd_applicable(
7489 					    lun->be_lun->lun_type, sentry))
7490 						num++;
7491 				}
7492 			} else {
7493 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7494 				    entry))
7495 					num++;
7496 			}
7497 		}
7498 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7499 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7500 		break;
7501 	case RSO_OPTIONS_OC:
7502 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7503 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7504 					      /*sks_valid*/ 1,
7505 					      /*command*/ 1,
7506 					      /*field*/ 2,
7507 					      /*bit_valid*/ 1,
7508 					      /*bit*/ 2);
7509 			ctl_done((union ctl_io *)ctsio);
7510 			return (CTL_RETVAL_COMPLETE);
7511 		}
7512 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7513 		break;
7514 	case RSO_OPTIONS_OC_SA:
7515 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7516 		    service_action >= 32) {
7517 			goto invalid;
7518 		}
7519 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7520 		break;
7521 	case RSO_OPTIONS_OC_ASA:
7522 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) != 0 &&
7523 		    service_action >= 32) {
7524 			goto invalid;
7525 		}
7526 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7527 		break;
7528 	default:
7529 invalid:
7530 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7531 				      /*sks_valid*/ 1,
7532 				      /*command*/ 1,
7533 				      /*field*/ 2,
7534 				      /*bit_valid*/ 1,
7535 				      /*bit*/ 2);
7536 		ctl_done((union ctl_io *)ctsio);
7537 		return (CTL_RETVAL_COMPLETE);
7538 	}
7539 
7540 	alloc_len = scsi_4btoul(cdb->length);
7541 
7542 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7543 	ctsio->kern_sg_entries = 0;
7544 	ctsio->kern_rel_offset = 0;
7545 	ctsio->kern_data_len = min(total_len, alloc_len);
7546 	ctsio->kern_total_len = ctsio->kern_data_len;
7547 
7548 	switch (cdb->options & RSO_OPTIONS_MASK) {
7549 	case RSO_OPTIONS_ALL:
7550 		all = (struct scsi_report_supported_opcodes_all *)
7551 		    ctsio->kern_data_ptr;
7552 		num = 0;
7553 		for (i = 0; i < 256; i++) {
7554 			entry = &ctl_cmd_table[i];
7555 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7556 				for (j = 0; j < 32; j++) {
7557 					sentry = &((const struct ctl_cmd_entry *)
7558 					    entry->execute)[j];
7559 					if (!ctl_cmd_applicable(
7560 					    lun->be_lun->lun_type, sentry))
7561 						continue;
7562 					descr = &all->descr[num++];
7563 					descr->opcode = i;
7564 					scsi_ulto2b(j, descr->service_action);
7565 					descr->flags = RSO_SERVACTV;
7566 					scsi_ulto2b(sentry->length,
7567 					    descr->cdb_length);
7568 				}
7569 			} else {
7570 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7571 				    entry))
7572 					continue;
7573 				descr = &all->descr[num++];
7574 				descr->opcode = i;
7575 				scsi_ulto2b(0, descr->service_action);
7576 				descr->flags = 0;
7577 				scsi_ulto2b(entry->length, descr->cdb_length);
7578 			}
7579 		}
7580 		scsi_ulto4b(
7581 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7582 		    all->length);
7583 		break;
7584 	case RSO_OPTIONS_OC:
7585 		one = (struct scsi_report_supported_opcodes_one *)
7586 		    ctsio->kern_data_ptr;
7587 		entry = &ctl_cmd_table[opcode];
7588 		goto fill_one;
7589 	case RSO_OPTIONS_OC_SA:
7590 		one = (struct scsi_report_supported_opcodes_one *)
7591 		    ctsio->kern_data_ptr;
7592 		entry = &ctl_cmd_table[opcode];
7593 		entry = &((const struct ctl_cmd_entry *)
7594 		    entry->execute)[service_action];
7595 fill_one:
7596 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7597 			one->support = 3;
7598 			scsi_ulto2b(entry->length, one->cdb_length);
7599 			one->cdb_usage[0] = opcode;
7600 			memcpy(&one->cdb_usage[1], entry->usage,
7601 			    entry->length - 1);
7602 		} else
7603 			one->support = 1;
7604 		break;
7605 	case RSO_OPTIONS_OC_ASA:
7606 		one = (struct scsi_report_supported_opcodes_one *)
7607 		    ctsio->kern_data_ptr;
7608 		entry = &ctl_cmd_table[opcode];
7609 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7610 			entry = &((const struct ctl_cmd_entry *)
7611 			    entry->execute)[service_action];
7612 		} else if (service_action != 0) {
7613 			one->support = 1;
7614 			break;
7615 		}
7616 		goto fill_one;
7617 	}
7618 
7619 	ctl_set_success(ctsio);
7620 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7621 	ctsio->be_move_done = ctl_config_move_done;
7622 	ctl_datamove((union ctl_io *)ctsio);
7623 	return(retval);
7624 }
7625 
7626 int
7627 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7628 {
7629 	struct scsi_report_supported_tmf *cdb;
7630 	struct scsi_report_supported_tmf_ext_data *data;
7631 	int retval;
7632 	int alloc_len, total_len;
7633 
7634 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7635 
7636 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7637 
7638 	retval = CTL_RETVAL_COMPLETE;
7639 
7640 	if (cdb->options & RST_REPD)
7641 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7642 	else
7643 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7644 	alloc_len = scsi_4btoul(cdb->length);
7645 
7646 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7647 	ctsio->kern_sg_entries = 0;
7648 	ctsio->kern_rel_offset = 0;
7649 	ctsio->kern_data_len = min(total_len, alloc_len);
7650 	ctsio->kern_total_len = ctsio->kern_data_len;
7651 
7652 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7653 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7654 	    RST_TRS;
7655 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7656 	data->length = total_len - 4;
7657 
7658 	ctl_set_success(ctsio);
7659 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7660 	ctsio->be_move_done = ctl_config_move_done;
7661 	ctl_datamove((union ctl_io *)ctsio);
7662 	return (retval);
7663 }
7664 
7665 int
7666 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7667 {
7668 	struct scsi_report_timestamp *cdb;
7669 	struct scsi_report_timestamp_data *data;
7670 	struct timeval tv;
7671 	int64_t timestamp;
7672 	int retval;
7673 	int alloc_len, total_len;
7674 
7675 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7676 
7677 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7678 
7679 	retval = CTL_RETVAL_COMPLETE;
7680 
7681 	total_len = sizeof(struct scsi_report_timestamp_data);
7682 	alloc_len = scsi_4btoul(cdb->length);
7683 
7684 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7685 	ctsio->kern_sg_entries = 0;
7686 	ctsio->kern_rel_offset = 0;
7687 	ctsio->kern_data_len = min(total_len, alloc_len);
7688 	ctsio->kern_total_len = ctsio->kern_data_len;
7689 
7690 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7691 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7692 	data->origin = RTS_ORIG_OUTSIDE;
7693 	getmicrotime(&tv);
7694 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7695 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7696 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7697 
7698 	ctl_set_success(ctsio);
7699 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7700 	ctsio->be_move_done = ctl_config_move_done;
7701 	ctl_datamove((union ctl_io *)ctsio);
7702 	return (retval);
7703 }
7704 
7705 int
7706 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7707 {
7708 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7709 	struct ctl_lun *lun = CTL_LUN(ctsio);
7710 	struct scsi_per_res_in *cdb;
7711 	int alloc_len, total_len = 0;
7712 	/* struct scsi_per_res_in_rsrv in_data; */
7713 	uint64_t key;
7714 
7715 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7716 
7717 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7718 
7719 	alloc_len = scsi_2btoul(cdb->length);
7720 
7721 retry:
7722 	mtx_lock(&lun->lun_lock);
7723 	switch (cdb->action) {
7724 	case SPRI_RK: /* read keys */
7725 		total_len = sizeof(struct scsi_per_res_in_keys) +
7726 			lun->pr_key_count *
7727 			sizeof(struct scsi_per_res_key);
7728 		break;
7729 	case SPRI_RR: /* read reservation */
7730 		if (lun->flags & CTL_LUN_PR_RESERVED)
7731 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7732 		else
7733 			total_len = sizeof(struct scsi_per_res_in_header);
7734 		break;
7735 	case SPRI_RC: /* report capabilities */
7736 		total_len = sizeof(struct scsi_per_res_cap);
7737 		break;
7738 	case SPRI_RS: /* read full status */
7739 		total_len = sizeof(struct scsi_per_res_in_header) +
7740 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7741 		    lun->pr_key_count;
7742 		break;
7743 	default:
7744 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7745 	}
7746 	mtx_unlock(&lun->lun_lock);
7747 
7748 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7749 	ctsio->kern_rel_offset = 0;
7750 	ctsio->kern_sg_entries = 0;
7751 	ctsio->kern_data_len = min(total_len, alloc_len);
7752 	ctsio->kern_total_len = ctsio->kern_data_len;
7753 
7754 	mtx_lock(&lun->lun_lock);
7755 	switch (cdb->action) {
7756 	case SPRI_RK: { // read keys
7757         struct scsi_per_res_in_keys *res_keys;
7758 		int i, key_count;
7759 
7760 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7761 
7762 		/*
7763 		 * We had to drop the lock to allocate our buffer, which
7764 		 * leaves time for someone to come in with another
7765 		 * persistent reservation.  (That is unlikely, though,
7766 		 * since this should be the only persistent reservation
7767 		 * command active right now.)
7768 		 */
7769 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7770 		    (lun->pr_key_count *
7771 		     sizeof(struct scsi_per_res_key)))){
7772 			mtx_unlock(&lun->lun_lock);
7773 			free(ctsio->kern_data_ptr, M_CTL);
7774 			printf("%s: reservation length changed, retrying\n",
7775 			       __func__);
7776 			goto retry;
7777 		}
7778 
7779 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7780 
7781 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7782 			     lun->pr_key_count, res_keys->header.length);
7783 
7784 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7785 			if ((key = ctl_get_prkey(lun, i)) == 0)
7786 				continue;
7787 
7788 			/*
7789 			 * We used lun->pr_key_count to calculate the
7790 			 * size to allocate.  If it turns out the number of
7791 			 * initiators with the registered flag set is
7792 			 * larger than that (i.e. they haven't been kept in
7793 			 * sync), we've got a problem.
7794 			 */
7795 			if (key_count >= lun->pr_key_count) {
7796 				key_count++;
7797 				continue;
7798 			}
7799 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7800 			key_count++;
7801 		}
7802 		break;
7803 	}
7804 	case SPRI_RR: { // read reservation
7805 		struct scsi_per_res_in_rsrv *res;
7806 		int tmp_len, header_only;
7807 
7808 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7809 
7810 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7811 
7812 		if (lun->flags & CTL_LUN_PR_RESERVED)
7813 		{
7814 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7815 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7816 				    res->header.length);
7817 			header_only = 0;
7818 		} else {
7819 			tmp_len = sizeof(struct scsi_per_res_in_header);
7820 			scsi_ulto4b(0, res->header.length);
7821 			header_only = 1;
7822 		}
7823 
7824 		/*
7825 		 * We had to drop the lock to allocate our buffer, which
7826 		 * leaves time for someone to come in with another
7827 		 * persistent reservation.  (That is unlikely, though,
7828 		 * since this should be the only persistent reservation
7829 		 * command active right now.)
7830 		 */
7831 		if (tmp_len != total_len) {
7832 			mtx_unlock(&lun->lun_lock);
7833 			free(ctsio->kern_data_ptr, M_CTL);
7834 			printf("%s: reservation status changed, retrying\n",
7835 			       __func__);
7836 			goto retry;
7837 		}
7838 
7839 		/*
7840 		 * No reservation held, so we're done.
7841 		 */
7842 		if (header_only != 0)
7843 			break;
7844 
7845 		/*
7846 		 * If the registration is an All Registrants type, the key
7847 		 * is 0, since it doesn't really matter.
7848 		 */
7849 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7850 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7851 			    res->data.reservation);
7852 		}
7853 		res->data.scopetype = lun->pr_res_type;
7854 		break;
7855 	}
7856 	case SPRI_RC:     //report capabilities
7857 	{
7858 		struct scsi_per_res_cap *res_cap;
7859 		uint16_t type_mask;
7860 
7861 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7862 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7863 		res_cap->flags1 = SPRI_CRH;
7864 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7865 		type_mask = SPRI_TM_WR_EX_AR |
7866 			    SPRI_TM_EX_AC_RO |
7867 			    SPRI_TM_WR_EX_RO |
7868 			    SPRI_TM_EX_AC |
7869 			    SPRI_TM_WR_EX |
7870 			    SPRI_TM_EX_AC_AR;
7871 		scsi_ulto2b(type_mask, res_cap->type_mask);
7872 		break;
7873 	}
7874 	case SPRI_RS: { // read full status
7875 		struct scsi_per_res_in_full *res_status;
7876 		struct scsi_per_res_in_full_desc *res_desc;
7877 		struct ctl_port *port;
7878 		int i, len;
7879 
7880 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7881 
7882 		/*
7883 		 * We had to drop the lock to allocate our buffer, which
7884 		 * leaves time for someone to come in with another
7885 		 * persistent reservation.  (That is unlikely, though,
7886 		 * since this should be the only persistent reservation
7887 		 * command active right now.)
7888 		 */
7889 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7890 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7891 		     lun->pr_key_count)){
7892 			mtx_unlock(&lun->lun_lock);
7893 			free(ctsio->kern_data_ptr, M_CTL);
7894 			printf("%s: reservation length changed, retrying\n",
7895 			       __func__);
7896 			goto retry;
7897 		}
7898 
7899 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7900 
7901 		res_desc = &res_status->desc[0];
7902 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7903 			if ((key = ctl_get_prkey(lun, i)) == 0)
7904 				continue;
7905 
7906 			scsi_u64to8b(key, res_desc->res_key.key);
7907 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7908 			    (lun->pr_res_idx == i ||
7909 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7910 				res_desc->flags = SPRI_FULL_R_HOLDER;
7911 				res_desc->scopetype = lun->pr_res_type;
7912 			}
7913 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7914 			    res_desc->rel_trgt_port_id);
7915 			len = 0;
7916 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7917 			if (port != NULL)
7918 				len = ctl_create_iid(port,
7919 				    i % CTL_MAX_INIT_PER_PORT,
7920 				    res_desc->transport_id);
7921 			scsi_ulto4b(len, res_desc->additional_length);
7922 			res_desc = (struct scsi_per_res_in_full_desc *)
7923 			    &res_desc->transport_id[len];
7924 		}
7925 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7926 		    res_status->header.length);
7927 		break;
7928 	}
7929 	default:
7930 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7931 	}
7932 	mtx_unlock(&lun->lun_lock);
7933 
7934 	ctl_set_success(ctsio);
7935 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7936 	ctsio->be_move_done = ctl_config_move_done;
7937 	ctl_datamove((union ctl_io *)ctsio);
7938 	return (CTL_RETVAL_COMPLETE);
7939 }
7940 
7941 /*
7942  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7943  * it should return.
7944  */
7945 static int
7946 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7947 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7948 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7949 		struct scsi_per_res_out_parms* param)
7950 {
7951 	union ctl_ha_msg persis_io;
7952 	int i;
7953 
7954 	mtx_lock(&lun->lun_lock);
7955 	if (sa_res_key == 0) {
7956 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7957 			/* validate scope and type */
7958 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7959 			     SPR_LU_SCOPE) {
7960 				mtx_unlock(&lun->lun_lock);
7961 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7962 						      /*sks_valid*/ 1,
7963 						      /*command*/ 1,
7964 						      /*field*/ 2,
7965 						      /*bit_valid*/ 1,
7966 						      /*bit*/ 4);
7967 				ctl_done((union ctl_io *)ctsio);
7968 				return (1);
7969 			}
7970 
7971 		        if (type>8 || type==2 || type==4 || type==0) {
7972 				mtx_unlock(&lun->lun_lock);
7973 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7974        	           				      /*sks_valid*/ 1,
7975 						      /*command*/ 1,
7976 						      /*field*/ 2,
7977 						      /*bit_valid*/ 1,
7978 						      /*bit*/ 0);
7979 				ctl_done((union ctl_io *)ctsio);
7980 				return (1);
7981 		        }
7982 
7983 			/*
7984 			 * Unregister everybody else and build UA for
7985 			 * them
7986 			 */
7987 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7988 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7989 					continue;
7990 
7991 				ctl_clr_prkey(lun, i);
7992 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7993 			}
7994 			lun->pr_key_count = 1;
7995 			lun->pr_res_type = type;
7996 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7997 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7998 				lun->pr_res_idx = residx;
7999 			lun->pr_generation++;
8000 			mtx_unlock(&lun->lun_lock);
8001 
8002 			/* send msg to other side */
8003 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8004 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8005 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8006 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8007 			persis_io.pr.pr_info.res_type = type;
8008 			memcpy(persis_io.pr.pr_info.sa_res_key,
8009 			       param->serv_act_res_key,
8010 			       sizeof(param->serv_act_res_key));
8011 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8012 			    sizeof(persis_io.pr), M_WAITOK);
8013 		} else {
8014 			/* not all registrants */
8015 			mtx_unlock(&lun->lun_lock);
8016 			free(ctsio->kern_data_ptr, M_CTL);
8017 			ctl_set_invalid_field(ctsio,
8018 					      /*sks_valid*/ 1,
8019 					      /*command*/ 0,
8020 					      /*field*/ 8,
8021 					      /*bit_valid*/ 0,
8022 					      /*bit*/ 0);
8023 			ctl_done((union ctl_io *)ctsio);
8024 			return (1);
8025 		}
8026 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8027 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8028 		int found = 0;
8029 
8030 		if (res_key == sa_res_key) {
8031 			/* special case */
8032 			/*
8033 			 * The spec implies this is not good but doesn't
8034 			 * say what to do. There are two choices either
8035 			 * generate a res conflict or check condition
8036 			 * with illegal field in parameter data. Since
8037 			 * that is what is done when the sa_res_key is
8038 			 * zero I'll take that approach since this has
8039 			 * to do with the sa_res_key.
8040 			 */
8041 			mtx_unlock(&lun->lun_lock);
8042 			free(ctsio->kern_data_ptr, M_CTL);
8043 			ctl_set_invalid_field(ctsio,
8044 					      /*sks_valid*/ 1,
8045 					      /*command*/ 0,
8046 					      /*field*/ 8,
8047 					      /*bit_valid*/ 0,
8048 					      /*bit*/ 0);
8049 			ctl_done((union ctl_io *)ctsio);
8050 			return (1);
8051 		}
8052 
8053 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8054 			if (ctl_get_prkey(lun, i) != sa_res_key)
8055 				continue;
8056 
8057 			found = 1;
8058 			ctl_clr_prkey(lun, i);
8059 			lun->pr_key_count--;
8060 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8061 		}
8062 		if (!found) {
8063 			mtx_unlock(&lun->lun_lock);
8064 			free(ctsio->kern_data_ptr, M_CTL);
8065 			ctl_set_reservation_conflict(ctsio);
8066 			ctl_done((union ctl_io *)ctsio);
8067 			return (CTL_RETVAL_COMPLETE);
8068 		}
8069 		lun->pr_generation++;
8070 		mtx_unlock(&lun->lun_lock);
8071 
8072 		/* send msg to other side */
8073 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8074 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8075 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8076 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8077 		persis_io.pr.pr_info.res_type = type;
8078 		memcpy(persis_io.pr.pr_info.sa_res_key,
8079 		       param->serv_act_res_key,
8080 		       sizeof(param->serv_act_res_key));
8081 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8082 		    sizeof(persis_io.pr), M_WAITOK);
8083 	} else {
8084 		/* Reserved but not all registrants */
8085 		/* sa_res_key is res holder */
8086 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8087 			/* validate scope and type */
8088 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8089 			     SPR_LU_SCOPE) {
8090 				mtx_unlock(&lun->lun_lock);
8091 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8092 						      /*sks_valid*/ 1,
8093 						      /*command*/ 1,
8094 						      /*field*/ 2,
8095 						      /*bit_valid*/ 1,
8096 						      /*bit*/ 4);
8097 				ctl_done((union ctl_io *)ctsio);
8098 				return (1);
8099 			}
8100 
8101 			if (type>8 || type==2 || type==4 || type==0) {
8102 				mtx_unlock(&lun->lun_lock);
8103 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8104 						      /*sks_valid*/ 1,
8105 						      /*command*/ 1,
8106 						      /*field*/ 2,
8107 						      /*bit_valid*/ 1,
8108 						      /*bit*/ 0);
8109 				ctl_done((union ctl_io *)ctsio);
8110 				return (1);
8111 			}
8112 
8113 			/*
8114 			 * Do the following:
8115 			 * if sa_res_key != res_key remove all
8116 			 * registrants w/sa_res_key and generate UA
8117 			 * for these registrants(Registrations
8118 			 * Preempted) if it wasn't an exclusive
8119 			 * reservation generate UA(Reservations
8120 			 * Preempted) for all other registered nexuses
8121 			 * if the type has changed. Establish the new
8122 			 * reservation and holder. If res_key and
8123 			 * sa_res_key are the same do the above
8124 			 * except don't unregister the res holder.
8125 			 */
8126 
8127 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8128 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8129 					continue;
8130 
8131 				if (sa_res_key == ctl_get_prkey(lun, i)) {
8132 					ctl_clr_prkey(lun, i);
8133 					lun->pr_key_count--;
8134 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8135 				} else if (type != lun->pr_res_type &&
8136 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8137 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8138 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8139 				}
8140 			}
8141 			lun->pr_res_type = type;
8142 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8143 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8144 				lun->pr_res_idx = residx;
8145 			else
8146 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8147 			lun->pr_generation++;
8148 			mtx_unlock(&lun->lun_lock);
8149 
8150 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8151 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8152 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8153 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8154 			persis_io.pr.pr_info.res_type = type;
8155 			memcpy(persis_io.pr.pr_info.sa_res_key,
8156 			       param->serv_act_res_key,
8157 			       sizeof(param->serv_act_res_key));
8158 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8159 			    sizeof(persis_io.pr), M_WAITOK);
8160 		} else {
8161 			/*
8162 			 * sa_res_key is not the res holder just
8163 			 * remove registrants
8164 			 */
8165 			int found=0;
8166 
8167 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8168 				if (sa_res_key != ctl_get_prkey(lun, i))
8169 					continue;
8170 
8171 				found = 1;
8172 				ctl_clr_prkey(lun, i);
8173 				lun->pr_key_count--;
8174 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8175 			}
8176 
8177 			if (!found) {
8178 				mtx_unlock(&lun->lun_lock);
8179 				free(ctsio->kern_data_ptr, M_CTL);
8180 				ctl_set_reservation_conflict(ctsio);
8181 				ctl_done((union ctl_io *)ctsio);
8182 		        	return (1);
8183 			}
8184 			lun->pr_generation++;
8185 			mtx_unlock(&lun->lun_lock);
8186 
8187 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8188 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8189 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8190 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8191 			persis_io.pr.pr_info.res_type = type;
8192 			memcpy(persis_io.pr.pr_info.sa_res_key,
8193 			       param->serv_act_res_key,
8194 			       sizeof(param->serv_act_res_key));
8195 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8196 			    sizeof(persis_io.pr), M_WAITOK);
8197 		}
8198 	}
8199 	return (0);
8200 }
8201 
8202 static void
8203 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8204 {
8205 	uint64_t sa_res_key;
8206 	int i;
8207 
8208 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8209 
8210 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8211 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8212 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8213 		if (sa_res_key == 0) {
8214 			/*
8215 			 * Unregister everybody else and build UA for
8216 			 * them
8217 			 */
8218 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8219 				if (i == msg->pr.pr_info.residx ||
8220 				    ctl_get_prkey(lun, i) == 0)
8221 					continue;
8222 
8223 				ctl_clr_prkey(lun, i);
8224 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8225 			}
8226 
8227 			lun->pr_key_count = 1;
8228 			lun->pr_res_type = msg->pr.pr_info.res_type;
8229 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8230 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8231 				lun->pr_res_idx = msg->pr.pr_info.residx;
8232 		} else {
8233 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8234 				if (sa_res_key == ctl_get_prkey(lun, i))
8235 					continue;
8236 
8237 				ctl_clr_prkey(lun, i);
8238 				lun->pr_key_count--;
8239 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8240 			}
8241 		}
8242 	} else {
8243 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8244 			if (i == msg->pr.pr_info.residx ||
8245 			    ctl_get_prkey(lun, i) == 0)
8246 				continue;
8247 
8248 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8249 				ctl_clr_prkey(lun, i);
8250 				lun->pr_key_count--;
8251 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8252 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8253 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8254 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8255 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8256 			}
8257 		}
8258 		lun->pr_res_type = msg->pr.pr_info.res_type;
8259 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8260 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8261 			lun->pr_res_idx = msg->pr.pr_info.residx;
8262 		else
8263 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8264 	}
8265 	lun->pr_generation++;
8266 
8267 }
8268 
8269 int
8270 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8271 {
8272 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8273 	struct ctl_lun *lun = CTL_LUN(ctsio);
8274 	int retval;
8275 	uint32_t param_len;
8276 	struct scsi_per_res_out *cdb;
8277 	struct scsi_per_res_out_parms* param;
8278 	uint32_t residx;
8279 	uint64_t res_key, sa_res_key, key;
8280 	uint8_t type;
8281 	union ctl_ha_msg persis_io;
8282 	int    i;
8283 
8284 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8285 
8286 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8287 	retval = CTL_RETVAL_COMPLETE;
8288 
8289 	/*
8290 	 * We only support whole-LUN scope.  The scope & type are ignored for
8291 	 * register, register and ignore existing key and clear.
8292 	 * We sometimes ignore scope and type on preempts too!!
8293 	 * Verify reservation type here as well.
8294 	 */
8295 	type = cdb->scope_type & SPR_TYPE_MASK;
8296 	if ((cdb->action == SPRO_RESERVE)
8297 	 || (cdb->action == SPRO_RELEASE)) {
8298 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8299 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8300 					      /*sks_valid*/ 1,
8301 					      /*command*/ 1,
8302 					      /*field*/ 2,
8303 					      /*bit_valid*/ 1,
8304 					      /*bit*/ 4);
8305 			ctl_done((union ctl_io *)ctsio);
8306 			return (CTL_RETVAL_COMPLETE);
8307 		}
8308 
8309 		if (type>8 || type==2 || type==4 || type==0) {
8310 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8311 					      /*sks_valid*/ 1,
8312 					      /*command*/ 1,
8313 					      /*field*/ 2,
8314 					      /*bit_valid*/ 1,
8315 					      /*bit*/ 0);
8316 			ctl_done((union ctl_io *)ctsio);
8317 			return (CTL_RETVAL_COMPLETE);
8318 		}
8319 	}
8320 
8321 	param_len = scsi_4btoul(cdb->length);
8322 
8323 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8324 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8325 		ctsio->kern_data_len = param_len;
8326 		ctsio->kern_total_len = param_len;
8327 		ctsio->kern_rel_offset = 0;
8328 		ctsio->kern_sg_entries = 0;
8329 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8330 		ctsio->be_move_done = ctl_config_move_done;
8331 		ctl_datamove((union ctl_io *)ctsio);
8332 
8333 		return (CTL_RETVAL_COMPLETE);
8334 	}
8335 
8336 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8337 
8338 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8339 	res_key = scsi_8btou64(param->res_key.key);
8340 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8341 
8342 	/*
8343 	 * Validate the reservation key here except for SPRO_REG_IGNO
8344 	 * This must be done for all other service actions
8345 	 */
8346 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8347 		mtx_lock(&lun->lun_lock);
8348 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8349 			if (res_key != key) {
8350 				/*
8351 				 * The current key passed in doesn't match
8352 				 * the one the initiator previously
8353 				 * registered.
8354 				 */
8355 				mtx_unlock(&lun->lun_lock);
8356 				free(ctsio->kern_data_ptr, M_CTL);
8357 				ctl_set_reservation_conflict(ctsio);
8358 				ctl_done((union ctl_io *)ctsio);
8359 				return (CTL_RETVAL_COMPLETE);
8360 			}
8361 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8362 			/*
8363 			 * We are not registered
8364 			 */
8365 			mtx_unlock(&lun->lun_lock);
8366 			free(ctsio->kern_data_ptr, M_CTL);
8367 			ctl_set_reservation_conflict(ctsio);
8368 			ctl_done((union ctl_io *)ctsio);
8369 			return (CTL_RETVAL_COMPLETE);
8370 		} else if (res_key != 0) {
8371 			/*
8372 			 * We are not registered and trying to register but
8373 			 * the register key isn't zero.
8374 			 */
8375 			mtx_unlock(&lun->lun_lock);
8376 			free(ctsio->kern_data_ptr, M_CTL);
8377 			ctl_set_reservation_conflict(ctsio);
8378 			ctl_done((union ctl_io *)ctsio);
8379 			return (CTL_RETVAL_COMPLETE);
8380 		}
8381 		mtx_unlock(&lun->lun_lock);
8382 	}
8383 
8384 	switch (cdb->action & SPRO_ACTION_MASK) {
8385 	case SPRO_REGISTER:
8386 	case SPRO_REG_IGNO: {
8387 		/*
8388 		 * We don't support any of these options, as we report in
8389 		 * the read capabilities request (see
8390 		 * ctl_persistent_reserve_in(), above).
8391 		 */
8392 		if ((param->flags & SPR_SPEC_I_PT)
8393 		 || (param->flags & SPR_ALL_TG_PT)
8394 		 || (param->flags & SPR_APTPL)) {
8395 			int bit_ptr;
8396 
8397 			if (param->flags & SPR_APTPL)
8398 				bit_ptr = 0;
8399 			else if (param->flags & SPR_ALL_TG_PT)
8400 				bit_ptr = 2;
8401 			else /* SPR_SPEC_I_PT */
8402 				bit_ptr = 3;
8403 
8404 			free(ctsio->kern_data_ptr, M_CTL);
8405 			ctl_set_invalid_field(ctsio,
8406 					      /*sks_valid*/ 1,
8407 					      /*command*/ 0,
8408 					      /*field*/ 20,
8409 					      /*bit_valid*/ 1,
8410 					      /*bit*/ bit_ptr);
8411 			ctl_done((union ctl_io *)ctsio);
8412 			return (CTL_RETVAL_COMPLETE);
8413 		}
8414 
8415 		mtx_lock(&lun->lun_lock);
8416 
8417 		/*
8418 		 * The initiator wants to clear the
8419 		 * key/unregister.
8420 		 */
8421 		if (sa_res_key == 0) {
8422 			if ((res_key == 0
8423 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8424 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8425 			  && ctl_get_prkey(lun, residx) == 0)) {
8426 				mtx_unlock(&lun->lun_lock);
8427 				goto done;
8428 			}
8429 
8430 			ctl_clr_prkey(lun, residx);
8431 			lun->pr_key_count--;
8432 
8433 			if (residx == lun->pr_res_idx) {
8434 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8435 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8436 
8437 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8438 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8439 				    lun->pr_key_count) {
8440 					/*
8441 					 * If the reservation is a registrants
8442 					 * only type we need to generate a UA
8443 					 * for other registered inits.  The
8444 					 * sense code should be RESERVATIONS
8445 					 * RELEASED
8446 					 */
8447 
8448 					for (i = softc->init_min; i < softc->init_max; i++){
8449 						if (ctl_get_prkey(lun, i) == 0)
8450 							continue;
8451 						ctl_est_ua(lun, i,
8452 						    CTL_UA_RES_RELEASE);
8453 					}
8454 				}
8455 				lun->pr_res_type = 0;
8456 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8457 				if (lun->pr_key_count==0) {
8458 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8459 					lun->pr_res_type = 0;
8460 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8461 				}
8462 			}
8463 			lun->pr_generation++;
8464 			mtx_unlock(&lun->lun_lock);
8465 
8466 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8467 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8468 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8469 			persis_io.pr.pr_info.residx = residx;
8470 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8471 			    sizeof(persis_io.pr), M_WAITOK);
8472 		} else /* sa_res_key != 0 */ {
8473 			/*
8474 			 * If we aren't registered currently then increment
8475 			 * the key count and set the registered flag.
8476 			 */
8477 			ctl_alloc_prkey(lun, residx);
8478 			if (ctl_get_prkey(lun, residx) == 0)
8479 				lun->pr_key_count++;
8480 			ctl_set_prkey(lun, residx, sa_res_key);
8481 			lun->pr_generation++;
8482 			mtx_unlock(&lun->lun_lock);
8483 
8484 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8485 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8486 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8487 			persis_io.pr.pr_info.residx = residx;
8488 			memcpy(persis_io.pr.pr_info.sa_res_key,
8489 			       param->serv_act_res_key,
8490 			       sizeof(param->serv_act_res_key));
8491 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8492 			    sizeof(persis_io.pr), M_WAITOK);
8493 		}
8494 
8495 		break;
8496 	}
8497 	case SPRO_RESERVE:
8498 		mtx_lock(&lun->lun_lock);
8499 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8500 			/*
8501 			 * if this isn't the reservation holder and it's
8502 			 * not a "all registrants" type or if the type is
8503 			 * different then we have a conflict
8504 			 */
8505 			if ((lun->pr_res_idx != residx
8506 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8507 			 || lun->pr_res_type != type) {
8508 				mtx_unlock(&lun->lun_lock);
8509 				free(ctsio->kern_data_ptr, M_CTL);
8510 				ctl_set_reservation_conflict(ctsio);
8511 				ctl_done((union ctl_io *)ctsio);
8512 				return (CTL_RETVAL_COMPLETE);
8513 			}
8514 			mtx_unlock(&lun->lun_lock);
8515 		} else /* create a reservation */ {
8516 			/*
8517 			 * If it's not an "all registrants" type record
8518 			 * reservation holder
8519 			 */
8520 			if (type != SPR_TYPE_WR_EX_AR
8521 			 && type != SPR_TYPE_EX_AC_AR)
8522 				lun->pr_res_idx = residx; /* Res holder */
8523 			else
8524 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8525 
8526 			lun->flags |= CTL_LUN_PR_RESERVED;
8527 			lun->pr_res_type = type;
8528 
8529 			mtx_unlock(&lun->lun_lock);
8530 
8531 			/* send msg to other side */
8532 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8533 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8534 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8535 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8536 			persis_io.pr.pr_info.res_type = type;
8537 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8538 			    sizeof(persis_io.pr), M_WAITOK);
8539 		}
8540 		break;
8541 
8542 	case SPRO_RELEASE:
8543 		mtx_lock(&lun->lun_lock);
8544 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8545 			/* No reservation exists return good status */
8546 			mtx_unlock(&lun->lun_lock);
8547 			goto done;
8548 		}
8549 		/*
8550 		 * Is this nexus a reservation holder?
8551 		 */
8552 		if (lun->pr_res_idx != residx
8553 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8554 			/*
8555 			 * not a res holder return good status but
8556 			 * do nothing
8557 			 */
8558 			mtx_unlock(&lun->lun_lock);
8559 			goto done;
8560 		}
8561 
8562 		if (lun->pr_res_type != type) {
8563 			mtx_unlock(&lun->lun_lock);
8564 			free(ctsio->kern_data_ptr, M_CTL);
8565 			ctl_set_illegal_pr_release(ctsio);
8566 			ctl_done((union ctl_io *)ctsio);
8567 			return (CTL_RETVAL_COMPLETE);
8568 		}
8569 
8570 		/* okay to release */
8571 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8572 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8573 		lun->pr_res_type = 0;
8574 
8575 		/*
8576 		 * If this isn't an exclusive access reservation and NUAR
8577 		 * is not set, generate UA for all other registrants.
8578 		 */
8579 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8580 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8581 			for (i = softc->init_min; i < softc->init_max; i++) {
8582 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8583 					continue;
8584 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8585 			}
8586 		}
8587 		mtx_unlock(&lun->lun_lock);
8588 
8589 		/* Send msg to other side */
8590 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8591 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8592 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8593 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8594 		     sizeof(persis_io.pr), M_WAITOK);
8595 		break;
8596 
8597 	case SPRO_CLEAR:
8598 		/* send msg to other side */
8599 
8600 		mtx_lock(&lun->lun_lock);
8601 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8602 		lun->pr_res_type = 0;
8603 		lun->pr_key_count = 0;
8604 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8605 
8606 		ctl_clr_prkey(lun, residx);
8607 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8608 			if (ctl_get_prkey(lun, i) != 0) {
8609 				ctl_clr_prkey(lun, i);
8610 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8611 			}
8612 		lun->pr_generation++;
8613 		mtx_unlock(&lun->lun_lock);
8614 
8615 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8616 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8617 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8618 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8619 		     sizeof(persis_io.pr), M_WAITOK);
8620 		break;
8621 
8622 	case SPRO_PREEMPT:
8623 	case SPRO_PRE_ABO: {
8624 		int nretval;
8625 
8626 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8627 					  residx, ctsio, cdb, param);
8628 		if (nretval != 0)
8629 			return (CTL_RETVAL_COMPLETE);
8630 		break;
8631 	}
8632 	default:
8633 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8634 	}
8635 
8636 done:
8637 	free(ctsio->kern_data_ptr, M_CTL);
8638 	ctl_set_success(ctsio);
8639 	ctl_done((union ctl_io *)ctsio);
8640 
8641 	return (retval);
8642 }
8643 
8644 /*
8645  * This routine is for handling a message from the other SC pertaining to
8646  * persistent reserve out. All the error checking will have been done
8647  * so only performing the action need be done here to keep the two
8648  * in sync.
8649  */
8650 static void
8651 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8652 {
8653 	struct ctl_softc *softc = CTL_SOFTC(io);
8654 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8655 	struct ctl_lun *lun;
8656 	int i;
8657 	uint32_t residx, targ_lun;
8658 
8659 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8660 	mtx_lock(&softc->ctl_lock);
8661 	if (targ_lun >= ctl_max_luns ||
8662 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8663 		mtx_unlock(&softc->ctl_lock);
8664 		return;
8665 	}
8666 	mtx_lock(&lun->lun_lock);
8667 	mtx_unlock(&softc->ctl_lock);
8668 	if (lun->flags & CTL_LUN_DISABLED) {
8669 		mtx_unlock(&lun->lun_lock);
8670 		return;
8671 	}
8672 	residx = ctl_get_initindex(&msg->hdr.nexus);
8673 	switch(msg->pr.pr_info.action) {
8674 	case CTL_PR_REG_KEY:
8675 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8676 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8677 			lun->pr_key_count++;
8678 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8679 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8680 		lun->pr_generation++;
8681 		break;
8682 
8683 	case CTL_PR_UNREG_KEY:
8684 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8685 		lun->pr_key_count--;
8686 
8687 		/* XXX Need to see if the reservation has been released */
8688 		/* if so do we need to generate UA? */
8689 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8690 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8691 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8692 
8693 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8694 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8695 			    lun->pr_key_count) {
8696 				/*
8697 				 * If the reservation is a registrants
8698 				 * only type we need to generate a UA
8699 				 * for other registered inits.  The
8700 				 * sense code should be RESERVATIONS
8701 				 * RELEASED
8702 				 */
8703 
8704 				for (i = softc->init_min; i < softc->init_max; i++) {
8705 					if (ctl_get_prkey(lun, i) == 0)
8706 						continue;
8707 
8708 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8709 				}
8710 			}
8711 			lun->pr_res_type = 0;
8712 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8713 			if (lun->pr_key_count==0) {
8714 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8715 				lun->pr_res_type = 0;
8716 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8717 			}
8718 		}
8719 		lun->pr_generation++;
8720 		break;
8721 
8722 	case CTL_PR_RESERVE:
8723 		lun->flags |= CTL_LUN_PR_RESERVED;
8724 		lun->pr_res_type = msg->pr.pr_info.res_type;
8725 		lun->pr_res_idx = msg->pr.pr_info.residx;
8726 
8727 		break;
8728 
8729 	case CTL_PR_RELEASE:
8730 		/*
8731 		 * If this isn't an exclusive access reservation and NUAR
8732 		 * is not set, generate UA for all other registrants.
8733 		 */
8734 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8735 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8736 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8737 			for (i = softc->init_min; i < softc->init_max; i++) {
8738 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8739 					continue;
8740 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8741 			}
8742 		}
8743 
8744 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8745 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8746 		lun->pr_res_type = 0;
8747 		break;
8748 
8749 	case CTL_PR_PREEMPT:
8750 		ctl_pro_preempt_other(lun, msg);
8751 		break;
8752 	case CTL_PR_CLEAR:
8753 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8754 		lun->pr_res_type = 0;
8755 		lun->pr_key_count = 0;
8756 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8757 
8758 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8759 			if (ctl_get_prkey(lun, i) == 0)
8760 				continue;
8761 			ctl_clr_prkey(lun, i);
8762 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8763 		}
8764 		lun->pr_generation++;
8765 		break;
8766 	}
8767 
8768 	mtx_unlock(&lun->lun_lock);
8769 }
8770 
8771 int
8772 ctl_read_write(struct ctl_scsiio *ctsio)
8773 {
8774 	struct ctl_lun *lun = CTL_LUN(ctsio);
8775 	struct ctl_lba_len_flags *lbalen;
8776 	uint64_t lba;
8777 	uint32_t num_blocks;
8778 	int flags, retval;
8779 	int isread;
8780 
8781 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8782 
8783 	flags = 0;
8784 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8785 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8786 	switch (ctsio->cdb[0]) {
8787 	case READ_6:
8788 	case WRITE_6: {
8789 		struct scsi_rw_6 *cdb;
8790 
8791 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8792 
8793 		lba = scsi_3btoul(cdb->addr);
8794 		/* only 5 bits are valid in the most significant address byte */
8795 		lba &= 0x1fffff;
8796 		num_blocks = cdb->length;
8797 		/*
8798 		 * This is correct according to SBC-2.
8799 		 */
8800 		if (num_blocks == 0)
8801 			num_blocks = 256;
8802 		break;
8803 	}
8804 	case READ_10:
8805 	case WRITE_10: {
8806 		struct scsi_rw_10 *cdb;
8807 
8808 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8809 		if (cdb->byte2 & SRW10_FUA)
8810 			flags |= CTL_LLF_FUA;
8811 		if (cdb->byte2 & SRW10_DPO)
8812 			flags |= CTL_LLF_DPO;
8813 		lba = scsi_4btoul(cdb->addr);
8814 		num_blocks = scsi_2btoul(cdb->length);
8815 		break;
8816 	}
8817 	case WRITE_VERIFY_10: {
8818 		struct scsi_write_verify_10 *cdb;
8819 
8820 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8821 		flags |= CTL_LLF_FUA;
8822 		if (cdb->byte2 & SWV_DPO)
8823 			flags |= CTL_LLF_DPO;
8824 		lba = scsi_4btoul(cdb->addr);
8825 		num_blocks = scsi_2btoul(cdb->length);
8826 		break;
8827 	}
8828 	case READ_12:
8829 	case WRITE_12: {
8830 		struct scsi_rw_12 *cdb;
8831 
8832 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8833 		if (cdb->byte2 & SRW12_FUA)
8834 			flags |= CTL_LLF_FUA;
8835 		if (cdb->byte2 & SRW12_DPO)
8836 			flags |= CTL_LLF_DPO;
8837 		lba = scsi_4btoul(cdb->addr);
8838 		num_blocks = scsi_4btoul(cdb->length);
8839 		break;
8840 	}
8841 	case WRITE_VERIFY_12: {
8842 		struct scsi_write_verify_12 *cdb;
8843 
8844 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8845 		flags |= CTL_LLF_FUA;
8846 		if (cdb->byte2 & SWV_DPO)
8847 			flags |= CTL_LLF_DPO;
8848 		lba = scsi_4btoul(cdb->addr);
8849 		num_blocks = scsi_4btoul(cdb->length);
8850 		break;
8851 	}
8852 	case READ_16:
8853 	case WRITE_16: {
8854 		struct scsi_rw_16 *cdb;
8855 
8856 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8857 		if (cdb->byte2 & SRW12_FUA)
8858 			flags |= CTL_LLF_FUA;
8859 		if (cdb->byte2 & SRW12_DPO)
8860 			flags |= CTL_LLF_DPO;
8861 		lba = scsi_8btou64(cdb->addr);
8862 		num_blocks = scsi_4btoul(cdb->length);
8863 		break;
8864 	}
8865 	case WRITE_ATOMIC_16: {
8866 		struct scsi_write_atomic_16 *cdb;
8867 
8868 		if (lun->be_lun->atomicblock == 0) {
8869 			ctl_set_invalid_opcode(ctsio);
8870 			ctl_done((union ctl_io *)ctsio);
8871 			return (CTL_RETVAL_COMPLETE);
8872 		}
8873 
8874 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8875 		if (cdb->byte2 & SRW12_FUA)
8876 			flags |= CTL_LLF_FUA;
8877 		if (cdb->byte2 & SRW12_DPO)
8878 			flags |= CTL_LLF_DPO;
8879 		lba = scsi_8btou64(cdb->addr);
8880 		num_blocks = scsi_2btoul(cdb->length);
8881 		if (num_blocks > lun->be_lun->atomicblock) {
8882 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8883 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8884 			    /*bit*/ 0);
8885 			ctl_done((union ctl_io *)ctsio);
8886 			return (CTL_RETVAL_COMPLETE);
8887 		}
8888 		break;
8889 	}
8890 	case WRITE_VERIFY_16: {
8891 		struct scsi_write_verify_16 *cdb;
8892 
8893 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8894 		flags |= CTL_LLF_FUA;
8895 		if (cdb->byte2 & SWV_DPO)
8896 			flags |= CTL_LLF_DPO;
8897 		lba = scsi_8btou64(cdb->addr);
8898 		num_blocks = scsi_4btoul(cdb->length);
8899 		break;
8900 	}
8901 	default:
8902 		/*
8903 		 * We got a command we don't support.  This shouldn't
8904 		 * happen, commands should be filtered out above us.
8905 		 */
8906 		ctl_set_invalid_opcode(ctsio);
8907 		ctl_done((union ctl_io *)ctsio);
8908 
8909 		return (CTL_RETVAL_COMPLETE);
8910 		break; /* NOTREACHED */
8911 	}
8912 
8913 	/*
8914 	 * The first check is to make sure we're in bounds, the second
8915 	 * check is to catch wrap-around problems.  If the lba + num blocks
8916 	 * is less than the lba, then we've wrapped around and the block
8917 	 * range is invalid anyway.
8918 	 */
8919 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8920 	 || ((lba + num_blocks) < lba)) {
8921 		ctl_set_lba_out_of_range(ctsio,
8922 		    MAX(lba, lun->be_lun->maxlba + 1));
8923 		ctl_done((union ctl_io *)ctsio);
8924 		return (CTL_RETVAL_COMPLETE);
8925 	}
8926 
8927 	/*
8928 	 * According to SBC-3, a transfer length of 0 is not an error.
8929 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8930 	 * translates to 256 blocks for those commands.
8931 	 */
8932 	if (num_blocks == 0) {
8933 		ctl_set_success(ctsio);
8934 		ctl_done((union ctl_io *)ctsio);
8935 		return (CTL_RETVAL_COMPLETE);
8936 	}
8937 
8938 	/* Set FUA and/or DPO if caches are disabled. */
8939 	if (isread) {
8940 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8941 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8942 	} else {
8943 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8944 			flags |= CTL_LLF_FUA;
8945 	}
8946 
8947 	lbalen = (struct ctl_lba_len_flags *)
8948 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8949 	lbalen->lba = lba;
8950 	lbalen->len = num_blocks;
8951 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8952 
8953 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8954 	ctsio->kern_rel_offset = 0;
8955 
8956 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8957 
8958 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8959 	return (retval);
8960 }
8961 
8962 static int
8963 ctl_cnw_cont(union ctl_io *io)
8964 {
8965 	struct ctl_lun *lun = CTL_LUN(io);
8966 	struct ctl_scsiio *ctsio;
8967 	struct ctl_lba_len_flags *lbalen;
8968 	int retval;
8969 
8970 	ctsio = &io->scsiio;
8971 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8972 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8973 	lbalen = (struct ctl_lba_len_flags *)
8974 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8975 	lbalen->flags &= ~CTL_LLF_COMPARE;
8976 	lbalen->flags |= CTL_LLF_WRITE;
8977 
8978 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8979 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8980 	return (retval);
8981 }
8982 
8983 int
8984 ctl_cnw(struct ctl_scsiio *ctsio)
8985 {
8986 	struct ctl_lun *lun = CTL_LUN(ctsio);
8987 	struct ctl_lba_len_flags *lbalen;
8988 	uint64_t lba;
8989 	uint32_t num_blocks;
8990 	int flags, retval;
8991 
8992 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8993 
8994 	flags = 0;
8995 	switch (ctsio->cdb[0]) {
8996 	case COMPARE_AND_WRITE: {
8997 		struct scsi_compare_and_write *cdb;
8998 
8999 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9000 		if (cdb->byte2 & SRW10_FUA)
9001 			flags |= CTL_LLF_FUA;
9002 		if (cdb->byte2 & SRW10_DPO)
9003 			flags |= CTL_LLF_DPO;
9004 		lba = scsi_8btou64(cdb->addr);
9005 		num_blocks = cdb->length;
9006 		break;
9007 	}
9008 	default:
9009 		/*
9010 		 * We got a command we don't support.  This shouldn't
9011 		 * happen, commands should be filtered out above us.
9012 		 */
9013 		ctl_set_invalid_opcode(ctsio);
9014 		ctl_done((union ctl_io *)ctsio);
9015 
9016 		return (CTL_RETVAL_COMPLETE);
9017 		break; /* NOTREACHED */
9018 	}
9019 
9020 	/*
9021 	 * The first check is to make sure we're in bounds, the second
9022 	 * check is to catch wrap-around problems.  If the lba + num blocks
9023 	 * is less than the lba, then we've wrapped around and the block
9024 	 * range is invalid anyway.
9025 	 */
9026 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9027 	 || ((lba + num_blocks) < lba)) {
9028 		ctl_set_lba_out_of_range(ctsio,
9029 		    MAX(lba, lun->be_lun->maxlba + 1));
9030 		ctl_done((union ctl_io *)ctsio);
9031 		return (CTL_RETVAL_COMPLETE);
9032 	}
9033 
9034 	/*
9035 	 * According to SBC-3, a transfer length of 0 is not an error.
9036 	 */
9037 	if (num_blocks == 0) {
9038 		ctl_set_success(ctsio);
9039 		ctl_done((union ctl_io *)ctsio);
9040 		return (CTL_RETVAL_COMPLETE);
9041 	}
9042 
9043 	/* Set FUA if write cache is disabled. */
9044 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
9045 		flags |= CTL_LLF_FUA;
9046 
9047 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9048 	ctsio->kern_rel_offset = 0;
9049 
9050 	/*
9051 	 * Set the IO_CONT flag, so that if this I/O gets passed to
9052 	 * ctl_data_submit_done(), it'll get passed back to
9053 	 * ctl_ctl_cnw_cont() for further processing.
9054 	 */
9055 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9056 	ctsio->io_cont = ctl_cnw_cont;
9057 
9058 	lbalen = (struct ctl_lba_len_flags *)
9059 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9060 	lbalen->lba = lba;
9061 	lbalen->len = num_blocks;
9062 	lbalen->flags = CTL_LLF_COMPARE | flags;
9063 
9064 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9065 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9066 	return (retval);
9067 }
9068 
9069 int
9070 ctl_verify(struct ctl_scsiio *ctsio)
9071 {
9072 	struct ctl_lun *lun = CTL_LUN(ctsio);
9073 	struct ctl_lba_len_flags *lbalen;
9074 	uint64_t lba;
9075 	uint32_t num_blocks;
9076 	int bytchk, flags;
9077 	int retval;
9078 
9079 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9080 
9081 	bytchk = 0;
9082 	flags = CTL_LLF_FUA;
9083 	switch (ctsio->cdb[0]) {
9084 	case VERIFY_10: {
9085 		struct scsi_verify_10 *cdb;
9086 
9087 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9088 		if (cdb->byte2 & SVFY_BYTCHK)
9089 			bytchk = 1;
9090 		if (cdb->byte2 & SVFY_DPO)
9091 			flags |= CTL_LLF_DPO;
9092 		lba = scsi_4btoul(cdb->addr);
9093 		num_blocks = scsi_2btoul(cdb->length);
9094 		break;
9095 	}
9096 	case VERIFY_12: {
9097 		struct scsi_verify_12 *cdb;
9098 
9099 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9100 		if (cdb->byte2 & SVFY_BYTCHK)
9101 			bytchk = 1;
9102 		if (cdb->byte2 & SVFY_DPO)
9103 			flags |= CTL_LLF_DPO;
9104 		lba = scsi_4btoul(cdb->addr);
9105 		num_blocks = scsi_4btoul(cdb->length);
9106 		break;
9107 	}
9108 	case VERIFY_16: {
9109 		struct scsi_rw_16 *cdb;
9110 
9111 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9112 		if (cdb->byte2 & SVFY_BYTCHK)
9113 			bytchk = 1;
9114 		if (cdb->byte2 & SVFY_DPO)
9115 			flags |= CTL_LLF_DPO;
9116 		lba = scsi_8btou64(cdb->addr);
9117 		num_blocks = scsi_4btoul(cdb->length);
9118 		break;
9119 	}
9120 	default:
9121 		/*
9122 		 * We got a command we don't support.  This shouldn't
9123 		 * happen, commands should be filtered out above us.
9124 		 */
9125 		ctl_set_invalid_opcode(ctsio);
9126 		ctl_done((union ctl_io *)ctsio);
9127 		return (CTL_RETVAL_COMPLETE);
9128 	}
9129 
9130 	/*
9131 	 * The first check is to make sure we're in bounds, the second
9132 	 * check is to catch wrap-around problems.  If the lba + num blocks
9133 	 * is less than the lba, then we've wrapped around and the block
9134 	 * range is invalid anyway.
9135 	 */
9136 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9137 	 || ((lba + num_blocks) < lba)) {
9138 		ctl_set_lba_out_of_range(ctsio,
9139 		    MAX(lba, lun->be_lun->maxlba + 1));
9140 		ctl_done((union ctl_io *)ctsio);
9141 		return (CTL_RETVAL_COMPLETE);
9142 	}
9143 
9144 	/*
9145 	 * According to SBC-3, a transfer length of 0 is not an error.
9146 	 */
9147 	if (num_blocks == 0) {
9148 		ctl_set_success(ctsio);
9149 		ctl_done((union ctl_io *)ctsio);
9150 		return (CTL_RETVAL_COMPLETE);
9151 	}
9152 
9153 	lbalen = (struct ctl_lba_len_flags *)
9154 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9155 	lbalen->lba = lba;
9156 	lbalen->len = num_blocks;
9157 	if (bytchk) {
9158 		lbalen->flags = CTL_LLF_COMPARE | flags;
9159 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9160 	} else {
9161 		lbalen->flags = CTL_LLF_VERIFY | flags;
9162 		ctsio->kern_total_len = 0;
9163 	}
9164 	ctsio->kern_rel_offset = 0;
9165 
9166 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9167 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9168 	return (retval);
9169 }
9170 
9171 int
9172 ctl_report_luns(struct ctl_scsiio *ctsio)
9173 {
9174 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9175 	struct ctl_port *port = CTL_PORT(ctsio);
9176 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9177 	struct scsi_report_luns *cdb;
9178 	struct scsi_report_luns_data *lun_data;
9179 	int num_filled, num_luns, num_port_luns, retval;
9180 	uint32_t alloc_len, lun_datalen;
9181 	uint32_t initidx, targ_lun_id, lun_id;
9182 
9183 	retval = CTL_RETVAL_COMPLETE;
9184 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9185 
9186 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9187 
9188 	num_luns = 0;
9189 	num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
9190 	mtx_lock(&softc->ctl_lock);
9191 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9192 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9193 			num_luns++;
9194 	}
9195 	mtx_unlock(&softc->ctl_lock);
9196 
9197 	switch (cdb->select_report) {
9198 	case RPL_REPORT_DEFAULT:
9199 	case RPL_REPORT_ALL:
9200 	case RPL_REPORT_NONSUBSID:
9201 		break;
9202 	case RPL_REPORT_WELLKNOWN:
9203 	case RPL_REPORT_ADMIN:
9204 	case RPL_REPORT_CONGLOM:
9205 		num_luns = 0;
9206 		break;
9207 	default:
9208 		ctl_set_invalid_field(ctsio,
9209 				      /*sks_valid*/ 1,
9210 				      /*command*/ 1,
9211 				      /*field*/ 2,
9212 				      /*bit_valid*/ 0,
9213 				      /*bit*/ 0);
9214 		ctl_done((union ctl_io *)ctsio);
9215 		return (retval);
9216 		break; /* NOTREACHED */
9217 	}
9218 
9219 	alloc_len = scsi_4btoul(cdb->length);
9220 	/*
9221 	 * The initiator has to allocate at least 16 bytes for this request,
9222 	 * so he can at least get the header and the first LUN.  Otherwise
9223 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9224 	 */
9225 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9226 	    sizeof(struct scsi_report_luns_lundata))) {
9227 		ctl_set_invalid_field(ctsio,
9228 				      /*sks_valid*/ 1,
9229 				      /*command*/ 1,
9230 				      /*field*/ 6,
9231 				      /*bit_valid*/ 0,
9232 				      /*bit*/ 0);
9233 		ctl_done((union ctl_io *)ctsio);
9234 		return (retval);
9235 	}
9236 
9237 	lun_datalen = sizeof(*lun_data) +
9238 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9239 
9240 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9241 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9242 	ctsio->kern_sg_entries = 0;
9243 
9244 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9245 
9246 	mtx_lock(&softc->ctl_lock);
9247 	for (targ_lun_id = 0, num_filled = 0;
9248 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9249 	    targ_lun_id++) {
9250 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9251 		if (lun_id == UINT32_MAX)
9252 			continue;
9253 		lun = softc->ctl_luns[lun_id];
9254 		if (lun == NULL)
9255 			continue;
9256 
9257 		be64enc(lun_data->luns[num_filled++].lundata,
9258 		    ctl_encode_lun(targ_lun_id));
9259 
9260 		/*
9261 		 * According to SPC-3, rev 14 section 6.21:
9262 		 *
9263 		 * "The execution of a REPORT LUNS command to any valid and
9264 		 * installed logical unit shall clear the REPORTED LUNS DATA
9265 		 * HAS CHANGED unit attention condition for all logical
9266 		 * units of that target with respect to the requesting
9267 		 * initiator. A valid and installed logical unit is one
9268 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9269 		 * INQUIRY data (see 6.4.2)."
9270 		 *
9271 		 * If request_lun is NULL, the LUN this report luns command
9272 		 * was issued to is either disabled or doesn't exist. In that
9273 		 * case, we shouldn't clear any pending lun change unit
9274 		 * attention.
9275 		 */
9276 		if (request_lun != NULL) {
9277 			mtx_lock(&lun->lun_lock);
9278 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9279 			mtx_unlock(&lun->lun_lock);
9280 		}
9281 	}
9282 	mtx_unlock(&softc->ctl_lock);
9283 
9284 	/*
9285 	 * It's quite possible that we've returned fewer LUNs than we allocated
9286 	 * space for.  Trim it.
9287 	 */
9288 	lun_datalen = sizeof(*lun_data) +
9289 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9290 	ctsio->kern_rel_offset = 0;
9291 	ctsio->kern_sg_entries = 0;
9292 	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9293 	ctsio->kern_total_len = ctsio->kern_data_len;
9294 
9295 	/*
9296 	 * We set this to the actual data length, regardless of how much
9297 	 * space we actually have to return results.  If the user looks at
9298 	 * this value, he'll know whether or not he allocated enough space
9299 	 * and reissue the command if necessary.  We don't support well
9300 	 * known logical units, so if the user asks for that, return none.
9301 	 */
9302 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9303 
9304 	/*
9305 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9306 	 * this request.
9307 	 */
9308 	ctl_set_success(ctsio);
9309 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9310 	ctsio->be_move_done = ctl_config_move_done;
9311 	ctl_datamove((union ctl_io *)ctsio);
9312 	return (retval);
9313 }
9314 
9315 int
9316 ctl_request_sense(struct ctl_scsiio *ctsio)
9317 {
9318 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9319 	struct ctl_lun *lun = CTL_LUN(ctsio);
9320 	struct scsi_request_sense *cdb;
9321 	struct scsi_sense_data *sense_ptr, *ps;
9322 	uint32_t initidx;
9323 	int have_error;
9324 	u_int sense_len = SSD_FULL_SIZE;
9325 	scsi_sense_data_type sense_format;
9326 	ctl_ua_type ua_type;
9327 	uint8_t asc = 0, ascq = 0;
9328 
9329 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9330 
9331 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9332 
9333 	/*
9334 	 * Determine which sense format the user wants.
9335 	 */
9336 	if (cdb->byte2 & SRS_DESC)
9337 		sense_format = SSD_TYPE_DESC;
9338 	else
9339 		sense_format = SSD_TYPE_FIXED;
9340 
9341 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9342 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9343 	ctsio->kern_sg_entries = 0;
9344 	ctsio->kern_rel_offset = 0;
9345 	ctsio->kern_data_len = ctsio->kern_total_len =
9346 	    MIN(cdb->length, sizeof(*sense_ptr));
9347 
9348 	/*
9349 	 * If we don't have a LUN, we don't have any pending sense.
9350 	 */
9351 	if (lun == NULL ||
9352 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9353 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9354 		/* "Logical unit not supported" */
9355 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9356 		    /*current_error*/ 1,
9357 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9358 		    /*asc*/ 0x25,
9359 		    /*ascq*/ 0x00,
9360 		    SSD_ELEM_NONE);
9361 		goto send;
9362 	}
9363 
9364 	have_error = 0;
9365 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9366 	/*
9367 	 * Check for pending sense, and then for pending unit attentions.
9368 	 * Pending sense gets returned first, then pending unit attentions.
9369 	 */
9370 	mtx_lock(&lun->lun_lock);
9371 	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9372 	if (ps != NULL)
9373 		ps += initidx % CTL_MAX_INIT_PER_PORT;
9374 	if (ps != NULL && ps->error_code != 0) {
9375 		scsi_sense_data_type stored_format;
9376 
9377 		/*
9378 		 * Check to see which sense format was used for the stored
9379 		 * sense data.
9380 		 */
9381 		stored_format = scsi_sense_type(ps);
9382 
9383 		/*
9384 		 * If the user requested a different sense format than the
9385 		 * one we stored, then we need to convert it to the other
9386 		 * format.  If we're going from descriptor to fixed format
9387 		 * sense data, we may lose things in translation, depending
9388 		 * on what options were used.
9389 		 *
9390 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9391 		 * for some reason we'll just copy it out as-is.
9392 		 */
9393 		if ((stored_format == SSD_TYPE_FIXED)
9394 		 && (sense_format == SSD_TYPE_DESC))
9395 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9396 			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9397 		else if ((stored_format == SSD_TYPE_DESC)
9398 		      && (sense_format == SSD_TYPE_FIXED))
9399 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9400 			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9401 		else
9402 			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9403 
9404 		ps->error_code = 0;
9405 		have_error = 1;
9406 	} else {
9407 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9408 		    sense_format);
9409 		if (ua_type != CTL_UA_NONE)
9410 			have_error = 1;
9411 	}
9412 	if (have_error == 0) {
9413 		/*
9414 		 * Report informational exception if have one and allowed.
9415 		 */
9416 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9417 			asc = lun->ie_asc;
9418 			ascq = lun->ie_ascq;
9419 		}
9420 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9421 		    /*current_error*/ 1,
9422 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9423 		    /*asc*/ asc,
9424 		    /*ascq*/ ascq,
9425 		    SSD_ELEM_NONE);
9426 	}
9427 	mtx_unlock(&lun->lun_lock);
9428 
9429 send:
9430 	/*
9431 	 * We report the SCSI status as OK, since the status of the command
9432 	 * itself is OK.  We're reporting sense as parameter data.
9433 	 */
9434 	ctl_set_success(ctsio);
9435 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9436 	ctsio->be_move_done = ctl_config_move_done;
9437 	ctl_datamove((union ctl_io *)ctsio);
9438 	return (CTL_RETVAL_COMPLETE);
9439 }
9440 
9441 int
9442 ctl_tur(struct ctl_scsiio *ctsio)
9443 {
9444 
9445 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9446 
9447 	ctl_set_success(ctsio);
9448 	ctl_done((union ctl_io *)ctsio);
9449 
9450 	return (CTL_RETVAL_COMPLETE);
9451 }
9452 
9453 /*
9454  * SCSI VPD page 0x00, the Supported VPD Pages page.
9455  */
9456 static int
9457 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9458 {
9459 	struct ctl_lun *lun = CTL_LUN(ctsio);
9460 	struct scsi_vpd_supported_pages *pages;
9461 	int sup_page_size;
9462 	int p;
9463 
9464 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9465 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9466 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9467 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9468 	ctsio->kern_rel_offset = 0;
9469 	ctsio->kern_sg_entries = 0;
9470 	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9471 	ctsio->kern_total_len = ctsio->kern_data_len;
9472 
9473 	/*
9474 	 * The control device is always connected.  The disk device, on the
9475 	 * other hand, may not be online all the time.  Need to change this
9476 	 * to figure out whether the disk device is actually online or not.
9477 	 */
9478 	if (lun != NULL)
9479 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9480 				lun->be_lun->lun_type;
9481 	else
9482 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9483 
9484 	p = 0;
9485 	/* Supported VPD pages */
9486 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9487 	/* Serial Number */
9488 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9489 	/* Device Identification */
9490 	pages->page_list[p++] = SVPD_DEVICE_ID;
9491 	/* Extended INQUIRY Data */
9492 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9493 	/* Mode Page Policy */
9494 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9495 	/* SCSI Ports */
9496 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9497 	/* Third-party Copy */
9498 	pages->page_list[p++] = SVPD_SCSI_TPC;
9499 	/* SCSI Feature Sets */
9500 	pages->page_list[p++] = SVPD_SCSI_SFS;
9501 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9502 		/* Block limits */
9503 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9504 		/* Block Device Characteristics */
9505 		pages->page_list[p++] = SVPD_BDC;
9506 		/* Logical Block Provisioning */
9507 		pages->page_list[p++] = SVPD_LBP;
9508 	}
9509 	pages->length = p;
9510 
9511 	ctl_set_success(ctsio);
9512 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9513 	ctsio->be_move_done = ctl_config_move_done;
9514 	ctl_datamove((union ctl_io *)ctsio);
9515 	return (CTL_RETVAL_COMPLETE);
9516 }
9517 
9518 /*
9519  * SCSI VPD page 0x80, the Unit Serial Number page.
9520  */
9521 static int
9522 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9523 {
9524 	struct ctl_lun *lun = CTL_LUN(ctsio);
9525 	struct scsi_vpd_unit_serial_number *sn_ptr;
9526 	int data_len;
9527 
9528 	data_len = 4 + CTL_SN_LEN;
9529 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9530 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9531 	ctsio->kern_rel_offset = 0;
9532 	ctsio->kern_sg_entries = 0;
9533 	ctsio->kern_data_len = min(data_len, alloc_len);
9534 	ctsio->kern_total_len = ctsio->kern_data_len;
9535 
9536 	/*
9537 	 * The control device is always connected.  The disk device, on the
9538 	 * other hand, may not be online all the time.  Need to change this
9539 	 * to figure out whether the disk device is actually online or not.
9540 	 */
9541 	if (lun != NULL)
9542 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9543 				  lun->be_lun->lun_type;
9544 	else
9545 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9546 
9547 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9548 	sn_ptr->length = CTL_SN_LEN;
9549 	/*
9550 	 * If we don't have a LUN, we just leave the serial number as
9551 	 * all spaces.
9552 	 */
9553 	if (lun != NULL) {
9554 		strncpy((char *)sn_ptr->serial_num,
9555 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9556 	} else
9557 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9558 
9559 	ctl_set_success(ctsio);
9560 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9561 	ctsio->be_move_done = ctl_config_move_done;
9562 	ctl_datamove((union ctl_io *)ctsio);
9563 	return (CTL_RETVAL_COMPLETE);
9564 }
9565 
9566 /*
9567  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9568  */
9569 static int
9570 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9571 {
9572 	struct ctl_lun *lun = CTL_LUN(ctsio);
9573 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9574 	int data_len;
9575 
9576 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9577 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9578 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9579 	ctsio->kern_sg_entries = 0;
9580 	ctsio->kern_rel_offset = 0;
9581 	ctsio->kern_data_len = min(data_len, alloc_len);
9582 	ctsio->kern_total_len = ctsio->kern_data_len;
9583 
9584 	/*
9585 	 * The control device is always connected.  The disk device, on the
9586 	 * other hand, may not be online all the time.
9587 	 */
9588 	if (lun != NULL)
9589 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9590 				     lun->be_lun->lun_type;
9591 	else
9592 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9593 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9594 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9595 	/*
9596 	 * We support head of queue, ordered and simple tags.
9597 	 */
9598 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9599 	/*
9600 	 * Volatile cache supported.
9601 	 */
9602 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9603 
9604 	/*
9605 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9606 	 * attention for a particular IT nexus on all LUNs once we report
9607 	 * it to that nexus once.  This bit is required as of SPC-4.
9608 	 */
9609 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9610 
9611 	/*
9612 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9613 	 */
9614 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9615 
9616 	/*
9617 	 * XXX KDM in order to correctly answer this, we would need
9618 	 * information from the SIM to determine how much sense data it
9619 	 * can send.  So this would really be a path inquiry field, most
9620 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9621 	 * but the hardware may or may not be able to support that much.
9622 	 * 0 just means that the maximum sense data length is not reported.
9623 	 */
9624 	eid_ptr->max_sense_length = 0;
9625 
9626 	ctl_set_success(ctsio);
9627 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9628 	ctsio->be_move_done = ctl_config_move_done;
9629 	ctl_datamove((union ctl_io *)ctsio);
9630 	return (CTL_RETVAL_COMPLETE);
9631 }
9632 
9633 static int
9634 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9635 {
9636 	struct ctl_lun *lun = CTL_LUN(ctsio);
9637 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9638 	int data_len;
9639 
9640 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9641 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9642 
9643 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9644 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9645 	ctsio->kern_rel_offset = 0;
9646 	ctsio->kern_sg_entries = 0;
9647 	ctsio->kern_data_len = min(data_len, alloc_len);
9648 	ctsio->kern_total_len = ctsio->kern_data_len;
9649 
9650 	/*
9651 	 * The control device is always connected.  The disk device, on the
9652 	 * other hand, may not be online all the time.
9653 	 */
9654 	if (lun != NULL)
9655 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9656 				     lun->be_lun->lun_type;
9657 	else
9658 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9659 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9660 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9661 	mpp_ptr->descr[0].page_code = 0x3f;
9662 	mpp_ptr->descr[0].subpage_code = 0xff;
9663 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9664 
9665 	ctl_set_success(ctsio);
9666 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9667 	ctsio->be_move_done = ctl_config_move_done;
9668 	ctl_datamove((union ctl_io *)ctsio);
9669 	return (CTL_RETVAL_COMPLETE);
9670 }
9671 
9672 /*
9673  * SCSI VPD page 0x83, the Device Identification page.
9674  */
9675 static int
9676 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9677 {
9678 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9679 	struct ctl_port *port = CTL_PORT(ctsio);
9680 	struct ctl_lun *lun = CTL_LUN(ctsio);
9681 	struct scsi_vpd_device_id *devid_ptr;
9682 	struct scsi_vpd_id_descriptor *desc;
9683 	int data_len, g;
9684 	uint8_t proto;
9685 
9686 	data_len = sizeof(struct scsi_vpd_device_id) +
9687 	    sizeof(struct scsi_vpd_id_descriptor) +
9688 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9689 	    sizeof(struct scsi_vpd_id_descriptor) +
9690 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9691 	if (lun && lun->lun_devid)
9692 		data_len += lun->lun_devid->len;
9693 	if (port && port->port_devid)
9694 		data_len += port->port_devid->len;
9695 	if (port && port->target_devid)
9696 		data_len += port->target_devid->len;
9697 
9698 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9699 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9700 	ctsio->kern_sg_entries = 0;
9701 	ctsio->kern_rel_offset = 0;
9702 	ctsio->kern_sg_entries = 0;
9703 	ctsio->kern_data_len = min(data_len, alloc_len);
9704 	ctsio->kern_total_len = ctsio->kern_data_len;
9705 
9706 	/*
9707 	 * The control device is always connected.  The disk device, on the
9708 	 * other hand, may not be online all the time.
9709 	 */
9710 	if (lun != NULL)
9711 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9712 				     lun->be_lun->lun_type;
9713 	else
9714 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9715 	devid_ptr->page_code = SVPD_DEVICE_ID;
9716 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9717 
9718 	if (port && port->port_type == CTL_PORT_FC)
9719 		proto = SCSI_PROTO_FC << 4;
9720 	else if (port && port->port_type == CTL_PORT_SAS)
9721 		proto = SCSI_PROTO_SAS << 4;
9722 	else if (port && port->port_type == CTL_PORT_ISCSI)
9723 		proto = SCSI_PROTO_ISCSI << 4;
9724 	else
9725 		proto = SCSI_PROTO_SPI << 4;
9726 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9727 
9728 	/*
9729 	 * We're using a LUN association here.  i.e., this device ID is a
9730 	 * per-LUN identifier.
9731 	 */
9732 	if (lun && lun->lun_devid) {
9733 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9734 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9735 		    lun->lun_devid->len);
9736 	}
9737 
9738 	/*
9739 	 * This is for the WWPN which is a port association.
9740 	 */
9741 	if (port && port->port_devid) {
9742 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9743 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9744 		    port->port_devid->len);
9745 	}
9746 
9747 	/*
9748 	 * This is for the Relative Target Port(type 4h) identifier
9749 	 */
9750 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9751 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9752 	    SVPD_ID_TYPE_RELTARG;
9753 	desc->length = 4;
9754 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9755 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9756 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9757 
9758 	/*
9759 	 * This is for the Target Port Group(type 5h) identifier
9760 	 */
9761 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9762 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9763 	    SVPD_ID_TYPE_TPORTGRP;
9764 	desc->length = 4;
9765 	if (softc->is_single ||
9766 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9767 		g = 1;
9768 	else
9769 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9770 	scsi_ulto2b(g, &desc->identifier[2]);
9771 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9772 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9773 
9774 	/*
9775 	 * This is for the Target identifier
9776 	 */
9777 	if (port && port->target_devid) {
9778 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9779 	}
9780 
9781 	ctl_set_success(ctsio);
9782 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9783 	ctsio->be_move_done = ctl_config_move_done;
9784 	ctl_datamove((union ctl_io *)ctsio);
9785 	return (CTL_RETVAL_COMPLETE);
9786 }
9787 
9788 static int
9789 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9790 {
9791 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9792 	struct ctl_lun *lun = CTL_LUN(ctsio);
9793 	struct scsi_vpd_scsi_ports *sp;
9794 	struct scsi_vpd_port_designation *pd;
9795 	struct scsi_vpd_port_designation_cont *pdc;
9796 	struct ctl_port *port;
9797 	int data_len, num_target_ports, iid_len, id_len;
9798 
9799 	num_target_ports = 0;
9800 	iid_len = 0;
9801 	id_len = 0;
9802 	mtx_lock(&softc->ctl_lock);
9803 	STAILQ_FOREACH(port, &softc->port_list, links) {
9804 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9805 			continue;
9806 		if (lun != NULL &&
9807 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9808 			continue;
9809 		num_target_ports++;
9810 		if (port->init_devid)
9811 			iid_len += port->init_devid->len;
9812 		if (port->port_devid)
9813 			id_len += port->port_devid->len;
9814 	}
9815 	mtx_unlock(&softc->ctl_lock);
9816 
9817 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9818 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9819 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9820 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9821 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9822 	ctsio->kern_sg_entries = 0;
9823 	ctsio->kern_rel_offset = 0;
9824 	ctsio->kern_sg_entries = 0;
9825 	ctsio->kern_data_len = min(data_len, alloc_len);
9826 	ctsio->kern_total_len = ctsio->kern_data_len;
9827 
9828 	/*
9829 	 * The control device is always connected.  The disk device, on the
9830 	 * other hand, may not be online all the time.  Need to change this
9831 	 * to figure out whether the disk device is actually online or not.
9832 	 */
9833 	if (lun != NULL)
9834 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9835 				  lun->be_lun->lun_type;
9836 	else
9837 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9838 
9839 	sp->page_code = SVPD_SCSI_PORTS;
9840 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9841 	    sp->page_length);
9842 	pd = &sp->design[0];
9843 
9844 	mtx_lock(&softc->ctl_lock);
9845 	STAILQ_FOREACH(port, &softc->port_list, links) {
9846 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9847 			continue;
9848 		if (lun != NULL &&
9849 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9850 			continue;
9851 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9852 		if (port->init_devid) {
9853 			iid_len = port->init_devid->len;
9854 			memcpy(pd->initiator_transportid,
9855 			    port->init_devid->data, port->init_devid->len);
9856 		} else
9857 			iid_len = 0;
9858 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9859 		pdc = (struct scsi_vpd_port_designation_cont *)
9860 		    (&pd->initiator_transportid[iid_len]);
9861 		if (port->port_devid) {
9862 			id_len = port->port_devid->len;
9863 			memcpy(pdc->target_port_descriptors,
9864 			    port->port_devid->data, port->port_devid->len);
9865 		} else
9866 			id_len = 0;
9867 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9868 		pd = (struct scsi_vpd_port_designation *)
9869 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9870 	}
9871 	mtx_unlock(&softc->ctl_lock);
9872 
9873 	ctl_set_success(ctsio);
9874 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9875 	ctsio->be_move_done = ctl_config_move_done;
9876 	ctl_datamove((union ctl_io *)ctsio);
9877 	return (CTL_RETVAL_COMPLETE);
9878 }
9879 
9880 static int
9881 ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len)
9882 {
9883 	struct ctl_lun *lun = CTL_LUN(ctsio);
9884 	struct scsi_vpd_sfs *sfs_ptr;
9885 	int sfs_page_size, n;
9886 
9887 	sfs_page_size = sizeof(*sfs_ptr) + 5 * 2;
9888 	ctsio->kern_data_ptr = malloc(sfs_page_size, M_CTL, M_WAITOK | M_ZERO);
9889 	sfs_ptr = (struct scsi_vpd_sfs *)ctsio->kern_data_ptr;
9890 	ctsio->kern_sg_entries = 0;
9891 	ctsio->kern_rel_offset = 0;
9892 	ctsio->kern_sg_entries = 0;
9893 	ctsio->kern_data_len = min(sfs_page_size, alloc_len);
9894 	ctsio->kern_total_len = ctsio->kern_data_len;
9895 
9896 	/*
9897 	 * The control device is always connected.  The disk device, on the
9898 	 * other hand, may not be online all the time.  Need to change this
9899 	 * to figure out whether the disk device is actually online or not.
9900 	 */
9901 	if (lun != NULL)
9902 		sfs_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9903 				  lun->be_lun->lun_type;
9904 	else
9905 		sfs_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9906 
9907 	sfs_ptr->page_code = SVPD_SCSI_SFS;
9908 	n = 0;
9909 	/* Discovery 2016 */
9910 	scsi_ulto2b(0x0001, &sfs_ptr->codes[2 * n++]);
9911 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9912 		 /* SBC Base 2016 */
9913 		scsi_ulto2b(0x0101, &sfs_ptr->codes[2 * n++]);
9914 		 /* SBC Base 2010 */
9915 		scsi_ulto2b(0x0102, &sfs_ptr->codes[2 * n++]);
9916 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9917 			/* Basic Provisioning 2016 */
9918 			scsi_ulto2b(0x0103, &sfs_ptr->codes[2 * n++]);
9919 		}
9920 		/* Drive Maintenance 2016 */
9921 		//scsi_ulto2b(0x0104, &sfs_ptr->codes[2 * n++]);
9922 	}
9923 	scsi_ulto2b(4 + 2 * n, sfs_ptr->page_length);
9924 
9925 	ctl_set_success(ctsio);
9926 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9927 	ctsio->be_move_done = ctl_config_move_done;
9928 	ctl_datamove((union ctl_io *)ctsio);
9929 	return (CTL_RETVAL_COMPLETE);
9930 }
9931 
9932 static int
9933 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9934 {
9935 	struct ctl_lun *lun = CTL_LUN(ctsio);
9936 	struct scsi_vpd_block_limits *bl_ptr;
9937 	const char *val;
9938 	uint64_t ival;
9939 
9940 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9941 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9942 	ctsio->kern_sg_entries = 0;
9943 	ctsio->kern_rel_offset = 0;
9944 	ctsio->kern_sg_entries = 0;
9945 	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9946 	ctsio->kern_total_len = ctsio->kern_data_len;
9947 
9948 	/*
9949 	 * The control device is always connected.  The disk device, on the
9950 	 * other hand, may not be online all the time.  Need to change this
9951 	 * to figure out whether the disk device is actually online or not.
9952 	 */
9953 	if (lun != NULL)
9954 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9955 				  lun->be_lun->lun_type;
9956 	else
9957 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9958 
9959 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9960 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9961 	bl_ptr->max_cmp_write_len = 0xff;
9962 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9963 	if (lun != NULL) {
9964 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9965 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9966 			ival = 0xffffffff;
9967 			val = dnvlist_get_string(lun->be_lun->options,
9968 			    "unmap_max_lba", NULL);
9969 			if (val != NULL)
9970 				ctl_expand_number(val, &ival);
9971 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9972 			ival = 0xffffffff;
9973 			val = dnvlist_get_string(lun->be_lun->options,
9974 			    "unmap_max_descr", NULL);
9975 			if (val != NULL)
9976 				ctl_expand_number(val, &ival);
9977 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9978 			if (lun->be_lun->ublockexp != 0) {
9979 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9980 				    bl_ptr->opt_unmap_grain);
9981 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9982 				    bl_ptr->unmap_grain_align);
9983 			}
9984 		}
9985 		scsi_ulto4b(lun->be_lun->atomicblock,
9986 		    bl_ptr->max_atomic_transfer_length);
9987 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9988 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9989 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9990 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9991 		ival = UINT64_MAX;
9992 		val = dnvlist_get_string(lun->be_lun->options,
9993 		    "write_same_max_lba", NULL);
9994 		if (val != NULL)
9995 			ctl_expand_number(val, &ival);
9996 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9997 		if (lun->be_lun->maxlba + 1 > ival)
9998 			bl_ptr->flags |= SVPD_BL_WSNZ;
9999 	}
10000 
10001 	ctl_set_success(ctsio);
10002 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10003 	ctsio->be_move_done = ctl_config_move_done;
10004 	ctl_datamove((union ctl_io *)ctsio);
10005 	return (CTL_RETVAL_COMPLETE);
10006 }
10007 
10008 static int
10009 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10010 {
10011 	struct ctl_lun *lun = CTL_LUN(ctsio);
10012 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10013 	const char *value;
10014 	u_int i;
10015 
10016 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10017 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10018 	ctsio->kern_sg_entries = 0;
10019 	ctsio->kern_rel_offset = 0;
10020 	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
10021 	ctsio->kern_total_len = ctsio->kern_data_len;
10022 
10023 	/*
10024 	 * The control device is always connected.  The disk device, on the
10025 	 * other hand, may not be online all the time.  Need to change this
10026 	 * to figure out whether the disk device is actually online or not.
10027 	 */
10028 	if (lun != NULL)
10029 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10030 				  lun->be_lun->lun_type;
10031 	else
10032 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10033 	bdc_ptr->page_code = SVPD_BDC;
10034 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10035 	if (lun != NULL &&
10036 	    (value = dnvlist_get_string(lun->be_lun->options, "rpm", NULL)) != NULL)
10037 		i = strtol(value, NULL, 0);
10038 	else
10039 		i = CTL_DEFAULT_ROTATION_RATE;
10040 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10041 	if (lun != NULL &&
10042 	    (value = dnvlist_get_string(lun->be_lun->options, "formfactor", NULL)) != NULL)
10043 		i = strtol(value, NULL, 0);
10044 	else
10045 		i = 0;
10046 	bdc_ptr->wab_wac_ff = (i & 0x0f);
10047 	bdc_ptr->flags = SVPD_RBWZ | SVPD_FUAB | SVPD_VBULS;
10048 
10049 	ctl_set_success(ctsio);
10050 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10051 	ctsio->be_move_done = ctl_config_move_done;
10052 	ctl_datamove((union ctl_io *)ctsio);
10053 	return (CTL_RETVAL_COMPLETE);
10054 }
10055 
10056 static int
10057 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10058 {
10059 	struct ctl_lun *lun = CTL_LUN(ctsio);
10060 	struct scsi_vpd_logical_block_prov *lbp_ptr;
10061 	const char *value;
10062 
10063 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10064 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10065 	ctsio->kern_sg_entries = 0;
10066 	ctsio->kern_rel_offset = 0;
10067 	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
10068 	ctsio->kern_total_len = ctsio->kern_data_len;
10069 
10070 	/*
10071 	 * The control device is always connected.  The disk device, on the
10072 	 * other hand, may not be online all the time.  Need to change this
10073 	 * to figure out whether the disk device is actually online or not.
10074 	 */
10075 	if (lun != NULL)
10076 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10077 				  lun->be_lun->lun_type;
10078 	else
10079 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10080 
10081 	lbp_ptr->page_code = SVPD_LBP;
10082 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10083 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10084 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10085 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10086 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10087 		value = dnvlist_get_string(lun->be_lun->options,
10088 		    "provisioning_type", NULL);
10089 		if (value != NULL) {
10090 			if (strcmp(value, "resource") == 0)
10091 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10092 			else if (strcmp(value, "thin") == 0)
10093 				lbp_ptr->prov_type = SVPD_LBP_THIN;
10094 		} else
10095 			lbp_ptr->prov_type = SVPD_LBP_THIN;
10096 	}
10097 
10098 	ctl_set_success(ctsio);
10099 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10100 	ctsio->be_move_done = ctl_config_move_done;
10101 	ctl_datamove((union ctl_io *)ctsio);
10102 	return (CTL_RETVAL_COMPLETE);
10103 }
10104 
10105 /*
10106  * INQUIRY with the EVPD bit set.
10107  */
10108 static int
10109 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10110 {
10111 	struct ctl_lun *lun = CTL_LUN(ctsio);
10112 	struct scsi_inquiry *cdb;
10113 	int alloc_len, retval;
10114 
10115 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10116 	alloc_len = scsi_2btoul(cdb->length);
10117 
10118 	switch (cdb->page_code) {
10119 	case SVPD_SUPPORTED_PAGES:
10120 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10121 		break;
10122 	case SVPD_UNIT_SERIAL_NUMBER:
10123 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10124 		break;
10125 	case SVPD_DEVICE_ID:
10126 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10127 		break;
10128 	case SVPD_EXTENDED_INQUIRY_DATA:
10129 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10130 		break;
10131 	case SVPD_MODE_PAGE_POLICY:
10132 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10133 		break;
10134 	case SVPD_SCSI_PORTS:
10135 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10136 		break;
10137 	case SVPD_SCSI_TPC:
10138 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10139 		break;
10140 	case SVPD_SCSI_SFS:
10141 		retval = ctl_inquiry_evpd_sfs(ctsio, alloc_len);
10142 		break;
10143 	case SVPD_BLOCK_LIMITS:
10144 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10145 			goto err;
10146 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10147 		break;
10148 	case SVPD_BDC:
10149 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10150 			goto err;
10151 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10152 		break;
10153 	case SVPD_LBP:
10154 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10155 			goto err;
10156 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10157 		break;
10158 	default:
10159 err:
10160 		ctl_set_invalid_field(ctsio,
10161 				      /*sks_valid*/ 1,
10162 				      /*command*/ 1,
10163 				      /*field*/ 2,
10164 				      /*bit_valid*/ 0,
10165 				      /*bit*/ 0);
10166 		ctl_done((union ctl_io *)ctsio);
10167 		retval = CTL_RETVAL_COMPLETE;
10168 		break;
10169 	}
10170 
10171 	return (retval);
10172 }
10173 
10174 /*
10175  * Standard INQUIRY data.
10176  */
10177 static int
10178 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10179 {
10180 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
10181 	struct ctl_port *port = CTL_PORT(ctsio);
10182 	struct ctl_lun *lun = CTL_LUN(ctsio);
10183 	struct scsi_inquiry_data *inq_ptr;
10184 	struct scsi_inquiry *cdb;
10185 	const char *val;
10186 	uint32_t alloc_len, data_len;
10187 	ctl_port_type port_type;
10188 
10189 	port_type = port->port_type;
10190 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10191 		port_type = CTL_PORT_SCSI;
10192 
10193 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10194 	alloc_len = scsi_2btoul(cdb->length);
10195 
10196 	/*
10197 	 * We malloc the full inquiry data size here and fill it
10198 	 * in.  If the user only asks for less, we'll give him
10199 	 * that much.
10200 	 */
10201 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10202 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10203 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10204 	ctsio->kern_sg_entries = 0;
10205 	ctsio->kern_rel_offset = 0;
10206 	ctsio->kern_data_len = min(data_len, alloc_len);
10207 	ctsio->kern_total_len = ctsio->kern_data_len;
10208 
10209 	if (lun != NULL) {
10210 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10211 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10212 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10213 			    lun->be_lun->lun_type;
10214 		} else {
10215 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10216 			    lun->be_lun->lun_type;
10217 		}
10218 		if (lun->flags & CTL_LUN_REMOVABLE)
10219 			inq_ptr->dev_qual2 |= SID_RMB;
10220 	} else
10221 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10222 
10223 	/* RMB in byte 2 is 0 */
10224 	inq_ptr->version = SCSI_REV_SPC5;
10225 
10226 	/*
10227 	 * According to SAM-3, even if a device only supports a single
10228 	 * level of LUN addressing, it should still set the HISUP bit:
10229 	 *
10230 	 * 4.9.1 Logical unit numbers overview
10231 	 *
10232 	 * All logical unit number formats described in this standard are
10233 	 * hierarchical in structure even when only a single level in that
10234 	 * hierarchy is used. The HISUP bit shall be set to one in the
10235 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10236 	 * format described in this standard is used.  Non-hierarchical
10237 	 * formats are outside the scope of this standard.
10238 	 *
10239 	 * Therefore we set the HiSup bit here.
10240 	 *
10241 	 * The response format is 2, per SPC-3.
10242 	 */
10243 	inq_ptr->response_format = SID_HiSup | 2;
10244 
10245 	inq_ptr->additional_length = data_len -
10246 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10247 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10248 			 inq_ptr->additional_length));
10249 
10250 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10251 	if (port_type == CTL_PORT_SCSI)
10252 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10253 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10254 	inq_ptr->flags = SID_CmdQue;
10255 	if (port_type == CTL_PORT_SCSI)
10256 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10257 
10258 	/*
10259 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10260 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10261 	 * name and 4 bytes for the revision.
10262 	 */
10263 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10264 	    "vendor", NULL)) == NULL) {
10265 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10266 	} else {
10267 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10268 		strncpy(inq_ptr->vendor, val,
10269 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10270 	}
10271 	if (lun == NULL) {
10272 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10273 		    sizeof(inq_ptr->product));
10274 	} else if ((val = dnvlist_get_string(lun->be_lun->options, "product",
10275 	    NULL)) == NULL) {
10276 		switch (lun->be_lun->lun_type) {
10277 		case T_DIRECT:
10278 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10279 			    sizeof(inq_ptr->product));
10280 			break;
10281 		case T_PROCESSOR:
10282 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10283 			    sizeof(inq_ptr->product));
10284 			break;
10285 		case T_CDROM:
10286 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10287 			    sizeof(inq_ptr->product));
10288 			break;
10289 		default:
10290 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10291 			    sizeof(inq_ptr->product));
10292 			break;
10293 		}
10294 	} else {
10295 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10296 		strncpy(inq_ptr->product, val,
10297 		    min(sizeof(inq_ptr->product), strlen(val)));
10298 	}
10299 
10300 	/*
10301 	 * XXX make this a macro somewhere so it automatically gets
10302 	 * incremented when we make changes.
10303 	 */
10304 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10305 	    "revision", NULL)) == NULL) {
10306 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10307 	} else {
10308 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10309 		strncpy(inq_ptr->revision, val,
10310 		    min(sizeof(inq_ptr->revision), strlen(val)));
10311 	}
10312 
10313 	/*
10314 	 * For parallel SCSI, we support double transition and single
10315 	 * transition clocking.  We also support QAS (Quick Arbitration
10316 	 * and Selection) and Information Unit transfers on both the
10317 	 * control and array devices.
10318 	 */
10319 	if (port_type == CTL_PORT_SCSI)
10320 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10321 				    SID_SPI_IUS;
10322 
10323 	/* SAM-6 (no version claimed) */
10324 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10325 	/* SPC-5 (no version claimed) */
10326 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10327 	if (port_type == CTL_PORT_FC) {
10328 		/* FCP-2 ANSI INCITS.350:2003 */
10329 		scsi_ulto2b(0x0917, inq_ptr->version3);
10330 	} else if (port_type == CTL_PORT_SCSI) {
10331 		/* SPI-4 ANSI INCITS.362:200x */
10332 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10333 	} else if (port_type == CTL_PORT_ISCSI) {
10334 		/* iSCSI (no version claimed) */
10335 		scsi_ulto2b(0x0960, inq_ptr->version3);
10336 	} else if (port_type == CTL_PORT_SAS) {
10337 		/* SAS (no version claimed) */
10338 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10339 	} else if (port_type == CTL_PORT_UMASS) {
10340 		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10341 		scsi_ulto2b(0x1730, inq_ptr->version3);
10342 	}
10343 
10344 	if (lun == NULL) {
10345 		/* SBC-4 (no version claimed) */
10346 		scsi_ulto2b(0x0600, inq_ptr->version4);
10347 	} else {
10348 		switch (lun->be_lun->lun_type) {
10349 		case T_DIRECT:
10350 			/* SBC-4 (no version claimed) */
10351 			scsi_ulto2b(0x0600, inq_ptr->version4);
10352 			break;
10353 		case T_PROCESSOR:
10354 			break;
10355 		case T_CDROM:
10356 			/* MMC-6 (no version claimed) */
10357 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10358 			break;
10359 		default:
10360 			break;
10361 		}
10362 	}
10363 
10364 	ctl_set_success(ctsio);
10365 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10366 	ctsio->be_move_done = ctl_config_move_done;
10367 	ctl_datamove((union ctl_io *)ctsio);
10368 	return (CTL_RETVAL_COMPLETE);
10369 }
10370 
10371 int
10372 ctl_inquiry(struct ctl_scsiio *ctsio)
10373 {
10374 	struct scsi_inquiry *cdb;
10375 	int retval;
10376 
10377 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10378 
10379 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10380 	if (cdb->byte2 & SI_EVPD)
10381 		retval = ctl_inquiry_evpd(ctsio);
10382 	else if (cdb->page_code == 0)
10383 		retval = ctl_inquiry_std(ctsio);
10384 	else {
10385 		ctl_set_invalid_field(ctsio,
10386 				      /*sks_valid*/ 1,
10387 				      /*command*/ 1,
10388 				      /*field*/ 2,
10389 				      /*bit_valid*/ 0,
10390 				      /*bit*/ 0);
10391 		ctl_done((union ctl_io *)ctsio);
10392 		return (CTL_RETVAL_COMPLETE);
10393 	}
10394 
10395 	return (retval);
10396 }
10397 
10398 int
10399 ctl_get_config(struct ctl_scsiio *ctsio)
10400 {
10401 	struct ctl_lun *lun = CTL_LUN(ctsio);
10402 	struct scsi_get_config_header *hdr;
10403 	struct scsi_get_config_feature *feature;
10404 	struct scsi_get_config *cdb;
10405 	uint32_t alloc_len, data_len;
10406 	int rt, starting;
10407 
10408 	cdb = (struct scsi_get_config *)ctsio->cdb;
10409 	rt = (cdb->rt & SGC_RT_MASK);
10410 	starting = scsi_2btoul(cdb->starting_feature);
10411 	alloc_len = scsi_2btoul(cdb->length);
10412 
10413 	data_len = sizeof(struct scsi_get_config_header) +
10414 	    sizeof(struct scsi_get_config_feature) + 8 +
10415 	    sizeof(struct scsi_get_config_feature) + 8 +
10416 	    sizeof(struct scsi_get_config_feature) + 4 +
10417 	    sizeof(struct scsi_get_config_feature) + 4 +
10418 	    sizeof(struct scsi_get_config_feature) + 8 +
10419 	    sizeof(struct scsi_get_config_feature) +
10420 	    sizeof(struct scsi_get_config_feature) + 4 +
10421 	    sizeof(struct scsi_get_config_feature) + 4 +
10422 	    sizeof(struct scsi_get_config_feature) + 4 +
10423 	    sizeof(struct scsi_get_config_feature) + 4 +
10424 	    sizeof(struct scsi_get_config_feature) + 4 +
10425 	    sizeof(struct scsi_get_config_feature) + 4;
10426 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10427 	ctsio->kern_sg_entries = 0;
10428 	ctsio->kern_rel_offset = 0;
10429 
10430 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10431 	if (lun->flags & CTL_LUN_NO_MEDIA)
10432 		scsi_ulto2b(0x0000, hdr->current_profile);
10433 	else
10434 		scsi_ulto2b(0x0010, hdr->current_profile);
10435 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10436 
10437 	if (starting > 0x003b)
10438 		goto done;
10439 	if (starting > 0x003a)
10440 		goto f3b;
10441 	if (starting > 0x002b)
10442 		goto f3a;
10443 	if (starting > 0x002a)
10444 		goto f2b;
10445 	if (starting > 0x001f)
10446 		goto f2a;
10447 	if (starting > 0x001e)
10448 		goto f1f;
10449 	if (starting > 0x001d)
10450 		goto f1e;
10451 	if (starting > 0x0010)
10452 		goto f1d;
10453 	if (starting > 0x0003)
10454 		goto f10;
10455 	if (starting > 0x0002)
10456 		goto f3;
10457 	if (starting > 0x0001)
10458 		goto f2;
10459 	if (starting > 0x0000)
10460 		goto f1;
10461 
10462 	/* Profile List */
10463 	scsi_ulto2b(0x0000, feature->feature_code);
10464 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10465 	feature->add_length = 8;
10466 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10467 	feature->feature_data[2] = 0x00;
10468 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10469 	feature->feature_data[6] = 0x01;
10470 	feature = (struct scsi_get_config_feature *)
10471 	    &feature->feature_data[feature->add_length];
10472 
10473 f1:	/* Core */
10474 	scsi_ulto2b(0x0001, feature->feature_code);
10475 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10476 	feature->add_length = 8;
10477 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10478 	feature->feature_data[4] = 0x03;
10479 	feature = (struct scsi_get_config_feature *)
10480 	    &feature->feature_data[feature->add_length];
10481 
10482 f2:	/* Morphing */
10483 	scsi_ulto2b(0x0002, feature->feature_code);
10484 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10485 	feature->add_length = 4;
10486 	feature->feature_data[0] = 0x02;
10487 	feature = (struct scsi_get_config_feature *)
10488 	    &feature->feature_data[feature->add_length];
10489 
10490 f3:	/* Removable Medium */
10491 	scsi_ulto2b(0x0003, feature->feature_code);
10492 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10493 	feature->add_length = 4;
10494 	feature->feature_data[0] = 0x39;
10495 	feature = (struct scsi_get_config_feature *)
10496 	    &feature->feature_data[feature->add_length];
10497 
10498 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10499 		goto done;
10500 
10501 f10:	/* Random Read */
10502 	scsi_ulto2b(0x0010, feature->feature_code);
10503 	feature->flags = 0x00;
10504 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10505 		feature->flags |= SGC_F_CURRENT;
10506 	feature->add_length = 8;
10507 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10508 	scsi_ulto2b(1, &feature->feature_data[4]);
10509 	feature->feature_data[6] = 0x00;
10510 	feature = (struct scsi_get_config_feature *)
10511 	    &feature->feature_data[feature->add_length];
10512 
10513 f1d:	/* Multi-Read */
10514 	scsi_ulto2b(0x001D, feature->feature_code);
10515 	feature->flags = 0x00;
10516 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10517 		feature->flags |= SGC_F_CURRENT;
10518 	feature->add_length = 0;
10519 	feature = (struct scsi_get_config_feature *)
10520 	    &feature->feature_data[feature->add_length];
10521 
10522 f1e:	/* CD Read */
10523 	scsi_ulto2b(0x001E, feature->feature_code);
10524 	feature->flags = 0x00;
10525 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10526 		feature->flags |= SGC_F_CURRENT;
10527 	feature->add_length = 4;
10528 	feature->feature_data[0] = 0x00;
10529 	feature = (struct scsi_get_config_feature *)
10530 	    &feature->feature_data[feature->add_length];
10531 
10532 f1f:	/* DVD Read */
10533 	scsi_ulto2b(0x001F, feature->feature_code);
10534 	feature->flags = 0x08;
10535 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10536 		feature->flags |= SGC_F_CURRENT;
10537 	feature->add_length = 4;
10538 	feature->feature_data[0] = 0x01;
10539 	feature->feature_data[2] = 0x03;
10540 	feature = (struct scsi_get_config_feature *)
10541 	    &feature->feature_data[feature->add_length];
10542 
10543 f2a:	/* DVD+RW */
10544 	scsi_ulto2b(0x002A, feature->feature_code);
10545 	feature->flags = 0x04;
10546 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10547 		feature->flags |= SGC_F_CURRENT;
10548 	feature->add_length = 4;
10549 	feature->feature_data[0] = 0x00;
10550 	feature->feature_data[1] = 0x00;
10551 	feature = (struct scsi_get_config_feature *)
10552 	    &feature->feature_data[feature->add_length];
10553 
10554 f2b:	/* DVD+R */
10555 	scsi_ulto2b(0x002B, feature->feature_code);
10556 	feature->flags = 0x00;
10557 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10558 		feature->flags |= SGC_F_CURRENT;
10559 	feature->add_length = 4;
10560 	feature->feature_data[0] = 0x00;
10561 	feature = (struct scsi_get_config_feature *)
10562 	    &feature->feature_data[feature->add_length];
10563 
10564 f3a:	/* DVD+RW Dual Layer */
10565 	scsi_ulto2b(0x003A, feature->feature_code);
10566 	feature->flags = 0x00;
10567 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10568 		feature->flags |= SGC_F_CURRENT;
10569 	feature->add_length = 4;
10570 	feature->feature_data[0] = 0x00;
10571 	feature->feature_data[1] = 0x00;
10572 	feature = (struct scsi_get_config_feature *)
10573 	    &feature->feature_data[feature->add_length];
10574 
10575 f3b:	/* DVD+R Dual Layer */
10576 	scsi_ulto2b(0x003B, feature->feature_code);
10577 	feature->flags = 0x00;
10578 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10579 		feature->flags |= SGC_F_CURRENT;
10580 	feature->add_length = 4;
10581 	feature->feature_data[0] = 0x00;
10582 	feature = (struct scsi_get_config_feature *)
10583 	    &feature->feature_data[feature->add_length];
10584 
10585 done:
10586 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10587 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10588 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10589 		if (scsi_2btoul(feature->feature_code) == starting)
10590 			feature = (struct scsi_get_config_feature *)
10591 			    &feature->feature_data[feature->add_length];
10592 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10593 	}
10594 	scsi_ulto4b(data_len - 4, hdr->data_length);
10595 	ctsio->kern_data_len = min(data_len, alloc_len);
10596 	ctsio->kern_total_len = ctsio->kern_data_len;
10597 
10598 	ctl_set_success(ctsio);
10599 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10600 	ctsio->be_move_done = ctl_config_move_done;
10601 	ctl_datamove((union ctl_io *)ctsio);
10602 	return (CTL_RETVAL_COMPLETE);
10603 }
10604 
10605 int
10606 ctl_get_event_status(struct ctl_scsiio *ctsio)
10607 {
10608 	struct scsi_get_event_status_header *hdr;
10609 	struct scsi_get_event_status *cdb;
10610 	uint32_t alloc_len, data_len;
10611 
10612 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10613 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10614 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10615 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10616 		ctl_done((union ctl_io *)ctsio);
10617 		return (CTL_RETVAL_COMPLETE);
10618 	}
10619 	alloc_len = scsi_2btoul(cdb->length);
10620 
10621 	data_len = sizeof(struct scsi_get_event_status_header);
10622 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10623 	ctsio->kern_sg_entries = 0;
10624 	ctsio->kern_rel_offset = 0;
10625 	ctsio->kern_data_len = min(data_len, alloc_len);
10626 	ctsio->kern_total_len = ctsio->kern_data_len;
10627 
10628 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10629 	scsi_ulto2b(0, hdr->descr_length);
10630 	hdr->nea_class = SGESN_NEA;
10631 	hdr->supported_class = 0;
10632 
10633 	ctl_set_success(ctsio);
10634 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10635 	ctsio->be_move_done = ctl_config_move_done;
10636 	ctl_datamove((union ctl_io *)ctsio);
10637 	return (CTL_RETVAL_COMPLETE);
10638 }
10639 
10640 int
10641 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10642 {
10643 	struct scsi_mechanism_status_header *hdr;
10644 	struct scsi_mechanism_status *cdb;
10645 	uint32_t alloc_len, data_len;
10646 
10647 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10648 	alloc_len = scsi_2btoul(cdb->length);
10649 
10650 	data_len = sizeof(struct scsi_mechanism_status_header);
10651 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10652 	ctsio->kern_sg_entries = 0;
10653 	ctsio->kern_rel_offset = 0;
10654 	ctsio->kern_data_len = min(data_len, alloc_len);
10655 	ctsio->kern_total_len = ctsio->kern_data_len;
10656 
10657 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10658 	hdr->state1 = 0x00;
10659 	hdr->state2 = 0xe0;
10660 	scsi_ulto3b(0, hdr->lba);
10661 	hdr->slots_num = 0;
10662 	scsi_ulto2b(0, hdr->slots_length);
10663 
10664 	ctl_set_success(ctsio);
10665 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10666 	ctsio->be_move_done = ctl_config_move_done;
10667 	ctl_datamove((union ctl_io *)ctsio);
10668 	return (CTL_RETVAL_COMPLETE);
10669 }
10670 
10671 static void
10672 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10673 {
10674 
10675 	lba += 150;
10676 	buf[0] = 0;
10677 	buf[1] = bin2bcd((lba / 75) / 60);
10678 	buf[2] = bin2bcd((lba / 75) % 60);
10679 	buf[3] = bin2bcd(lba % 75);
10680 }
10681 
10682 int
10683 ctl_read_toc(struct ctl_scsiio *ctsio)
10684 {
10685 	struct ctl_lun *lun = CTL_LUN(ctsio);
10686 	struct scsi_read_toc_hdr *hdr;
10687 	struct scsi_read_toc_type01_descr *descr;
10688 	struct scsi_read_toc *cdb;
10689 	uint32_t alloc_len, data_len;
10690 	int format, msf;
10691 
10692 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10693 	msf = (cdb->byte2 & CD_MSF) != 0;
10694 	format = cdb->format;
10695 	alloc_len = scsi_2btoul(cdb->data_len);
10696 
10697 	data_len = sizeof(struct scsi_read_toc_hdr);
10698 	if (format == 0)
10699 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10700 	else
10701 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10702 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10703 	ctsio->kern_sg_entries = 0;
10704 	ctsio->kern_rel_offset = 0;
10705 	ctsio->kern_data_len = min(data_len, alloc_len);
10706 	ctsio->kern_total_len = ctsio->kern_data_len;
10707 
10708 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10709 	if (format == 0) {
10710 		scsi_ulto2b(0x12, hdr->data_length);
10711 		hdr->first = 1;
10712 		hdr->last = 1;
10713 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10714 		descr->addr_ctl = 0x14;
10715 		descr->track_number = 1;
10716 		if (msf)
10717 			ctl_ultomsf(0, descr->track_start);
10718 		else
10719 			scsi_ulto4b(0, descr->track_start);
10720 		descr++;
10721 		descr->addr_ctl = 0x14;
10722 		descr->track_number = 0xaa;
10723 		if (msf)
10724 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10725 		else
10726 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10727 	} else {
10728 		scsi_ulto2b(0x0a, hdr->data_length);
10729 		hdr->first = 1;
10730 		hdr->last = 1;
10731 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10732 		descr->addr_ctl = 0x14;
10733 		descr->track_number = 1;
10734 		if (msf)
10735 			ctl_ultomsf(0, descr->track_start);
10736 		else
10737 			scsi_ulto4b(0, descr->track_start);
10738 	}
10739 
10740 	ctl_set_success(ctsio);
10741 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10742 	ctsio->be_move_done = ctl_config_move_done;
10743 	ctl_datamove((union ctl_io *)ctsio);
10744 	return (CTL_RETVAL_COMPLETE);
10745 }
10746 
10747 /*
10748  * For known CDB types, parse the LBA and length.
10749  */
10750 static int
10751 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10752 {
10753 
10754 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10755 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10756 
10757 	switch (io->scsiio.cdb[0]) {
10758 	case COMPARE_AND_WRITE: {
10759 		struct scsi_compare_and_write *cdb;
10760 
10761 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10762 
10763 		*lba = scsi_8btou64(cdb->addr);
10764 		*len = cdb->length;
10765 		break;
10766 	}
10767 	case READ_6:
10768 	case WRITE_6: {
10769 		struct scsi_rw_6 *cdb;
10770 
10771 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10772 
10773 		*lba = scsi_3btoul(cdb->addr);
10774 		/* only 5 bits are valid in the most significant address byte */
10775 		*lba &= 0x1fffff;
10776 		*len = cdb->length;
10777 		break;
10778 	}
10779 	case READ_10:
10780 	case WRITE_10: {
10781 		struct scsi_rw_10 *cdb;
10782 
10783 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10784 
10785 		*lba = scsi_4btoul(cdb->addr);
10786 		*len = scsi_2btoul(cdb->length);
10787 		break;
10788 	}
10789 	case WRITE_VERIFY_10: {
10790 		struct scsi_write_verify_10 *cdb;
10791 
10792 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10793 
10794 		*lba = scsi_4btoul(cdb->addr);
10795 		*len = scsi_2btoul(cdb->length);
10796 		break;
10797 	}
10798 	case READ_12:
10799 	case WRITE_12: {
10800 		struct scsi_rw_12 *cdb;
10801 
10802 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10803 
10804 		*lba = scsi_4btoul(cdb->addr);
10805 		*len = scsi_4btoul(cdb->length);
10806 		break;
10807 	}
10808 	case WRITE_VERIFY_12: {
10809 		struct scsi_write_verify_12 *cdb;
10810 
10811 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10812 
10813 		*lba = scsi_4btoul(cdb->addr);
10814 		*len = scsi_4btoul(cdb->length);
10815 		break;
10816 	}
10817 	case READ_16:
10818 	case WRITE_16: {
10819 		struct scsi_rw_16 *cdb;
10820 
10821 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10822 
10823 		*lba = scsi_8btou64(cdb->addr);
10824 		*len = scsi_4btoul(cdb->length);
10825 		break;
10826 	}
10827 	case WRITE_ATOMIC_16: {
10828 		struct scsi_write_atomic_16 *cdb;
10829 
10830 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10831 
10832 		*lba = scsi_8btou64(cdb->addr);
10833 		*len = scsi_2btoul(cdb->length);
10834 		break;
10835 	}
10836 	case WRITE_VERIFY_16: {
10837 		struct scsi_write_verify_16 *cdb;
10838 
10839 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10840 
10841 		*lba = scsi_8btou64(cdb->addr);
10842 		*len = scsi_4btoul(cdb->length);
10843 		break;
10844 	}
10845 	case WRITE_SAME_10: {
10846 		struct scsi_write_same_10 *cdb;
10847 
10848 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10849 
10850 		*lba = scsi_4btoul(cdb->addr);
10851 		*len = scsi_2btoul(cdb->length);
10852 		break;
10853 	}
10854 	case WRITE_SAME_16: {
10855 		struct scsi_write_same_16 *cdb;
10856 
10857 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10858 
10859 		*lba = scsi_8btou64(cdb->addr);
10860 		*len = scsi_4btoul(cdb->length);
10861 		break;
10862 	}
10863 	case VERIFY_10: {
10864 		struct scsi_verify_10 *cdb;
10865 
10866 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10867 
10868 		*lba = scsi_4btoul(cdb->addr);
10869 		*len = scsi_2btoul(cdb->length);
10870 		break;
10871 	}
10872 	case VERIFY_12: {
10873 		struct scsi_verify_12 *cdb;
10874 
10875 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10876 
10877 		*lba = scsi_4btoul(cdb->addr);
10878 		*len = scsi_4btoul(cdb->length);
10879 		break;
10880 	}
10881 	case VERIFY_16: {
10882 		struct scsi_verify_16 *cdb;
10883 
10884 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10885 
10886 		*lba = scsi_8btou64(cdb->addr);
10887 		*len = scsi_4btoul(cdb->length);
10888 		break;
10889 	}
10890 	case UNMAP: {
10891 		*lba = 0;
10892 		*len = UINT64_MAX;
10893 		break;
10894 	}
10895 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10896 		struct scsi_get_lba_status *cdb;
10897 
10898 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10899 		*lba = scsi_8btou64(cdb->addr);
10900 		*len = UINT32_MAX;
10901 		break;
10902 	}
10903 	default:
10904 		*lba = 0;
10905 		*len = UINT64_MAX;
10906 		return (1);
10907 	}
10908 
10909 	return (0);
10910 }
10911 
10912 static ctl_action
10913 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10914     bool seq)
10915 {
10916 	uint64_t endlba1, endlba2;
10917 
10918 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10919 	endlba2 = lba2 + len2 - 1;
10920 
10921 	if ((endlba1 < lba2) || (endlba2 < lba1))
10922 		return (CTL_ACTION_PASS);
10923 	else
10924 		return (CTL_ACTION_BLOCK);
10925 }
10926 
10927 static int
10928 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10929 {
10930 	struct ctl_ptr_len_flags *ptrlen;
10931 	struct scsi_unmap_desc *buf, *end, *range;
10932 	uint64_t lba;
10933 	uint32_t len;
10934 
10935 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10936 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10937 
10938 	/* If not UNMAP -- go other way. */
10939 	if (io->scsiio.cdb[0] != UNMAP)
10940 		return (CTL_ACTION_SKIP);
10941 
10942 	/* If UNMAP without data -- block and wait for data. */
10943 	ptrlen = (struct ctl_ptr_len_flags *)
10944 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10945 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10946 	    ptrlen->ptr == NULL)
10947 		return (CTL_ACTION_BLOCK);
10948 
10949 	/* UNMAP with data -- check for collision. */
10950 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10951 	end = buf + ptrlen->len / sizeof(*buf);
10952 	for (range = buf; range < end; range++) {
10953 		lba = scsi_8btou64(range->lba);
10954 		len = scsi_4btoul(range->length);
10955 		if ((lba < lba2 + len2) && (lba + len > lba2))
10956 			return (CTL_ACTION_BLOCK);
10957 	}
10958 	return (CTL_ACTION_PASS);
10959 }
10960 
10961 static ctl_action
10962 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10963 {
10964 	uint64_t lba1, lba2;
10965 	uint64_t len1, len2;
10966 	int retval;
10967 
10968 	retval = ctl_get_lba_len(io2, &lba2, &len2);
10969 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10970 
10971 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10972 	if (retval != CTL_ACTION_SKIP)
10973 		return (retval);
10974 
10975 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10976 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10977 
10978 	if (seq && (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE))
10979 		seq = FALSE;
10980 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10981 }
10982 
10983 static ctl_action
10984 ctl_seq_check(union ctl_io *io1, union ctl_io *io2)
10985 {
10986 	uint64_t lba1, lba2;
10987 	uint64_t len1, len2;
10988 	int retval __diagused;
10989 
10990 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10991 		return (CTL_ACTION_PASS);
10992 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10993 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10994 	retval = ctl_get_lba_len(io2, &lba2, &len2);
10995 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10996 
10997 	if (lba1 + len1 == lba2)
10998 		return (CTL_ACTION_BLOCK);
10999 	return (CTL_ACTION_PASS);
11000 }
11001 
11002 static ctl_action
11003 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11004     const uint8_t *serialize_row, union ctl_io *ooa_io)
11005 {
11006 
11007 	/*
11008 	 * The initiator attempted multiple untagged commands at the same
11009 	 * time.  Can't do that.
11010 	 */
11011 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11012 	 && __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11013 	 && ((pending_io->io_hdr.nexus.targ_port ==
11014 	      ooa_io->io_hdr.nexus.targ_port)
11015 	  && (pending_io->io_hdr.nexus.initid ==
11016 	      ooa_io->io_hdr.nexus.initid))
11017 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11018 	      CTL_FLAG_STATUS_SENT)) == 0))
11019 		return (CTL_ACTION_OVERLAP);
11020 
11021 	/*
11022 	 * The initiator attempted to send multiple tagged commands with
11023 	 * the same ID.  (It's fine if different initiators have the same
11024 	 * tag ID.)
11025 	 *
11026 	 * Even if all of those conditions are true, we don't kill the I/O
11027 	 * if the command ahead of us has been aborted.  We won't end up
11028 	 * sending it to the FETD, and it's perfectly legal to resend a
11029 	 * command with the same tag number as long as the previous
11030 	 * instance of this tag number has been aborted somehow.
11031 	 */
11032 	if (__predict_true(pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11033 	 && __predict_true(ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11034 	 && __predict_false(pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11035 	 && ((pending_io->io_hdr.nexus.targ_port ==
11036 	      ooa_io->io_hdr.nexus.targ_port)
11037 	  && (pending_io->io_hdr.nexus.initid ==
11038 	      ooa_io->io_hdr.nexus.initid))
11039 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11040 	      CTL_FLAG_STATUS_SENT)) == 0))
11041 		return (CTL_ACTION_OVERLAP_TAG);
11042 
11043 	/*
11044 	 * If we get a head of queue tag, SAM-3 says that we should
11045 	 * immediately execute it.
11046 	 *
11047 	 * What happens if this command would normally block for some other
11048 	 * reason?  e.g. a request sense with a head of queue tag
11049 	 * immediately after a write.  Normally that would block, but this
11050 	 * will result in its getting executed immediately...
11051 	 *
11052 	 * We currently return "pass" instead of "skip", so we'll end up
11053 	 * going through the rest of the queue to check for overlapped tags.
11054 	 *
11055 	 * XXX KDM check for other types of blockage first??
11056 	 */
11057 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
11058 		return (CTL_ACTION_PASS);
11059 
11060 	/*
11061 	 * Simple tags get blocked until all head of queue and ordered tags
11062 	 * ahead of them have completed.  I'm lumping untagged commands in
11063 	 * with simple tags here.  XXX KDM is that the right thing to do?
11064 	 */
11065 	if (__predict_false(ooa_io->scsiio.tag_type == CTL_TAG_ORDERED) ||
11066 	    __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
11067 		return (CTL_ACTION_BLOCK);
11068 
11069 	/* Unsupported command in OOA queue. */
11070 	if (__predict_false(ooa_io->scsiio.seridx == CTL_SERIDX_INVLD))
11071 		return (CTL_ACTION_PASS);
11072 
11073 	switch (serialize_row[ooa_io->scsiio.seridx]) {
11074 	case CTL_SER_SEQ:
11075 		if (lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11076 			return (ctl_seq_check(ooa_io, pending_io));
11077 		/* FALLTHROUGH */
11078 	case CTL_SER_PASS:
11079 		return (CTL_ACTION_PASS);
11080 	case CTL_SER_EXTENTOPT:
11081 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
11082 		    SCP_QUEUE_ALG_UNRESTRICTED)
11083 			return (CTL_ACTION_PASS);
11084 		/* FALLTHROUGH */
11085 	case CTL_SER_EXTENT:
11086 		return (ctl_extent_check(ooa_io, pending_io,
11087 		    (lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11088 	case CTL_SER_BLOCKOPT:
11089 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
11090 		    SCP_QUEUE_ALG_UNRESTRICTED)
11091 			return (CTL_ACTION_PASS);
11092 		/* FALLTHROUGH */
11093 	case CTL_SER_BLOCK:
11094 		return (CTL_ACTION_BLOCK);
11095 	default:
11096 		__assert_unreachable();
11097 	}
11098 }
11099 
11100 /*
11101  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11102  * Assumptions:
11103  * - pending_io is generally either incoming, or on the blocked queue
11104  * - starting I/O is the I/O we want to start the check with.
11105  */
11106 static ctl_action
11107 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11108 	      union ctl_io **starting_io)
11109 {
11110 	union ctl_io *ooa_io = *starting_io;
11111 	const uint8_t *serialize_row;
11112 	ctl_action action;
11113 
11114 	mtx_assert(&lun->lun_lock, MA_OWNED);
11115 
11116 	/*
11117 	 * Aborted commands are not going to be executed and may even
11118 	 * not report completion, so we don't care about their order.
11119 	 * Let them complete ASAP to clean the OOA queue.
11120 	 */
11121 	if (__predict_false(pending_io->io_hdr.flags & CTL_FLAG_ABORT))
11122 		return (CTL_ACTION_SKIP);
11123 
11124 	/*
11125 	 * Ordered tags have to block until all items ahead of them have
11126 	 * completed.  If we get called with an ordered tag, we always
11127 	 * block, if something else is ahead of us in the queue.
11128 	 */
11129 	if ((pending_io->scsiio.tag_type == CTL_TAG_ORDERED) &&
11130 	    (ooa_io != NULL))
11131 		return (CTL_ACTION_BLOCK);
11132 
11133 	serialize_row = ctl_serialize_table[pending_io->scsiio.seridx];
11134 
11135 	/*
11136 	 * Run back along the OOA queue, starting with the current
11137 	 * blocked I/O and going through every I/O before it on the
11138 	 * queue.  If starting_io is NULL, we'll just end up returning
11139 	 * CTL_ACTION_PASS.
11140 	 */
11141 	for (; ooa_io != NULL;
11142 	     ooa_io = (union ctl_io *)LIST_NEXT(&ooa_io->io_hdr, ooa_links)) {
11143 		action = ctl_check_for_blockage(lun, pending_io, serialize_row,
11144 		    ooa_io);
11145 		if (action != CTL_ACTION_PASS) {
11146 			*starting_io = ooa_io;
11147 			return (action);
11148 		}
11149 	}
11150 
11151 	*starting_io = NULL;
11152 	return (CTL_ACTION_PASS);
11153 }
11154 
11155 /*
11156  * Try to unblock the specified I/O.
11157  *
11158  * skip parameter allows explicitly skip present blocker of the I/O,
11159  * starting from the previous one on OOA queue.  It can be used when
11160  * we know for sure that the blocker I/O does no longer count.
11161  */
11162 static void
11163 ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io, bool skip)
11164 {
11165 	struct ctl_softc *softc = lun->ctl_softc;
11166 	union ctl_io *bio, *obio;
11167 	const struct ctl_cmd_entry *entry;
11168 	union ctl_ha_msg msg_info;
11169 	ctl_action action;
11170 
11171 	mtx_assert(&lun->lun_lock, MA_OWNED);
11172 
11173 	if (io->io_hdr.blocker == NULL)
11174 		return;
11175 
11176 	obio = bio = io->io_hdr.blocker;
11177 	if (skip)
11178 		bio = (union ctl_io *)LIST_NEXT(&bio->io_hdr, ooa_links);
11179 	action = ctl_check_ooa(lun, io, &bio);
11180 	if (action == CTL_ACTION_BLOCK) {
11181 		/* Still blocked, but may be by different I/O now. */
11182 		if (bio != obio) {
11183 			TAILQ_REMOVE(&obio->io_hdr.blocked_queue,
11184 			    &io->io_hdr, blocked_links);
11185 			TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue,
11186 			    &io->io_hdr, blocked_links);
11187 			io->io_hdr.blocker = bio;
11188 		}
11189 		return;
11190 	}
11191 
11192 	/* No longer blocked, one way or another. */
11193 	TAILQ_REMOVE(&obio->io_hdr.blocked_queue, &io->io_hdr, blocked_links);
11194 	io->io_hdr.blocker = NULL;
11195 
11196 	switch (action) {
11197 	case CTL_ACTION_PASS:
11198 	case CTL_ACTION_SKIP:
11199 
11200 		/* Serializing commands from the other SC retire there. */
11201 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11202 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11203 			io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11204 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11205 			msg_info.hdr.serializing_sc = io;
11206 			msg_info.hdr.msg_type = CTL_MSG_R2R;
11207 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11208 			    sizeof(msg_info.hdr), M_NOWAIT);
11209 			break;
11210 		}
11211 
11212 		/*
11213 		 * Check this I/O for LUN state changes that may have happened
11214 		 * while this command was blocked. The LUN state may have been
11215 		 * changed by a command ahead of us in the queue.
11216 		 */
11217 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11218 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
11219 			ctl_done(io);
11220 			break;
11221 		}
11222 
11223 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11224 		ctl_enqueue_rtr(io);
11225 		break;
11226 	default:
11227 		__assert_unreachable();
11228 	case CTL_ACTION_OVERLAP:
11229 		ctl_set_overlapped_cmd(&io->scsiio);
11230 		goto error;
11231 	case CTL_ACTION_OVERLAP_TAG:
11232 		ctl_set_overlapped_tag(&io->scsiio,
11233 		    io->scsiio.tag_num & 0xff);
11234 error:
11235 		/* Serializing commands from the other SC are done here. */
11236 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11237 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11238 			ctl_try_unblock_others(lun, io, TRUE);
11239 			LIST_REMOVE(&io->io_hdr, ooa_links);
11240 
11241 			ctl_copy_sense_data_back(io, &msg_info);
11242 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11243 			msg_info.hdr.serializing_sc = NULL;
11244 			msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
11245 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11246 			    sizeof(msg_info.scsi), M_WAITOK);
11247 			ctl_free_io(io);
11248 			break;
11249 		}
11250 
11251 		ctl_done(io);
11252 		break;
11253 	}
11254 }
11255 
11256 /*
11257  * Try to unblock I/Os blocked by the specified I/O.
11258  *
11259  * skip parameter allows explicitly skip the specified I/O as blocker,
11260  * starting from the previous one on the OOA queue.  It can be used when
11261  * we know for sure that the specified I/O does no longer count (done).
11262  * It has to be still on OOA queue though so that we know where to start.
11263  */
11264 static void
11265 ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *bio, bool skip)
11266 {
11267 	union ctl_io *io, *next_io;
11268 
11269 	mtx_assert(&lun->lun_lock, MA_OWNED);
11270 
11271 	for (io = (union ctl_io *)TAILQ_FIRST(&bio->io_hdr.blocked_queue);
11272 	     io != NULL; io = next_io) {
11273 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, blocked_links);
11274 
11275 		KASSERT(io->io_hdr.blocker != NULL,
11276 		    ("I/O %p on blocked list without blocker", io));
11277 		ctl_try_unblock_io(lun, io, skip);
11278 	}
11279 	KASSERT(!skip || TAILQ_EMPTY(&bio->io_hdr.blocked_queue),
11280 	    ("blocked_queue is not empty after skipping %p", bio));
11281 }
11282 
11283 /*
11284  * This routine (with one exception) checks LUN flags that can be set by
11285  * commands ahead of us in the OOA queue.  These flags have to be checked
11286  * when a command initially comes in, and when we pull a command off the
11287  * blocked queue and are preparing to execute it.  The reason we have to
11288  * check these flags for commands on the blocked queue is that the LUN
11289  * state may have been changed by a command ahead of us while we're on the
11290  * blocked queue.
11291  *
11292  * Ordering is somewhat important with these checks, so please pay
11293  * careful attention to the placement of any new checks.
11294  */
11295 static int
11296 ctl_scsiio_lun_check(struct ctl_lun *lun,
11297     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11298 {
11299 	struct ctl_softc *softc = lun->ctl_softc;
11300 	int retval;
11301 	uint32_t residx;
11302 
11303 	retval = 0;
11304 
11305 	mtx_assert(&lun->lun_lock, MA_OWNED);
11306 
11307 	/*
11308 	 * If this shelf is a secondary shelf controller, we may have to
11309 	 * reject some commands disallowed by HA mode and link state.
11310 	 */
11311 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11312 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11313 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11314 			ctl_set_lun_unavail(ctsio);
11315 			retval = 1;
11316 			goto bailout;
11317 		}
11318 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11319 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11320 			ctl_set_lun_transit(ctsio);
11321 			retval = 1;
11322 			goto bailout;
11323 		}
11324 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11325 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11326 			ctl_set_lun_standby(ctsio);
11327 			retval = 1;
11328 			goto bailout;
11329 		}
11330 
11331 		/* The rest of checks are only done on executing side */
11332 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11333 			goto bailout;
11334 	}
11335 
11336 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11337 		if (lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11338 			ctl_set_hw_write_protected(ctsio);
11339 			retval = 1;
11340 			goto bailout;
11341 		}
11342 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11343 			ctl_set_sense(ctsio, /*current_error*/ 1,
11344 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11345 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11346 			retval = 1;
11347 			goto bailout;
11348 		}
11349 	}
11350 
11351 	/*
11352 	 * Check for a reservation conflict.  If this command isn't allowed
11353 	 * even on reserved LUNs, and if this initiator isn't the one who
11354 	 * reserved us, reject the command with a reservation conflict.
11355 	 */
11356 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11357 	if ((lun->flags & CTL_LUN_RESERVED)
11358 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11359 		if (lun->res_idx != residx) {
11360 			ctl_set_reservation_conflict(ctsio);
11361 			retval = 1;
11362 			goto bailout;
11363 		}
11364 	}
11365 
11366 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11367 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11368 		/* No reservation or command is allowed. */;
11369 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11370 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11371 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11372 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11373 		/* The command is allowed for Write Exclusive resv. */;
11374 	} else {
11375 		/*
11376 		 * if we aren't registered or it's a res holder type
11377 		 * reservation and this isn't the res holder then set a
11378 		 * conflict.
11379 		 */
11380 		if (ctl_get_prkey(lun, residx) == 0 ||
11381 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11382 			ctl_set_reservation_conflict(ctsio);
11383 			retval = 1;
11384 			goto bailout;
11385 		}
11386 	}
11387 
11388 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11389 		if (lun->flags & CTL_LUN_EJECTED)
11390 			ctl_set_lun_ejected(ctsio);
11391 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11392 			if (lun->flags & CTL_LUN_REMOVABLE)
11393 				ctl_set_lun_no_media(ctsio);
11394 			else
11395 				ctl_set_lun_int_reqd(ctsio);
11396 		} else if (lun->flags & CTL_LUN_STOPPED)
11397 			ctl_set_lun_stopped(ctsio);
11398 		else
11399 			goto bailout;
11400 		retval = 1;
11401 		goto bailout;
11402 	}
11403 
11404 bailout:
11405 	return (retval);
11406 }
11407 
11408 static void
11409 ctl_failover_io(union ctl_io *io, int have_lock)
11410 {
11411 	ctl_set_busy(&io->scsiio);
11412 	ctl_done(io);
11413 }
11414 
11415 static void
11416 ctl_failover_lun(union ctl_io *rio)
11417 {
11418 	struct ctl_softc *softc = CTL_SOFTC(rio);
11419 	struct ctl_lun *lun;
11420 	struct ctl_io_hdr *io, *next_io;
11421 	uint32_t targ_lun;
11422 
11423 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11424 	CTL_DEBUG_PRINT(("FAILOVER for lun %u\n", targ_lun));
11425 
11426 	/* Find and lock the LUN. */
11427 	mtx_lock(&softc->ctl_lock);
11428 	if (targ_lun > ctl_max_luns ||
11429 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11430 		mtx_unlock(&softc->ctl_lock);
11431 		return;
11432 	}
11433 	mtx_lock(&lun->lun_lock);
11434 	mtx_unlock(&softc->ctl_lock);
11435 	if (lun->flags & CTL_LUN_DISABLED) {
11436 		mtx_unlock(&lun->lun_lock);
11437 		return;
11438 	}
11439 
11440 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11441 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11442 			/* We are master */
11443 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11444 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11445 					io->flags |= CTL_FLAG_ABORT |
11446 					    CTL_FLAG_FAILOVER;
11447 					ctl_try_unblock_io(lun,
11448 					    (union ctl_io *)io, FALSE);
11449 				} else { /* This can be only due to DATAMOVE */
11450 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11451 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11452 					io->flags |= CTL_FLAG_IO_ACTIVE;
11453 					io->port_status = 31340;
11454 					ctl_enqueue_isc((union ctl_io *)io);
11455 				}
11456 			} else
11457 			/* We are slave */
11458 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11459 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11460 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11461 					io->flags |= CTL_FLAG_FAILOVER;
11462 				} else {
11463 					ctl_set_busy(&((union ctl_io *)io)->
11464 					    scsiio);
11465 					ctl_done((union ctl_io *)io);
11466 				}
11467 			}
11468 		}
11469 	} else { /* SERIALIZE modes */
11470 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11471 			/* We are master */
11472 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11473 				if (io->blocker != NULL) {
11474 					TAILQ_REMOVE(&io->blocker->io_hdr.blocked_queue,
11475 					    io, blocked_links);
11476 					io->blocker = NULL;
11477 				}
11478 				ctl_try_unblock_others(lun, (union ctl_io *)io,
11479 				    TRUE);
11480 				LIST_REMOVE(io, ooa_links);
11481 				ctl_free_io((union ctl_io *)io);
11482 			} else
11483 			/* We are slave */
11484 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11485 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11486 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11487 					ctl_set_busy(&((union ctl_io *)io)->
11488 					    scsiio);
11489 					ctl_done((union ctl_io *)io);
11490 				}
11491 			}
11492 		}
11493 	}
11494 	mtx_unlock(&lun->lun_lock);
11495 }
11496 
11497 static void
11498 ctl_scsiio_precheck(struct ctl_scsiio *ctsio)
11499 {
11500 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
11501 	struct ctl_lun *lun;
11502 	const struct ctl_cmd_entry *entry;
11503 	union ctl_io *bio;
11504 	uint32_t initidx, targ_lun;
11505 
11506 	lun = NULL;
11507 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11508 	if (targ_lun < ctl_max_luns)
11509 		lun = softc->ctl_luns[targ_lun];
11510 	if (lun) {
11511 		/*
11512 		 * If the LUN is invalid, pretend that it doesn't exist.
11513 		 * It will go away as soon as all pending I/O has been
11514 		 * completed.
11515 		 */
11516 		mtx_lock(&lun->lun_lock);
11517 		if (lun->flags & CTL_LUN_DISABLED) {
11518 			mtx_unlock(&lun->lun_lock);
11519 			lun = NULL;
11520 		}
11521 	}
11522 	CTL_LUN(ctsio) = lun;
11523 	if (lun) {
11524 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11525 
11526 		/*
11527 		 * Every I/O goes into the OOA queue for a particular LUN,
11528 		 * and stays there until completion.
11529 		 */
11530 #ifdef CTL_TIME_IO
11531 		if (LIST_EMPTY(&lun->ooa_queue))
11532 			lun->idle_time += getsbinuptime() - lun->last_busy;
11533 #endif
11534 		LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11535 	}
11536 
11537 	/* Get command entry and return error if it is unsuppotyed. */
11538 	entry = ctl_validate_command(ctsio);
11539 	if (entry == NULL) {
11540 		if (lun)
11541 			mtx_unlock(&lun->lun_lock);
11542 		return;
11543 	}
11544 
11545 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11546 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11547 
11548 	/*
11549 	 * Check to see whether we can send this command to LUNs that don't
11550 	 * exist.  This should pretty much only be the case for inquiry
11551 	 * and request sense.  Further checks, below, really require having
11552 	 * a LUN, so we can't really check the command anymore.  Just put
11553 	 * it on the rtr queue.
11554 	 */
11555 	if (lun == NULL) {
11556 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11557 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11558 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11559 			return;
11560 		}
11561 
11562 		ctl_set_unsupported_lun(ctsio);
11563 		ctl_done((union ctl_io *)ctsio);
11564 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11565 		return;
11566 	} else {
11567 		/*
11568 		 * Make sure we support this particular command on this LUN.
11569 		 * e.g., we don't support writes to the control LUN.
11570 		 */
11571 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11572 			mtx_unlock(&lun->lun_lock);
11573 			ctl_set_invalid_opcode(ctsio);
11574 			ctl_done((union ctl_io *)ctsio);
11575 			return;
11576 		}
11577 	}
11578 
11579 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11580 
11581 	/*
11582 	 * If we've got a request sense, it'll clear the contingent
11583 	 * allegiance condition.  Otherwise, if we have a CA condition for
11584 	 * this initiator, clear it, because it sent down a command other
11585 	 * than request sense.
11586 	 */
11587 	if (ctsio->cdb[0] != REQUEST_SENSE) {
11588 		struct scsi_sense_data *ps;
11589 
11590 		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11591 		if (ps != NULL)
11592 			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11593 	}
11594 
11595 	/*
11596 	 * If the command has this flag set, it handles its own unit
11597 	 * attention reporting, we shouldn't do anything.  Otherwise we
11598 	 * check for any pending unit attentions, and send them back to the
11599 	 * initiator.  We only do this when a command initially comes in,
11600 	 * not when we pull it off the blocked queue.
11601 	 *
11602 	 * According to SAM-3, section 5.3.2, the order that things get
11603 	 * presented back to the host is basically unit attentions caused
11604 	 * by some sort of reset event, busy status, reservation conflicts
11605 	 * or task set full, and finally any other status.
11606 	 *
11607 	 * One issue here is that some of the unit attentions we report
11608 	 * don't fall into the "reset" category (e.g. "reported luns data
11609 	 * has changed").  So reporting it here, before the reservation
11610 	 * check, may be technically wrong.  I guess the only thing to do
11611 	 * would be to check for and report the reset events here, and then
11612 	 * check for the other unit attention types after we check for a
11613 	 * reservation conflict.
11614 	 *
11615 	 * XXX KDM need to fix this
11616 	 */
11617 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11618 		ctl_ua_type ua_type;
11619 		u_int sense_len = 0;
11620 
11621 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11622 		    &sense_len, SSD_TYPE_NONE);
11623 		if (ua_type != CTL_UA_NONE) {
11624 			mtx_unlock(&lun->lun_lock);
11625 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11626 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11627 			ctsio->sense_len = sense_len;
11628 			ctl_done((union ctl_io *)ctsio);
11629 			return;
11630 		}
11631 	}
11632 
11633 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11634 		mtx_unlock(&lun->lun_lock);
11635 		ctl_done((union ctl_io *)ctsio);
11636 		return;
11637 	}
11638 
11639 	/*
11640 	 * XXX CHD this is where we want to send IO to other side if
11641 	 * this LUN is secondary on this SC. We will need to make a copy
11642 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11643 	 * the copy we send as FROM_OTHER.
11644 	 * We also need to stuff the address of the original IO so we can
11645 	 * find it easily. Something similar will need be done on the other
11646 	 * side so when we are done we can find the copy.
11647 	 */
11648 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11649 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11650 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11651 		union ctl_ha_msg msg_info;
11652 		int isc_retval;
11653 
11654 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11655 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11656 		mtx_unlock(&lun->lun_lock);
11657 
11658 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11659 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11660 		msg_info.hdr.serializing_sc = NULL;
11661 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11662 		msg_info.scsi.tag_num = ctsio->tag_num;
11663 		msg_info.scsi.tag_type = ctsio->tag_type;
11664 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11665 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11666 		msg_info.scsi.priority = ctsio->priority;
11667 
11668 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11669 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11670 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11671 			ctsio->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11672 			ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
11673 			ctl_set_busy(ctsio);
11674 			ctl_done((union ctl_io *)ctsio);
11675 			return;
11676 		}
11677 		return;
11678 	}
11679 
11680 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
11681 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
11682 	case CTL_ACTION_PASS:
11683 	case CTL_ACTION_SKIP:
11684 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11685 		mtx_unlock(&lun->lun_lock);
11686 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11687 		break;
11688 	case CTL_ACTION_BLOCK:
11689 		ctsio->io_hdr.blocker = bio;
11690 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
11691 				  blocked_links);
11692 		mtx_unlock(&lun->lun_lock);
11693 		break;
11694 	case CTL_ACTION_OVERLAP:
11695 		mtx_unlock(&lun->lun_lock);
11696 		ctl_set_overlapped_cmd(ctsio);
11697 		ctl_done((union ctl_io *)ctsio);
11698 		break;
11699 	case CTL_ACTION_OVERLAP_TAG:
11700 		mtx_unlock(&lun->lun_lock);
11701 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11702 		ctl_done((union ctl_io *)ctsio);
11703 		break;
11704 	default:
11705 		__assert_unreachable();
11706 	}
11707 }
11708 
11709 const struct ctl_cmd_entry *
11710 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11711 {
11712 	const struct ctl_cmd_entry *entry;
11713 	int service_action;
11714 
11715 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11716 	if (sa)
11717 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11718 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11719 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11720 		entry = &((const struct ctl_cmd_entry *)
11721 		    entry->execute)[service_action];
11722 	}
11723 	return (entry);
11724 }
11725 
11726 const struct ctl_cmd_entry *
11727 ctl_validate_command(struct ctl_scsiio *ctsio)
11728 {
11729 	const struct ctl_cmd_entry *entry;
11730 	int i, sa;
11731 	uint8_t diff;
11732 
11733 	entry = ctl_get_cmd_entry(ctsio, &sa);
11734 	ctsio->seridx = entry->seridx;
11735 	if (entry->execute == NULL) {
11736 		if (sa)
11737 			ctl_set_invalid_field(ctsio,
11738 					      /*sks_valid*/ 1,
11739 					      /*command*/ 1,
11740 					      /*field*/ 1,
11741 					      /*bit_valid*/ 1,
11742 					      /*bit*/ 4);
11743 		else
11744 			ctl_set_invalid_opcode(ctsio);
11745 		ctl_done((union ctl_io *)ctsio);
11746 		return (NULL);
11747 	}
11748 	KASSERT(entry->length > 0,
11749 	    ("Not defined length for command 0x%02x/0x%02x",
11750 	     ctsio->cdb[0], ctsio->cdb[1]));
11751 	for (i = 1; i < entry->length; i++) {
11752 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11753 		if (diff == 0)
11754 			continue;
11755 		ctl_set_invalid_field(ctsio,
11756 				      /*sks_valid*/ 1,
11757 				      /*command*/ 1,
11758 				      /*field*/ i,
11759 				      /*bit_valid*/ 1,
11760 				      /*bit*/ fls(diff) - 1);
11761 		ctl_done((union ctl_io *)ctsio);
11762 		return (NULL);
11763 	}
11764 	return (entry);
11765 }
11766 
11767 static int
11768 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11769 {
11770 
11771 	switch (lun_type) {
11772 	case T_DIRECT:
11773 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11774 			return (0);
11775 		break;
11776 	case T_PROCESSOR:
11777 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11778 			return (0);
11779 		break;
11780 	case T_CDROM:
11781 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11782 			return (0);
11783 		break;
11784 	default:
11785 		return (0);
11786 	}
11787 	return (1);
11788 }
11789 
11790 static int
11791 ctl_scsiio(struct ctl_scsiio *ctsio)
11792 {
11793 	int retval;
11794 	const struct ctl_cmd_entry *entry;
11795 
11796 	retval = CTL_RETVAL_COMPLETE;
11797 
11798 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11799 
11800 	entry = ctl_get_cmd_entry(ctsio, NULL);
11801 
11802 	/*
11803 	 * If this I/O has been aborted, just send it straight to
11804 	 * ctl_done() without executing it.
11805 	 */
11806 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11807 		ctl_done((union ctl_io *)ctsio);
11808 		goto bailout;
11809 	}
11810 
11811 	/*
11812 	 * All the checks should have been handled by ctl_scsiio_precheck().
11813 	 * We should be clear now to just execute the I/O.
11814 	 */
11815 	retval = entry->execute(ctsio);
11816 
11817 bailout:
11818 	return (retval);
11819 }
11820 
11821 static int
11822 ctl_target_reset(union ctl_io *io)
11823 {
11824 	struct ctl_softc *softc = CTL_SOFTC(io);
11825 	struct ctl_port *port = CTL_PORT(io);
11826 	struct ctl_lun *lun;
11827 	uint32_t initidx;
11828 	ctl_ua_type ua_type;
11829 
11830 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11831 		union ctl_ha_msg msg_info;
11832 
11833 		msg_info.hdr.nexus = io->io_hdr.nexus;
11834 		msg_info.task.task_action = io->taskio.task_action;
11835 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11836 		msg_info.hdr.original_sc = NULL;
11837 		msg_info.hdr.serializing_sc = NULL;
11838 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11839 		    sizeof(msg_info.task), M_WAITOK);
11840 	}
11841 
11842 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11843 	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11844 		ua_type = CTL_UA_TARG_RESET;
11845 	else
11846 		ua_type = CTL_UA_BUS_RESET;
11847 	mtx_lock(&softc->ctl_lock);
11848 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11849 		if (port != NULL &&
11850 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11851 			continue;
11852 		ctl_do_lun_reset(lun, initidx, ua_type);
11853 	}
11854 	mtx_unlock(&softc->ctl_lock);
11855 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11856 	return (0);
11857 }
11858 
11859 /*
11860  * The LUN should always be set.  The I/O is optional, and is used to
11861  * distinguish between I/Os sent by this initiator, and by other
11862  * initiators.  We set unit attention for initiators other than this one.
11863  * SAM-3 is vague on this point.  It does say that a unit attention should
11864  * be established for other initiators when a LUN is reset (see section
11865  * 5.7.3), but it doesn't specifically say that the unit attention should
11866  * be established for this particular initiator when a LUN is reset.  Here
11867  * is the relevant text, from SAM-3 rev 8:
11868  *
11869  * 5.7.2 When a SCSI initiator port aborts its own tasks
11870  *
11871  * When a SCSI initiator port causes its own task(s) to be aborted, no
11872  * notification that the task(s) have been aborted shall be returned to
11873  * the SCSI initiator port other than the completion response for the
11874  * command or task management function action that caused the task(s) to
11875  * be aborted and notification(s) associated with related effects of the
11876  * action (e.g., a reset unit attention condition).
11877  *
11878  * XXX KDM for now, we're setting unit attention for all initiators.
11879  */
11880 static void
11881 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11882 {
11883 	struct ctl_io_hdr *xioh;
11884 	int i;
11885 
11886 	mtx_lock(&lun->lun_lock);
11887 	/* Abort tasks. */
11888 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11889 		xioh->flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11890 		ctl_try_unblock_io(lun, (union ctl_io *)xioh, FALSE);
11891 	}
11892 	/* Clear CA. */
11893 	for (i = 0; i < ctl_max_ports; i++) {
11894 		free(lun->pending_sense[i], M_CTL);
11895 		lun->pending_sense[i] = NULL;
11896 	}
11897 	/* Clear reservation. */
11898 	lun->flags &= ~CTL_LUN_RESERVED;
11899 	/* Clear prevent media removal. */
11900 	if (lun->prevent) {
11901 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11902 			ctl_clear_mask(lun->prevent, i);
11903 		lun->prevent_count = 0;
11904 	}
11905 	/* Clear TPC status */
11906 	ctl_tpc_lun_clear(lun, -1);
11907 	/* Establish UA. */
11908 #if 0
11909 	ctl_est_ua_all(lun, initidx, ua_type);
11910 #else
11911 	ctl_est_ua_all(lun, -1, ua_type);
11912 #endif
11913 	mtx_unlock(&lun->lun_lock);
11914 }
11915 
11916 static int
11917 ctl_lun_reset(union ctl_io *io)
11918 {
11919 	struct ctl_softc *softc = CTL_SOFTC(io);
11920 	struct ctl_lun *lun;
11921 	uint32_t targ_lun, initidx;
11922 
11923 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11924 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11925 	mtx_lock(&softc->ctl_lock);
11926 	if (targ_lun >= ctl_max_luns ||
11927 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11928 		mtx_unlock(&softc->ctl_lock);
11929 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11930 		return (1);
11931 	}
11932 	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11933 	mtx_unlock(&softc->ctl_lock);
11934 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11935 
11936 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11937 		union ctl_ha_msg msg_info;
11938 
11939 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11940 		msg_info.hdr.nexus = io->io_hdr.nexus;
11941 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11942 		msg_info.hdr.original_sc = NULL;
11943 		msg_info.hdr.serializing_sc = NULL;
11944 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11945 		    sizeof(msg_info.task), M_WAITOK);
11946 	}
11947 	return (0);
11948 }
11949 
11950 static void
11951 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11952     int other_sc)
11953 {
11954 	struct ctl_io_hdr *xioh;
11955 
11956 	mtx_assert(&lun->lun_lock, MA_OWNED);
11957 
11958 	/*
11959 	 * Run through the OOA queue and attempt to find the given I/O.
11960 	 * The target port, initiator ID, tag type and tag number have to
11961 	 * match the values that we got from the initiator.  If we have an
11962 	 * untagged command to abort, simply abort the first untagged command
11963 	 * we come to.  We only allow one untagged command at a time of course.
11964 	 */
11965 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11966 		union ctl_io *xio = (union ctl_io *)xioh;
11967 		if ((targ_port == UINT32_MAX ||
11968 		     targ_port == xioh->nexus.targ_port) &&
11969 		    (init_id == UINT32_MAX ||
11970 		     init_id == xioh->nexus.initid)) {
11971 			if (targ_port != xioh->nexus.targ_port ||
11972 			    init_id != xioh->nexus.initid)
11973 				xioh->flags |= CTL_FLAG_ABORT_STATUS;
11974 			xioh->flags |= CTL_FLAG_ABORT;
11975 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11976 				union ctl_ha_msg msg_info;
11977 
11978 				msg_info.hdr.nexus = xioh->nexus;
11979 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11980 				msg_info.task.tag_num = xio->scsiio.tag_num;
11981 				msg_info.task.tag_type = xio->scsiio.tag_type;
11982 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11983 				msg_info.hdr.original_sc = NULL;
11984 				msg_info.hdr.serializing_sc = NULL;
11985 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11986 				    sizeof(msg_info.task), M_NOWAIT);
11987 			}
11988 			ctl_try_unblock_io(lun, xio, FALSE);
11989 		}
11990 	}
11991 }
11992 
11993 static int
11994 ctl_abort_task_set(union ctl_io *io)
11995 {
11996 	struct ctl_softc *softc = CTL_SOFTC(io);
11997 	struct ctl_lun *lun;
11998 	uint32_t targ_lun;
11999 
12000 	/*
12001 	 * Look up the LUN.
12002 	 */
12003 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12004 	mtx_lock(&softc->ctl_lock);
12005 	if (targ_lun >= ctl_max_luns ||
12006 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12007 		mtx_unlock(&softc->ctl_lock);
12008 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12009 		return (1);
12010 	}
12011 
12012 	mtx_lock(&lun->lun_lock);
12013 	mtx_unlock(&softc->ctl_lock);
12014 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12015 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12016 		    io->io_hdr.nexus.initid,
12017 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12018 	} else { /* CTL_TASK_CLEAR_TASK_SET */
12019 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12020 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12021 	}
12022 	mtx_unlock(&lun->lun_lock);
12023 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12024 	return (0);
12025 }
12026 
12027 static void
12028 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
12029     ctl_ua_type ua_type)
12030 {
12031 	struct ctl_lun *lun;
12032 	struct scsi_sense_data *ps;
12033 	uint32_t p, i;
12034 
12035 	p = initidx / CTL_MAX_INIT_PER_PORT;
12036 	i = initidx % CTL_MAX_INIT_PER_PORT;
12037 	mtx_lock(&softc->ctl_lock);
12038 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12039 		mtx_lock(&lun->lun_lock);
12040 		/* Abort tasks. */
12041 		ctl_abort_tasks_lun(lun, p, i, 1);
12042 		/* Clear CA. */
12043 		ps = lun->pending_sense[p];
12044 		if (ps != NULL)
12045 			ps[i].error_code = 0;
12046 		/* Clear reservation. */
12047 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12048 			lun->flags &= ~CTL_LUN_RESERVED;
12049 		/* Clear prevent media removal. */
12050 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
12051 			ctl_clear_mask(lun->prevent, initidx);
12052 			lun->prevent_count--;
12053 		}
12054 		/* Clear TPC status */
12055 		ctl_tpc_lun_clear(lun, initidx);
12056 		/* Establish UA. */
12057 		ctl_est_ua(lun, initidx, ua_type);
12058 		mtx_unlock(&lun->lun_lock);
12059 	}
12060 	mtx_unlock(&softc->ctl_lock);
12061 }
12062 
12063 static int
12064 ctl_i_t_nexus_reset(union ctl_io *io)
12065 {
12066 	struct ctl_softc *softc = CTL_SOFTC(io);
12067 	uint32_t initidx;
12068 
12069 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12070 		union ctl_ha_msg msg_info;
12071 
12072 		msg_info.hdr.nexus = io->io_hdr.nexus;
12073 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12074 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12075 		msg_info.hdr.original_sc = NULL;
12076 		msg_info.hdr.serializing_sc = NULL;
12077 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12078 		    sizeof(msg_info.task), M_WAITOK);
12079 	}
12080 
12081 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12082 	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
12083 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12084 	return (0);
12085 }
12086 
12087 static int
12088 ctl_abort_task(union ctl_io *io)
12089 {
12090 	struct ctl_softc *softc = CTL_SOFTC(io);
12091 	struct ctl_io_hdr *xioh;
12092 	struct ctl_lun *lun;
12093 	uint32_t targ_lun;
12094 
12095 	/*
12096 	 * Look up the LUN.
12097 	 */
12098 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12099 	mtx_lock(&softc->ctl_lock);
12100 	if (targ_lun >= ctl_max_luns ||
12101 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12102 		mtx_unlock(&softc->ctl_lock);
12103 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12104 		return (1);
12105 	}
12106 
12107 	mtx_lock(&lun->lun_lock);
12108 	mtx_unlock(&softc->ctl_lock);
12109 	/*
12110 	 * Run through the OOA queue and attempt to find the given I/O.
12111 	 * The target port, initiator ID, tag type and tag number have to
12112 	 * match the values that we got from the initiator.  If we have an
12113 	 * untagged command to abort, simply abort the first untagged command
12114 	 * we come to.  We only allow one untagged command at a time of course.
12115 	 */
12116 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12117 		union ctl_io *xio = (union ctl_io *)xioh;
12118 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12119 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12120 		 || (xioh->flags & CTL_FLAG_ABORT))
12121 			continue;
12122 
12123 		/*
12124 		 * If the abort says that the task is untagged, the
12125 		 * task in the queue must be untagged.  Otherwise,
12126 		 * we just check to see whether the tag numbers
12127 		 * match.  This is because the QLogic firmware
12128 		 * doesn't pass back the tag type in an abort
12129 		 * request.
12130 		 */
12131 #if 0
12132 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12133 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12134 		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12135 #else
12136 		/*
12137 		 * XXX KDM we've got problems with FC, because it
12138 		 * doesn't send down a tag type with aborts.  So we
12139 		 * can only really go by the tag number...
12140 		 * This may cause problems with parallel SCSI.
12141 		 * Need to figure that out!!
12142 		 */
12143 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12144 #endif
12145 			xioh->flags |= CTL_FLAG_ABORT;
12146 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12147 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12148 				union ctl_ha_msg msg_info;
12149 
12150 				msg_info.hdr.nexus = io->io_hdr.nexus;
12151 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12152 				msg_info.task.tag_num = io->taskio.tag_num;
12153 				msg_info.task.tag_type = io->taskio.tag_type;
12154 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12155 				msg_info.hdr.original_sc = NULL;
12156 				msg_info.hdr.serializing_sc = NULL;
12157 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12158 				    sizeof(msg_info.task), M_NOWAIT);
12159 			}
12160 			ctl_try_unblock_io(lun, xio, FALSE);
12161 		}
12162 	}
12163 	mtx_unlock(&lun->lun_lock);
12164 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12165 	return (0);
12166 }
12167 
12168 static int
12169 ctl_query_task(union ctl_io *io, int task_set)
12170 {
12171 	struct ctl_softc *softc = CTL_SOFTC(io);
12172 	struct ctl_io_hdr *xioh;
12173 	struct ctl_lun *lun;
12174 	int found = 0;
12175 	uint32_t targ_lun;
12176 
12177 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12178 	mtx_lock(&softc->ctl_lock);
12179 	if (targ_lun >= ctl_max_luns ||
12180 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12181 		mtx_unlock(&softc->ctl_lock);
12182 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12183 		return (1);
12184 	}
12185 	mtx_lock(&lun->lun_lock);
12186 	mtx_unlock(&softc->ctl_lock);
12187 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12188 		union ctl_io *xio = (union ctl_io *)xioh;
12189 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12190 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12191 		 || (xioh->flags & CTL_FLAG_ABORT))
12192 			continue;
12193 
12194 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12195 			found = 1;
12196 			break;
12197 		}
12198 	}
12199 	mtx_unlock(&lun->lun_lock);
12200 	if (found)
12201 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12202 	else
12203 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12204 	return (0);
12205 }
12206 
12207 static int
12208 ctl_query_async_event(union ctl_io *io)
12209 {
12210 	struct ctl_softc *softc = CTL_SOFTC(io);
12211 	struct ctl_lun *lun;
12212 	ctl_ua_type ua;
12213 	uint32_t targ_lun, initidx;
12214 
12215 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12216 	mtx_lock(&softc->ctl_lock);
12217 	if (targ_lun >= ctl_max_luns ||
12218 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12219 		mtx_unlock(&softc->ctl_lock);
12220 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12221 		return (1);
12222 	}
12223 	mtx_lock(&lun->lun_lock);
12224 	mtx_unlock(&softc->ctl_lock);
12225 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12226 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12227 	mtx_unlock(&lun->lun_lock);
12228 	if (ua != CTL_UA_NONE)
12229 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12230 	else
12231 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12232 	return (0);
12233 }
12234 
12235 static void
12236 ctl_run_task(union ctl_io *io)
12237 {
12238 	int retval = 1;
12239 
12240 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12241 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12242 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12243 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12244 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12245 	switch (io->taskio.task_action) {
12246 	case CTL_TASK_ABORT_TASK:
12247 		retval = ctl_abort_task(io);
12248 		break;
12249 	case CTL_TASK_ABORT_TASK_SET:
12250 	case CTL_TASK_CLEAR_TASK_SET:
12251 		retval = ctl_abort_task_set(io);
12252 		break;
12253 	case CTL_TASK_CLEAR_ACA:
12254 		break;
12255 	case CTL_TASK_I_T_NEXUS_RESET:
12256 		retval = ctl_i_t_nexus_reset(io);
12257 		break;
12258 	case CTL_TASK_LUN_RESET:
12259 		retval = ctl_lun_reset(io);
12260 		break;
12261 	case CTL_TASK_TARGET_RESET:
12262 	case CTL_TASK_BUS_RESET:
12263 		retval = ctl_target_reset(io);
12264 		break;
12265 	case CTL_TASK_PORT_LOGIN:
12266 		break;
12267 	case CTL_TASK_PORT_LOGOUT:
12268 		break;
12269 	case CTL_TASK_QUERY_TASK:
12270 		retval = ctl_query_task(io, 0);
12271 		break;
12272 	case CTL_TASK_QUERY_TASK_SET:
12273 		retval = ctl_query_task(io, 1);
12274 		break;
12275 	case CTL_TASK_QUERY_ASYNC_EVENT:
12276 		retval = ctl_query_async_event(io);
12277 		break;
12278 	default:
12279 		printf("%s: got unknown task management event %d\n",
12280 		       __func__, io->taskio.task_action);
12281 		break;
12282 	}
12283 	if (retval == 0)
12284 		io->io_hdr.status = CTL_SUCCESS;
12285 	else
12286 		io->io_hdr.status = CTL_ERROR;
12287 	ctl_done(io);
12288 }
12289 
12290 /*
12291  * For HA operation.  Handle commands that come in from the other
12292  * controller.
12293  */
12294 static void
12295 ctl_handle_isc(union ctl_io *io)
12296 {
12297 	struct ctl_softc *softc = CTL_SOFTC(io);
12298 	struct ctl_lun *lun;
12299 	const struct ctl_cmd_entry *entry;
12300 	uint32_t targ_lun;
12301 
12302 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12303 	switch (io->io_hdr.msg_type) {
12304 	case CTL_MSG_SERIALIZE:
12305 		ctl_serialize_other_sc_cmd(&io->scsiio);
12306 		break;
12307 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12308 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12309 		if (targ_lun >= ctl_max_luns ||
12310 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12311 			ctl_done(io);
12312 			break;
12313 		}
12314 		mtx_lock(&lun->lun_lock);
12315 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12316 			mtx_unlock(&lun->lun_lock);
12317 			ctl_done(io);
12318 			break;
12319 		}
12320 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12321 		mtx_unlock(&lun->lun_lock);
12322 		ctl_enqueue_rtr(io);
12323 		break;
12324 	case CTL_MSG_FINISH_IO:
12325 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12326 			ctl_done(io);
12327 			break;
12328 		}
12329 		if (targ_lun >= ctl_max_luns ||
12330 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12331 			ctl_free_io(io);
12332 			break;
12333 		}
12334 		mtx_lock(&lun->lun_lock);
12335 		ctl_try_unblock_others(lun, io, TRUE);
12336 		LIST_REMOVE(&io->io_hdr, ooa_links);
12337 		mtx_unlock(&lun->lun_lock);
12338 		ctl_free_io(io);
12339 		break;
12340 	case CTL_MSG_PERS_ACTION:
12341 		ctl_hndl_per_res_out_on_other_sc(io);
12342 		ctl_free_io(io);
12343 		break;
12344 	case CTL_MSG_BAD_JUJU:
12345 		ctl_done(io);
12346 		break;
12347 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12348 		ctl_datamove_remote(io);
12349 		break;
12350 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12351 		ctl_datamove_done(io, false);
12352 		break;
12353 	case CTL_MSG_FAILOVER:
12354 		ctl_failover_lun(io);
12355 		ctl_free_io(io);
12356 		break;
12357 	default:
12358 		printf("%s: Invalid message type %d\n",
12359 		       __func__, io->io_hdr.msg_type);
12360 		ctl_free_io(io);
12361 		break;
12362 	}
12363 
12364 }
12365 
12366 /*
12367  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12368  * there is no match.
12369  */
12370 static ctl_lun_error_pattern
12371 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12372 {
12373 	const struct ctl_cmd_entry *entry;
12374 	ctl_lun_error_pattern filtered_pattern, pattern;
12375 
12376 	pattern = desc->error_pattern;
12377 
12378 	/*
12379 	 * XXX KDM we need more data passed into this function to match a
12380 	 * custom pattern, and we actually need to implement custom pattern
12381 	 * matching.
12382 	 */
12383 	if (pattern & CTL_LUN_PAT_CMD)
12384 		return (CTL_LUN_PAT_CMD);
12385 
12386 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12387 		return (CTL_LUN_PAT_ANY);
12388 
12389 	entry = ctl_get_cmd_entry(ctsio, NULL);
12390 
12391 	filtered_pattern = entry->pattern & pattern;
12392 
12393 	/*
12394 	 * If the user requested specific flags in the pattern (e.g.
12395 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12396 	 * flags.
12397 	 *
12398 	 * If the user did not specify any flags, it doesn't matter whether
12399 	 * or not the command supports the flags.
12400 	 */
12401 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12402 	     (pattern & ~CTL_LUN_PAT_MASK))
12403 		return (CTL_LUN_PAT_NONE);
12404 
12405 	/*
12406 	 * If the user asked for a range check, see if the requested LBA
12407 	 * range overlaps with this command's LBA range.
12408 	 */
12409 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12410 		uint64_t lba1;
12411 		uint64_t len1;
12412 		ctl_action action;
12413 		int retval;
12414 
12415 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12416 		if (retval != 0)
12417 			return (CTL_LUN_PAT_NONE);
12418 
12419 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12420 					      desc->lba_range.len, FALSE);
12421 		/*
12422 		 * A "pass" means that the LBA ranges don't overlap, so
12423 		 * this doesn't match the user's range criteria.
12424 		 */
12425 		if (action == CTL_ACTION_PASS)
12426 			return (CTL_LUN_PAT_NONE);
12427 	}
12428 
12429 	return (filtered_pattern);
12430 }
12431 
12432 static void
12433 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12434 {
12435 	struct ctl_error_desc *desc, *desc2;
12436 
12437 	mtx_assert(&lun->lun_lock, MA_OWNED);
12438 
12439 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12440 		ctl_lun_error_pattern pattern;
12441 		/*
12442 		 * Check to see whether this particular command matches
12443 		 * the pattern in the descriptor.
12444 		 */
12445 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12446 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12447 			continue;
12448 
12449 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12450 		case CTL_LUN_INJ_ABORTED:
12451 			ctl_set_aborted(&io->scsiio);
12452 			break;
12453 		case CTL_LUN_INJ_MEDIUM_ERR:
12454 			ctl_set_medium_error(&io->scsiio,
12455 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12456 			     CTL_FLAG_DATA_OUT);
12457 			break;
12458 		case CTL_LUN_INJ_UA:
12459 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12460 			 * OCCURRED */
12461 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12462 			break;
12463 		case CTL_LUN_INJ_CUSTOM:
12464 			/*
12465 			 * We're assuming the user knows what he is doing.
12466 			 * Just copy the sense information without doing
12467 			 * checks.
12468 			 */
12469 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12470 			      MIN(sizeof(desc->custom_sense),
12471 				  sizeof(io->scsiio.sense_data)));
12472 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12473 			io->scsiio.sense_len = SSD_FULL_SIZE;
12474 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12475 			break;
12476 		case CTL_LUN_INJ_NONE:
12477 		default:
12478 			/*
12479 			 * If this is an error injection type we don't know
12480 			 * about, clear the continuous flag (if it is set)
12481 			 * so it will get deleted below.
12482 			 */
12483 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12484 			break;
12485 		}
12486 		/*
12487 		 * By default, each error injection action is a one-shot
12488 		 */
12489 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12490 			continue;
12491 
12492 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12493 
12494 		free(desc, M_CTL);
12495 	}
12496 }
12497 
12498 #ifdef CTL_IO_DELAY
12499 static void
12500 ctl_datamove_timer_wakeup(void *arg)
12501 {
12502 	union ctl_io *io;
12503 
12504 	io = (union ctl_io *)arg;
12505 
12506 	ctl_datamove(io);
12507 }
12508 #endif /* CTL_IO_DELAY */
12509 
12510 static void
12511 ctl_datamove_done_process(union ctl_io *io)
12512 {
12513 #ifdef CTL_TIME_IO
12514 	struct bintime cur_bt;
12515 #endif
12516 
12517 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
12518 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
12519 
12520 #ifdef CTL_TIME_IO
12521 	getbinuptime(&cur_bt);
12522 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12523 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12524 #endif
12525 	io->io_hdr.num_dmas++;
12526 
12527 	if ((io->io_hdr.port_status != 0) &&
12528 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
12529 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
12530 		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
12531 		    /*retry_count*/ io->io_hdr.port_status);
12532 	} else if (io->scsiio.kern_data_resid != 0 &&
12533 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
12534 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
12535 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
12536 		ctl_set_invalid_field_ciu(&io->scsiio);
12537 	} else if (ctl_debug & CTL_DEBUG_CDB_DATA)
12538 		ctl_data_print(io);
12539 }
12540 
12541 void
12542 ctl_datamove_done(union ctl_io *io, bool samethr)
12543 {
12544 
12545 	ctl_datamove_done_process(io);
12546 	io->scsiio.be_move_done(io, samethr);
12547 }
12548 
12549 void
12550 ctl_datamove(union ctl_io *io)
12551 {
12552 	void (*fe_datamove)(union ctl_io *io);
12553 
12554 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12555 
12556 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12557 
12558 	/* No data transferred yet.  Frontend must update this when done. */
12559 	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12560 
12561 #ifdef CTL_TIME_IO
12562 	getbinuptime(&io->io_hdr.dma_start_bt);
12563 #endif /* CTL_TIME_IO */
12564 
12565 #ifdef CTL_IO_DELAY
12566 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12567 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12568 	} else {
12569 		struct ctl_lun *lun;
12570 
12571 		lun = CTL_LUN(io);
12572 		if ((lun != NULL)
12573 		 && (lun->delay_info.datamove_delay > 0)) {
12574 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12575 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12576 			callout_reset(&io->io_hdr.delay_callout,
12577 				      lun->delay_info.datamove_delay * hz,
12578 				      ctl_datamove_timer_wakeup, io);
12579 			if (lun->delay_info.datamove_type ==
12580 			    CTL_DELAY_TYPE_ONESHOT)
12581 				lun->delay_info.datamove_delay = 0;
12582 			return;
12583 		}
12584 	}
12585 #endif
12586 
12587 	/*
12588 	 * This command has been aborted.  Set the port status, so we fail
12589 	 * the data move.
12590 	 */
12591 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12592 		printf("ctl_datamove: tag 0x%jx on (%u:%u:%u) aborted\n",
12593 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12594 		       io->io_hdr.nexus.targ_port,
12595 		       io->io_hdr.nexus.targ_lun);
12596 		io->io_hdr.port_status = 31337;
12597 		ctl_datamove_done_process(io);
12598 		io->scsiio.be_move_done(io, true);
12599 		return;
12600 	}
12601 
12602 	/* Don't confuse frontend with zero length data move. */
12603 	if (io->scsiio.kern_data_len == 0) {
12604 		ctl_datamove_done_process(io);
12605 		io->scsiio.be_move_done(io, true);
12606 		return;
12607 	}
12608 
12609 	fe_datamove = CTL_PORT(io)->fe_datamove;
12610 	fe_datamove(io);
12611 }
12612 
12613 static void
12614 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12615 {
12616 	union ctl_ha_msg msg;
12617 #ifdef CTL_TIME_IO
12618 	struct bintime cur_bt;
12619 #endif
12620 
12621 	memset(&msg, 0, sizeof(msg));
12622 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12623 	msg.hdr.original_sc = io;
12624 	msg.hdr.serializing_sc = io->io_hdr.remote_io;
12625 	msg.hdr.nexus = io->io_hdr.nexus;
12626 	msg.hdr.status = io->io_hdr.status;
12627 	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12628 	msg.scsi.tag_num = io->scsiio.tag_num;
12629 	msg.scsi.tag_type = io->scsiio.tag_type;
12630 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12631 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12632 	       io->scsiio.sense_len);
12633 	msg.scsi.sense_len = io->scsiio.sense_len;
12634 	msg.scsi.port_status = io->io_hdr.port_status;
12635 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12636 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12637 		ctl_failover_io(io, /*have_lock*/ have_lock);
12638 		return;
12639 	}
12640 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12641 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12642 	    msg.scsi.sense_len, M_WAITOK);
12643 
12644 #ifdef CTL_TIME_IO
12645 	getbinuptime(&cur_bt);
12646 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12647 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12648 #endif
12649 	io->io_hdr.num_dmas++;
12650 }
12651 
12652 /*
12653  * The DMA to the remote side is done, now we need to tell the other side
12654  * we're done so it can continue with its data movement.
12655  */
12656 static void
12657 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12658 {
12659 	union ctl_io *io;
12660 	uint32_t i;
12661 
12662 	io = rq->context;
12663 
12664 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12665 		printf("%s: ISC DMA write failed with error %d", __func__,
12666 		       rq->ret);
12667 		ctl_set_internal_failure(&io->scsiio,
12668 					 /*sks_valid*/ 1,
12669 					 /*retry_count*/ rq->ret);
12670 	}
12671 
12672 	ctl_dt_req_free(rq);
12673 
12674 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12675 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12676 	free(CTL_RSGL(io), M_CTL);
12677 	CTL_RSGL(io) = NULL;
12678 	CTL_LSGL(io) = NULL;
12679 
12680 	/*
12681 	 * The data is in local and remote memory, so now we need to send
12682 	 * status (good or back) back to the other side.
12683 	 */
12684 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12685 }
12686 
12687 /*
12688  * We've moved the data from the host/controller into local memory.  Now we
12689  * need to push it over to the remote controller's memory.
12690  */
12691 static int
12692 ctl_datamove_remote_dm_write_cb(union ctl_io *io, bool samethr)
12693 {
12694 	int retval;
12695 
12696 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12697 					  ctl_datamove_remote_write_cb);
12698 	return (retval);
12699 }
12700 
12701 static void
12702 ctl_datamove_remote_write(union ctl_io *io)
12703 {
12704 	int retval;
12705 	void (*fe_datamove)(union ctl_io *io);
12706 
12707 	/*
12708 	 * - Get the data from the host/HBA into local memory.
12709 	 * - DMA memory from the local controller to the remote controller.
12710 	 * - Send status back to the remote controller.
12711 	 */
12712 
12713 	retval = ctl_datamove_remote_sgl_setup(io);
12714 	if (retval != 0)
12715 		return;
12716 
12717 	/* Switch the pointer over so the FETD knows what to do */
12718 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12719 
12720 	/*
12721 	 * Use a custom move done callback, since we need to send completion
12722 	 * back to the other controller, not to the backend on this side.
12723 	 */
12724 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12725 
12726 	fe_datamove = CTL_PORT(io)->fe_datamove;
12727 	fe_datamove(io);
12728 }
12729 
12730 static int
12731 ctl_datamove_remote_dm_read_cb(union ctl_io *io, bool samethr)
12732 {
12733 	uint32_t i;
12734 
12735 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12736 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12737 	free(CTL_RSGL(io), M_CTL);
12738 	CTL_RSGL(io) = NULL;
12739 	CTL_LSGL(io) = NULL;
12740 
12741 	/*
12742 	 * The read is done, now we need to send status (good or bad) back
12743 	 * to the other side.
12744 	 */
12745 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12746 
12747 	return (0);
12748 }
12749 
12750 static void
12751 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12752 {
12753 	union ctl_io *io;
12754 	void (*fe_datamove)(union ctl_io *io);
12755 
12756 	io = rq->context;
12757 
12758 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12759 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12760 		       rq->ret);
12761 		ctl_set_internal_failure(&io->scsiio,
12762 					 /*sks_valid*/ 1,
12763 					 /*retry_count*/ rq->ret);
12764 	}
12765 
12766 	ctl_dt_req_free(rq);
12767 
12768 	/* Switch the pointer over so the FETD knows what to do */
12769 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12770 
12771 	/*
12772 	 * Use a custom move done callback, since we need to send completion
12773 	 * back to the other controller, not to the backend on this side.
12774 	 */
12775 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12776 
12777 	/* XXX KDM add checks like the ones in ctl_datamove? */
12778 
12779 	fe_datamove = CTL_PORT(io)->fe_datamove;
12780 	fe_datamove(io);
12781 }
12782 
12783 static int
12784 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12785 {
12786 	struct ctl_sg_entry *local_sglist;
12787 	uint32_t len_to_go;
12788 	int retval;
12789 	int i;
12790 
12791 	retval = 0;
12792 	local_sglist = CTL_LSGL(io);
12793 	len_to_go = io->scsiio.kern_data_len;
12794 
12795 	/*
12796 	 * The difficult thing here is that the size of the various
12797 	 * S/G segments may be different than the size from the
12798 	 * remote controller.  That'll make it harder when DMAing
12799 	 * the data back to the other side.
12800 	 */
12801 	for (i = 0; len_to_go > 0; i++) {
12802 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12803 		local_sglist[i].addr =
12804 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12805 
12806 		len_to_go -= local_sglist[i].len;
12807 	}
12808 	/*
12809 	 * Reset the number of S/G entries accordingly.  The original
12810 	 * number of S/G entries is available in rem_sg_entries.
12811 	 */
12812 	io->scsiio.kern_sg_entries = i;
12813 
12814 	return (retval);
12815 }
12816 
12817 static int
12818 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12819 			 ctl_ha_dt_cb callback)
12820 {
12821 	struct ctl_ha_dt_req *rq;
12822 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12823 	uint32_t local_used, remote_used, total_used;
12824 	int i, j, isc_ret;
12825 
12826 	rq = ctl_dt_req_alloc();
12827 
12828 	/*
12829 	 * If we failed to allocate the request, and if the DMA didn't fail
12830 	 * anyway, set busy status.  This is just a resource allocation
12831 	 * failure.
12832 	 */
12833 	if ((rq == NULL)
12834 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12835 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12836 		ctl_set_busy(&io->scsiio);
12837 
12838 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12839 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12840 		if (rq != NULL)
12841 			ctl_dt_req_free(rq);
12842 
12843 		/*
12844 		 * The data move failed.  We need to return status back
12845 		 * to the other controller.  No point in trying to DMA
12846 		 * data to the remote controller.
12847 		 */
12848 
12849 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12850 
12851 		return (1);
12852 	}
12853 
12854 	local_sglist = CTL_LSGL(io);
12855 	remote_sglist = CTL_RSGL(io);
12856 	local_used = 0;
12857 	remote_used = 0;
12858 	total_used = 0;
12859 
12860 	/*
12861 	 * Pull/push the data over the wire from/to the other controller.
12862 	 * This takes into account the possibility that the local and
12863 	 * remote sglists may not be identical in terms of the size of
12864 	 * the elements and the number of elements.
12865 	 *
12866 	 * One fundamental assumption here is that the length allocated for
12867 	 * both the local and remote sglists is identical.  Otherwise, we've
12868 	 * essentially got a coding error of some sort.
12869 	 */
12870 	isc_ret = CTL_HA_STATUS_SUCCESS;
12871 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12872 		uint32_t cur_len;
12873 		uint8_t *tmp_ptr;
12874 
12875 		rq->command = command;
12876 		rq->context = io;
12877 
12878 		/*
12879 		 * Both pointers should be aligned.  But it is possible
12880 		 * that the allocation length is not.  They should both
12881 		 * also have enough slack left over at the end, though,
12882 		 * to round up to the next 8 byte boundary.
12883 		 */
12884 		cur_len = MIN(local_sglist[i].len - local_used,
12885 			      remote_sglist[j].len - remote_used);
12886 		rq->size = cur_len;
12887 
12888 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12889 		tmp_ptr += local_used;
12890 
12891 #if 0
12892 		/* Use physical addresses when talking to ISC hardware */
12893 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12894 			/* XXX KDM use busdma */
12895 			rq->local = vtophys(tmp_ptr);
12896 		} else
12897 			rq->local = tmp_ptr;
12898 #else
12899 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12900 		    ("HA does not support BUS_ADDR"));
12901 		rq->local = tmp_ptr;
12902 #endif
12903 
12904 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12905 		tmp_ptr += remote_used;
12906 		rq->remote = tmp_ptr;
12907 
12908 		rq->callback = NULL;
12909 
12910 		local_used += cur_len;
12911 		if (local_used >= local_sglist[i].len) {
12912 			i++;
12913 			local_used = 0;
12914 		}
12915 
12916 		remote_used += cur_len;
12917 		if (remote_used >= remote_sglist[j].len) {
12918 			j++;
12919 			remote_used = 0;
12920 		}
12921 		total_used += cur_len;
12922 
12923 		if (total_used >= io->scsiio.kern_data_len)
12924 			rq->callback = callback;
12925 
12926 		isc_ret = ctl_dt_single(rq);
12927 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12928 			break;
12929 	}
12930 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12931 		rq->ret = isc_ret;
12932 		callback(rq);
12933 	}
12934 
12935 	return (0);
12936 }
12937 
12938 static void
12939 ctl_datamove_remote_read(union ctl_io *io)
12940 {
12941 	int retval;
12942 	uint32_t i;
12943 
12944 	/*
12945 	 * This will send an error to the other controller in the case of a
12946 	 * failure.
12947 	 */
12948 	retval = ctl_datamove_remote_sgl_setup(io);
12949 	if (retval != 0)
12950 		return;
12951 
12952 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12953 					  ctl_datamove_remote_read_cb);
12954 	if (retval != 0) {
12955 		/*
12956 		 * Make sure we free memory if there was an error..  The
12957 		 * ctl_datamove_remote_xfer() function will send the
12958 		 * datamove done message, or call the callback with an
12959 		 * error if there is a problem.
12960 		 */
12961 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12962 			free(CTL_LSGLT(io)[i].addr, M_CTL);
12963 		free(CTL_RSGL(io), M_CTL);
12964 		CTL_RSGL(io) = NULL;
12965 		CTL_LSGL(io) = NULL;
12966 	}
12967 }
12968 
12969 /*
12970  * Process a datamove request from the other controller.  This is used for
12971  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12972  * first.  Once that is complete, the data gets DMAed into the remote
12973  * controller's memory.  For reads, we DMA from the remote controller's
12974  * memory into our memory first, and then move it out to the FETD.
12975  */
12976 static void
12977 ctl_datamove_remote(union ctl_io *io)
12978 {
12979 
12980 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12981 
12982 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12983 		ctl_failover_io(io, /*have_lock*/ 0);
12984 		return;
12985 	}
12986 
12987 	/*
12988 	 * Note that we look for an aborted I/O here, but don't do some of
12989 	 * the other checks that ctl_datamove() normally does.
12990 	 * We don't need to run the datamove delay code, since that should
12991 	 * have been done if need be on the other controller.
12992 	 */
12993 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12994 		printf("%s: tag 0x%jx on (%u:%u:%u) aborted\n", __func__,
12995 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12996 		       io->io_hdr.nexus.targ_port,
12997 		       io->io_hdr.nexus.targ_lun);
12998 		io->io_hdr.port_status = 31338;
12999 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13000 		return;
13001 	}
13002 
13003 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13004 		ctl_datamove_remote_write(io);
13005 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13006 		ctl_datamove_remote_read(io);
13007 	else {
13008 		io->io_hdr.port_status = 31339;
13009 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13010 	}
13011 }
13012 
13013 static void
13014 ctl_process_done(union ctl_io *io)
13015 {
13016 	struct ctl_softc *softc = CTL_SOFTC(io);
13017 	struct ctl_port *port = CTL_PORT(io);
13018 	struct ctl_lun *lun = CTL_LUN(io);
13019 	void (*fe_done)(union ctl_io *io);
13020 	union ctl_ha_msg msg;
13021 
13022 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13023 	fe_done = port->fe_done;
13024 
13025 #ifdef CTL_TIME_IO
13026 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13027 		char str[256];
13028 		char path_str[64];
13029 		struct sbuf sb;
13030 
13031 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13032 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13033 
13034 		ctl_io_sbuf(io, &sb);
13035 		sbuf_cat(&sb, path_str);
13036 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13037 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13038 		sbuf_finish(&sb);
13039 		printf("%s", sbuf_data(&sb));
13040 	}
13041 #endif /* CTL_TIME_IO */
13042 
13043 	switch (io->io_hdr.io_type) {
13044 	case CTL_IO_SCSI:
13045 		break;
13046 	case CTL_IO_TASK:
13047 		if (ctl_debug & CTL_DEBUG_INFO)
13048 			ctl_io_error_print(io, NULL);
13049 		fe_done(io);
13050 		return;
13051 	default:
13052 		panic("%s: Invalid CTL I/O type %d\n",
13053 		    __func__, io->io_hdr.io_type);
13054 	}
13055 
13056 	if (lun == NULL) {
13057 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13058 				 io->io_hdr.nexus.targ_mapped_lun));
13059 		goto bailout;
13060 	}
13061 
13062 	mtx_lock(&lun->lun_lock);
13063 
13064 	/*
13065 	 * Check to see if we have any informational exception and status
13066 	 * of this command can be modified to report it in form of either
13067 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13068 	 */
13069 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13070 	    io->io_hdr.status == CTL_SUCCESS &&
13071 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13072 		uint8_t mrie = lun->MODE_IE.mrie;
13073 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13074 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13075 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13076 		     mrie == SIEP_MRIE_REC_UNCOND ||
13077 		     mrie == SIEP_MRIE_NO_SENSE) &&
13078 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13079 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13080 			ctl_set_sense(&io->scsiio,
13081 			      /*current_error*/ 1,
13082 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13083 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13084 			      /*asc*/ lun->ie_asc,
13085 			      /*ascq*/ lun->ie_ascq,
13086 			      SSD_ELEM_NONE);
13087 			lun->ie_reported = 1;
13088 		}
13089 	} else if (lun->ie_reported < 0)
13090 		lun->ie_reported = 0;
13091 
13092 	/*
13093 	 * Check to see if we have any errors to inject here.  We only
13094 	 * inject errors for commands that don't already have errors set.
13095 	 */
13096 	if (!STAILQ_EMPTY(&lun->error_list) &&
13097 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13098 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13099 		ctl_inject_error(lun, io);
13100 
13101 	/*
13102 	 * XXX KDM how do we treat commands that aren't completed
13103 	 * successfully?
13104 	 *
13105 	 * XXX KDM should we also track I/O latency?
13106 	 */
13107 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13108 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13109 		int type;
13110 #ifdef CTL_TIME_IO
13111 		struct bintime bt;
13112 
13113 		getbinuptime(&bt);
13114 		bintime_sub(&bt, &io->io_hdr.start_bt);
13115 #endif
13116 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13117 		    CTL_FLAG_DATA_IN)
13118 			type = CTL_STATS_READ;
13119 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13120 		    CTL_FLAG_DATA_OUT)
13121 			type = CTL_STATS_WRITE;
13122 		else
13123 			type = CTL_STATS_NO_IO;
13124 
13125 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
13126 		lun->stats.operations[type] ++;
13127 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13128 #ifdef CTL_TIME_IO
13129 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13130 		bintime_add(&lun->stats.time[type], &bt);
13131 #endif
13132 
13133 		mtx_lock(&port->port_lock);
13134 		port->stats.bytes[type] += io->scsiio.kern_total_len;
13135 		port->stats.operations[type] ++;
13136 		port->stats.dmas[type] += io->io_hdr.num_dmas;
13137 #ifdef CTL_TIME_IO
13138 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13139 		bintime_add(&port->stats.time[type], &bt);
13140 #endif
13141 		mtx_unlock(&port->port_lock);
13142 	}
13143 
13144 	/*
13145 	 * Run through the blocked queue of this I/O and see if anything
13146 	 * can be unblocked, now that this I/O is done and will be removed.
13147 	 * We need to do it before removal to have OOA position to start.
13148 	 */
13149 	ctl_try_unblock_others(lun, io, TRUE);
13150 
13151 	/*
13152 	 * Remove this from the OOA queue.
13153 	 */
13154 	LIST_REMOVE(&io->io_hdr, ooa_links);
13155 #ifdef CTL_TIME_IO
13156 	if (LIST_EMPTY(&lun->ooa_queue))
13157 		lun->last_busy = getsbinuptime();
13158 #endif
13159 
13160 	/*
13161 	 * If the LUN has been invalidated, free it if there is nothing
13162 	 * left on its OOA queue.
13163 	 */
13164 	if ((lun->flags & CTL_LUN_INVALID)
13165 	 && LIST_EMPTY(&lun->ooa_queue)) {
13166 		mtx_unlock(&lun->lun_lock);
13167 		ctl_free_lun(lun);
13168 	} else
13169 		mtx_unlock(&lun->lun_lock);
13170 
13171 bailout:
13172 
13173 	/*
13174 	 * If this command has been aborted, make sure we set the status
13175 	 * properly.  The FETD is responsible for freeing the I/O and doing
13176 	 * whatever it needs to do to clean up its state.
13177 	 */
13178 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13179 		ctl_set_task_aborted(&io->scsiio);
13180 
13181 	/*
13182 	 * If enabled, print command error status.
13183 	 */
13184 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13185 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13186 		ctl_io_error_print(io, NULL);
13187 
13188 	/*
13189 	 * Tell the FETD or the other shelf controller we're done with this
13190 	 * command.  Note that only SCSI commands get to this point.  Task
13191 	 * management commands are completed above.
13192 	 */
13193 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13194 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13195 		memset(&msg, 0, sizeof(msg));
13196 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13197 		msg.hdr.serializing_sc = io->io_hdr.remote_io;
13198 		msg.hdr.nexus = io->io_hdr.nexus;
13199 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13200 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13201 		    M_WAITOK);
13202 	}
13203 
13204 	fe_done(io);
13205 }
13206 
13207 /*
13208  * Front end should call this if it doesn't do autosense.  When the request
13209  * sense comes back in from the initiator, we'll dequeue this and send it.
13210  */
13211 int
13212 ctl_queue_sense(union ctl_io *io)
13213 {
13214 	struct ctl_softc *softc = CTL_SOFTC(io);
13215 	struct ctl_port *port = CTL_PORT(io);
13216 	struct ctl_lun *lun;
13217 	struct scsi_sense_data *ps;
13218 	uint32_t initidx, p, targ_lun;
13219 
13220 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13221 
13222 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13223 
13224 	/*
13225 	 * LUN lookup will likely move to the ctl_work_thread() once we
13226 	 * have our new queueing infrastructure (that doesn't put things on
13227 	 * a per-LUN queue initially).  That is so that we can handle
13228 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13229 	 * can't deal with that right now.
13230 	 * If we don't have a LUN for this, just toss the sense information.
13231 	 */
13232 	mtx_lock(&softc->ctl_lock);
13233 	if (targ_lun >= ctl_max_luns ||
13234 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13235 		mtx_unlock(&softc->ctl_lock);
13236 		goto bailout;
13237 	}
13238 	mtx_lock(&lun->lun_lock);
13239 	mtx_unlock(&softc->ctl_lock);
13240 
13241 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13242 	p = initidx / CTL_MAX_INIT_PER_PORT;
13243 	if (lun->pending_sense[p] == NULL) {
13244 		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13245 		    M_CTL, M_NOWAIT | M_ZERO);
13246 	}
13247 	if ((ps = lun->pending_sense[p]) != NULL) {
13248 		ps += initidx % CTL_MAX_INIT_PER_PORT;
13249 		memset(ps, 0, sizeof(*ps));
13250 		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13251 	}
13252 	mtx_unlock(&lun->lun_lock);
13253 
13254 bailout:
13255 	ctl_free_io(io);
13256 	return (CTL_RETVAL_COMPLETE);
13257 }
13258 
13259 /*
13260  * Primary command inlet from frontend ports.  All SCSI and task I/O
13261  * requests must go through this function.
13262  */
13263 int
13264 ctl_queue(union ctl_io *io)
13265 {
13266 	struct ctl_port *port = CTL_PORT(io);
13267 
13268 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13269 
13270 #ifdef CTL_TIME_IO
13271 	io->io_hdr.start_time = time_uptime;
13272 	getbinuptime(&io->io_hdr.start_bt);
13273 #endif /* CTL_TIME_IO */
13274 
13275 	/* Map FE-specific LUN ID into global one. */
13276 	io->io_hdr.nexus.targ_mapped_lun =
13277 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13278 
13279 	switch (io->io_hdr.io_type) {
13280 	case CTL_IO_SCSI:
13281 	case CTL_IO_TASK:
13282 		if (ctl_debug & CTL_DEBUG_CDB)
13283 			ctl_io_print(io);
13284 		ctl_enqueue_incoming(io);
13285 		break;
13286 	default:
13287 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13288 		return (EINVAL);
13289 	}
13290 
13291 	return (CTL_RETVAL_COMPLETE);
13292 }
13293 
13294 int
13295 ctl_run(union ctl_io *io)
13296 {
13297 	struct ctl_port *port = CTL_PORT(io);
13298 
13299 	CTL_DEBUG_PRINT(("ctl_run cdb[0]=%02X\n", io->scsiio.cdb[0]));
13300 
13301 #ifdef CTL_TIME_IO
13302 	io->io_hdr.start_time = time_uptime;
13303 	getbinuptime(&io->io_hdr.start_bt);
13304 #endif /* CTL_TIME_IO */
13305 
13306 	/* Map FE-specific LUN ID into global one. */
13307 	io->io_hdr.nexus.targ_mapped_lun =
13308 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13309 
13310 	switch (io->io_hdr.io_type) {
13311 	case CTL_IO_SCSI:
13312 		if (ctl_debug & CTL_DEBUG_CDB)
13313 			ctl_io_print(io);
13314 		ctl_scsiio_precheck(&io->scsiio);
13315 		break;
13316 	case CTL_IO_TASK:
13317 		if (ctl_debug & CTL_DEBUG_CDB)
13318 			ctl_io_print(io);
13319 		ctl_run_task(io);
13320 		break;
13321 	default:
13322 		printf("ctl_run: unknown I/O type %d\n", io->io_hdr.io_type);
13323 		return (EINVAL);
13324 	}
13325 
13326 	return (CTL_RETVAL_COMPLETE);
13327 }
13328 
13329 #ifdef CTL_IO_DELAY
13330 static void
13331 ctl_done_timer_wakeup(void *arg)
13332 {
13333 	union ctl_io *io;
13334 
13335 	io = (union ctl_io *)arg;
13336 	ctl_done(io);
13337 }
13338 #endif /* CTL_IO_DELAY */
13339 
13340 void
13341 ctl_serseq_done(union ctl_io *io)
13342 {
13343 	struct ctl_lun *lun = CTL_LUN(io);
13344 
13345 	/* This is racy, but should not be a problem. */
13346 	if (!TAILQ_EMPTY(&io->io_hdr.blocked_queue)) {
13347 		mtx_lock(&lun->lun_lock);
13348 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13349 		ctl_try_unblock_others(lun, io, FALSE);
13350 		mtx_unlock(&lun->lun_lock);
13351 	} else
13352 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13353 }
13354 
13355 void
13356 ctl_done(union ctl_io *io)
13357 {
13358 
13359 	/*
13360 	 * Enable this to catch duplicate completion issues.
13361 	 */
13362 #if 0
13363 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13364 		printf("%s: type %d msg %d cdb %x iptl: "
13365 		       "%u:%u:%u tag 0x%04x "
13366 		       "flag %#x status %x\n",
13367 			__func__,
13368 			io->io_hdr.io_type,
13369 			io->io_hdr.msg_type,
13370 			io->scsiio.cdb[0],
13371 			io->io_hdr.nexus.initid,
13372 			io->io_hdr.nexus.targ_port,
13373 			io->io_hdr.nexus.targ_lun,
13374 			(io->io_hdr.io_type ==
13375 			CTL_IO_TASK) ?
13376 			io->taskio.tag_num :
13377 			io->scsiio.tag_num,
13378 		        io->io_hdr.flags,
13379 			io->io_hdr.status);
13380 	} else
13381 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13382 #endif
13383 
13384 	/*
13385 	 * This is an internal copy of an I/O, and should not go through
13386 	 * the normal done processing logic.
13387 	 */
13388 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13389 		return;
13390 
13391 #ifdef CTL_IO_DELAY
13392 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13393 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13394 	} else {
13395 		struct ctl_lun *lun = CTL_LUN(io);
13396 
13397 		if ((lun != NULL)
13398 		 && (lun->delay_info.done_delay > 0)) {
13399 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13400 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13401 			callout_reset(&io->io_hdr.delay_callout,
13402 				      lun->delay_info.done_delay * hz,
13403 				      ctl_done_timer_wakeup, io);
13404 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13405 				lun->delay_info.done_delay = 0;
13406 			return;
13407 		}
13408 	}
13409 #endif /* CTL_IO_DELAY */
13410 
13411 	ctl_enqueue_done(io);
13412 }
13413 
13414 static void
13415 ctl_work_thread(void *arg)
13416 {
13417 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13418 	struct ctl_softc *softc = thr->ctl_softc;
13419 	union ctl_io *io;
13420 	int retval;
13421 
13422 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13423 	thread_lock(curthread);
13424 	sched_prio(curthread, PUSER - 1);
13425 	thread_unlock(curthread);
13426 
13427 	while (!softc->shutdown) {
13428 		/*
13429 		 * We handle the queues in this order:
13430 		 * - ISC
13431 		 * - done queue (to free up resources, unblock other commands)
13432 		 * - incoming queue
13433 		 * - RtR queue
13434 		 *
13435 		 * If those queues are empty, we break out of the loop and
13436 		 * go to sleep.
13437 		 */
13438 		mtx_lock(&thr->queue_lock);
13439 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13440 		if (io != NULL) {
13441 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13442 			mtx_unlock(&thr->queue_lock);
13443 			ctl_handle_isc(io);
13444 			continue;
13445 		}
13446 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13447 		if (io != NULL) {
13448 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13449 			/* clear any blocked commands, call fe_done */
13450 			mtx_unlock(&thr->queue_lock);
13451 			ctl_process_done(io);
13452 			continue;
13453 		}
13454 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13455 		if (io != NULL) {
13456 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13457 			mtx_unlock(&thr->queue_lock);
13458 			if (io->io_hdr.io_type == CTL_IO_TASK)
13459 				ctl_run_task(io);
13460 			else
13461 				ctl_scsiio_precheck(&io->scsiio);
13462 			continue;
13463 		}
13464 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13465 		if (io != NULL) {
13466 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13467 			mtx_unlock(&thr->queue_lock);
13468 			retval = ctl_scsiio(&io->scsiio);
13469 			if (retval != CTL_RETVAL_COMPLETE)
13470 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13471 			continue;
13472 		}
13473 
13474 		/* Sleep until we have something to do. */
13475 		mtx_sleep(thr, &thr->queue_lock, PDROP, "-", 0);
13476 	}
13477 	thr->thread = NULL;
13478 	kthread_exit();
13479 }
13480 
13481 static void
13482 ctl_thresh_thread(void *arg)
13483 {
13484 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13485 	struct ctl_lun *lun;
13486 	struct ctl_logical_block_provisioning_page *page;
13487 	const char *attr;
13488 	union ctl_ha_msg msg;
13489 	uint64_t thres, val;
13490 	int i, e, set;
13491 
13492 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13493 	thread_lock(curthread);
13494 	sched_prio(curthread, PUSER - 1);
13495 	thread_unlock(curthread);
13496 
13497 	while (!softc->shutdown) {
13498 		mtx_lock(&softc->ctl_lock);
13499 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13500 			if ((lun->flags & CTL_LUN_DISABLED) ||
13501 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13502 			    lun->backend->lun_attr == NULL)
13503 				continue;
13504 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13505 			    softc->ha_mode == CTL_HA_MODE_XFER)
13506 				continue;
13507 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13508 				continue;
13509 			e = 0;
13510 			page = &lun->MODE_LBP;
13511 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13512 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13513 					continue;
13514 				thres = scsi_4btoul(page->descr[i].count);
13515 				thres <<= CTL_LBP_EXPONENT;
13516 				switch (page->descr[i].resource) {
13517 				case 0x01:
13518 					attr = "blocksavail";
13519 					break;
13520 				case 0x02:
13521 					attr = "blocksused";
13522 					break;
13523 				case 0xf1:
13524 					attr = "poolblocksavail";
13525 					break;
13526 				case 0xf2:
13527 					attr = "poolblocksused";
13528 					break;
13529 				default:
13530 					continue;
13531 				}
13532 				mtx_unlock(&softc->ctl_lock); // XXX
13533 				val = lun->backend->lun_attr(lun->be_lun, attr);
13534 				mtx_lock(&softc->ctl_lock);
13535 				if (val == UINT64_MAX)
13536 					continue;
13537 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13538 				    == SLBPPD_ARMING_INC)
13539 					e = (val >= thres);
13540 				else
13541 					e = (val <= thres);
13542 				if (e)
13543 					break;
13544 			}
13545 			mtx_lock(&lun->lun_lock);
13546 			if (e) {
13547 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13548 				    (uint8_t *)page, lun->ua_tpt_info);
13549 				if (lun->lasttpt == 0 ||
13550 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13551 					lun->lasttpt = time_uptime;
13552 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13553 					set = 1;
13554 				} else
13555 					set = 0;
13556 			} else {
13557 				lun->lasttpt = 0;
13558 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13559 				set = -1;
13560 			}
13561 			mtx_unlock(&lun->lun_lock);
13562 			if (set != 0 &&
13563 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13564 				/* Send msg to other side. */
13565 				bzero(&msg.ua, sizeof(msg.ua));
13566 				msg.hdr.msg_type = CTL_MSG_UA;
13567 				msg.hdr.nexus.initid = -1;
13568 				msg.hdr.nexus.targ_port = -1;
13569 				msg.hdr.nexus.targ_lun = lun->lun;
13570 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13571 				msg.ua.ua_all = 1;
13572 				msg.ua.ua_set = (set > 0);
13573 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13574 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13575 				mtx_unlock(&softc->ctl_lock); // XXX
13576 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13577 				    sizeof(msg.ua), M_WAITOK);
13578 				mtx_lock(&softc->ctl_lock);
13579 			}
13580 		}
13581 		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13582 		    PDROP, "-", CTL_LBP_PERIOD * hz);
13583 	}
13584 	softc->thresh_thread = NULL;
13585 	kthread_exit();
13586 }
13587 
13588 static void
13589 ctl_enqueue_incoming(union ctl_io *io)
13590 {
13591 	struct ctl_softc *softc = CTL_SOFTC(io);
13592 	struct ctl_thread *thr;
13593 	u_int idx;
13594 
13595 	idx = (io->io_hdr.nexus.targ_port * 127 +
13596 	       io->io_hdr.nexus.initid) % worker_threads;
13597 	thr = &softc->threads[idx];
13598 	mtx_lock(&thr->queue_lock);
13599 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13600 	mtx_unlock(&thr->queue_lock);
13601 	wakeup(thr);
13602 }
13603 
13604 static void
13605 ctl_enqueue_rtr(union ctl_io *io)
13606 {
13607 	struct ctl_softc *softc = CTL_SOFTC(io);
13608 	struct ctl_thread *thr;
13609 
13610 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13611 	mtx_lock(&thr->queue_lock);
13612 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13613 	mtx_unlock(&thr->queue_lock);
13614 	wakeup(thr);
13615 }
13616 
13617 static void
13618 ctl_enqueue_done(union ctl_io *io)
13619 {
13620 	struct ctl_softc *softc = CTL_SOFTC(io);
13621 	struct ctl_thread *thr;
13622 
13623 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13624 	mtx_lock(&thr->queue_lock);
13625 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13626 	mtx_unlock(&thr->queue_lock);
13627 	wakeup(thr);
13628 }
13629 
13630 static void
13631 ctl_enqueue_isc(union ctl_io *io)
13632 {
13633 	struct ctl_softc *softc = CTL_SOFTC(io);
13634 	struct ctl_thread *thr;
13635 
13636 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13637 	mtx_lock(&thr->queue_lock);
13638 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13639 	mtx_unlock(&thr->queue_lock);
13640 	wakeup(thr);
13641 }
13642 
13643 /*
13644  *  vim: ts=8
13645  */
13646