xref: /freebsd/sys/cam/ctl/ctl.c (revision d485c77f203fb0f4cdc08dea5ff81631b51d8809)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
5  * Copyright (c) 2012 The FreeBSD Foundation
6  * Copyright (c) 2014-2017 Alexander Motin <mav@FreeBSD.org>
7  * Copyright (c) 2017 Jakub Wojciech Klama <jceel@FreeBSD.org>
8  * Copyright (c) 2018 Marcelo Araujo <araujo@FreeBSD.org>
9  * All rights reserved.
10  *
11  * Portions of this software were developed by Edward Tomasz Napierala
12  * under sponsorship from the FreeBSD Foundation.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions, and the following disclaimer,
19  *    without modification.
20  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
21  *    substantially similar to the "NO WARRANTY" disclaimer below
22  *    ("Disclaimer") and any redistribution must be conditioned upon
23  *    including a substantially similar Disclaimer requirement for further
24  *    binary redistribution.
25  *
26  * NO WARRANTY
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
35  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
36  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGES.
38  *
39  * $Id$
40  */
41 /*
42  * CAM Target Layer, a SCSI device emulation subsystem.
43  *
44  * Author: Ken Merry <ken@FreeBSD.org>
45  */
46 
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/ctype.h>
53 #include <sys/kernel.h>
54 #include <sys/types.h>
55 #include <sys/kthread.h>
56 #include <sys/bio.h>
57 #include <sys/fcntl.h>
58 #include <sys/lock.h>
59 #include <sys/module.h>
60 #include <sys/mutex.h>
61 #include <sys/condvar.h>
62 #include <sys/malloc.h>
63 #include <sys/conf.h>
64 #include <sys/ioccom.h>
65 #include <sys/queue.h>
66 #include <sys/sbuf.h>
67 #include <sys/smp.h>
68 #include <sys/endian.h>
69 #include <sys/proc.h>
70 #include <sys/sched.h>
71 #include <sys/sysctl.h>
72 #include <sys/nv.h>
73 #include <sys/dnv.h>
74 #include <vm/uma.h>
75 
76 #include <cam/cam.h>
77 #include <cam/scsi/scsi_all.h>
78 #include <cam/scsi/scsi_cd.h>
79 #include <cam/scsi/scsi_da.h>
80 #include <cam/ctl/ctl_io.h>
81 #include <cam/ctl/ctl.h>
82 #include <cam/ctl/ctl_frontend.h>
83 #include <cam/ctl/ctl_util.h>
84 #include <cam/ctl/ctl_backend.h>
85 #include <cam/ctl/ctl_ioctl.h>
86 #include <cam/ctl/ctl_ha.h>
87 #include <cam/ctl/ctl_private.h>
88 #include <cam/ctl/ctl_debug.h>
89 #include <cam/ctl/ctl_scsi_all.h>
90 #include <cam/ctl/ctl_error.h>
91 
92 struct ctl_softc *control_softc = NULL;
93 
94 /*
95  * Template mode pages.
96  */
97 
98 /*
99  * Note that these are default values only.  The actual values will be
100  * filled in when the user does a mode sense.
101  */
102 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
103 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
104 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
105 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
106 	/*read_retry_count*/0,
107 	/*correction_span*/0,
108 	/*head_offset_count*/0,
109 	/*data_strobe_offset_cnt*/0,
110 	/*byte8*/SMS_RWER_LBPERE,
111 	/*write_retry_count*/0,
112 	/*reserved2*/0,
113 	/*recovery_time_limit*/{0, 0},
114 };
115 
116 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
117 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
118 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
119 	/*byte3*/SMS_RWER_PER,
120 	/*read_retry_count*/0,
121 	/*correction_span*/0,
122 	/*head_offset_count*/0,
123 	/*data_strobe_offset_cnt*/0,
124 	/*byte8*/SMS_RWER_LBPERE,
125 	/*write_retry_count*/0,
126 	/*reserved2*/0,
127 	/*recovery_time_limit*/{0, 0},
128 };
129 
130 const static struct scsi_format_page format_page_default = {
131 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
132 	/*page_length*/sizeof(struct scsi_format_page) - 2,
133 	/*tracks_per_zone*/ {0, 0},
134 	/*alt_sectors_per_zone*/ {0, 0},
135 	/*alt_tracks_per_zone*/ {0, 0},
136 	/*alt_tracks_per_lun*/ {0, 0},
137 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
138 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
139 	/*bytes_per_sector*/ {0, 0},
140 	/*interleave*/ {0, 0},
141 	/*track_skew*/ {0, 0},
142 	/*cylinder_skew*/ {0, 0},
143 	/*flags*/ SFP_HSEC,
144 	/*reserved*/ {0, 0, 0}
145 };
146 
147 const static struct scsi_format_page format_page_changeable = {
148 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
149 	/*page_length*/sizeof(struct scsi_format_page) - 2,
150 	/*tracks_per_zone*/ {0, 0},
151 	/*alt_sectors_per_zone*/ {0, 0},
152 	/*alt_tracks_per_zone*/ {0, 0},
153 	/*alt_tracks_per_lun*/ {0, 0},
154 	/*sectors_per_track*/ {0, 0},
155 	/*bytes_per_sector*/ {0, 0},
156 	/*interleave*/ {0, 0},
157 	/*track_skew*/ {0, 0},
158 	/*cylinder_skew*/ {0, 0},
159 	/*flags*/ 0,
160 	/*reserved*/ {0, 0, 0}
161 };
162 
163 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
164 	/*page_code*/SMS_RIGID_DISK_PAGE,
165 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
166 	/*cylinders*/ {0, 0, 0},
167 	/*heads*/ CTL_DEFAULT_HEADS,
168 	/*start_write_precomp*/ {0, 0, 0},
169 	/*start_reduced_current*/ {0, 0, 0},
170 	/*step_rate*/ {0, 0},
171 	/*landing_zone_cylinder*/ {0, 0, 0},
172 	/*rpl*/ SRDP_RPL_DISABLED,
173 	/*rotational_offset*/ 0,
174 	/*reserved1*/ 0,
175 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
176 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
177 	/*reserved2*/ {0, 0}
178 };
179 
180 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
181 	/*page_code*/SMS_RIGID_DISK_PAGE,
182 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
183 	/*cylinders*/ {0, 0, 0},
184 	/*heads*/ 0,
185 	/*start_write_precomp*/ {0, 0, 0},
186 	/*start_reduced_current*/ {0, 0, 0},
187 	/*step_rate*/ {0, 0},
188 	/*landing_zone_cylinder*/ {0, 0, 0},
189 	/*rpl*/ 0,
190 	/*rotational_offset*/ 0,
191 	/*reserved1*/ 0,
192 	/*rotation_rate*/ {0, 0},
193 	/*reserved2*/ {0, 0}
194 };
195 
196 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
197 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
198 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
199 	/*byte3*/0,
200 	/*read_retry_count*/0,
201 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
202 	/*recovery_time_limit*/{0, 0},
203 };
204 
205 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
206 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
207 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
208 	/*byte3*/SMS_VER_PER,
209 	/*read_retry_count*/0,
210 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
211 	/*recovery_time_limit*/{0, 0},
212 };
213 
214 const static struct scsi_caching_page caching_page_default = {
215 	/*page_code*/SMS_CACHING_PAGE,
216 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
217 	/*flags1*/ SCP_DISC | SCP_WCE,
218 	/*ret_priority*/ 0,
219 	/*disable_pf_transfer_len*/ {0xff, 0xff},
220 	/*min_prefetch*/ {0, 0},
221 	/*max_prefetch*/ {0xff, 0xff},
222 	/*max_pf_ceiling*/ {0xff, 0xff},
223 	/*flags2*/ 0,
224 	/*cache_segments*/ 0,
225 	/*cache_seg_size*/ {0, 0},
226 	/*reserved*/ 0,
227 	/*non_cache_seg_size*/ {0, 0, 0}
228 };
229 
230 const static struct scsi_caching_page caching_page_changeable = {
231 	/*page_code*/SMS_CACHING_PAGE,
232 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
233 	/*flags1*/ SCP_WCE | SCP_RCD,
234 	/*ret_priority*/ 0,
235 	/*disable_pf_transfer_len*/ {0, 0},
236 	/*min_prefetch*/ {0, 0},
237 	/*max_prefetch*/ {0, 0},
238 	/*max_pf_ceiling*/ {0, 0},
239 	/*flags2*/ 0,
240 	/*cache_segments*/ 0,
241 	/*cache_seg_size*/ {0, 0},
242 	/*reserved*/ 0,
243 	/*non_cache_seg_size*/ {0, 0, 0}
244 };
245 
246 const static struct scsi_control_page control_page_default = {
247 	/*page_code*/SMS_CONTROL_MODE_PAGE,
248 	/*page_length*/sizeof(struct scsi_control_page) - 2,
249 	/*rlec*/0,
250 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
251 	/*eca_and_aen*/0,
252 	/*flags4*/SCP_TAS,
253 	/*aen_holdoff_period*/{0, 0},
254 	/*busy_timeout_period*/{0, 0},
255 	/*extended_selftest_completion_time*/{0, 0}
256 };
257 
258 const static struct scsi_control_page control_page_changeable = {
259 	/*page_code*/SMS_CONTROL_MODE_PAGE,
260 	/*page_length*/sizeof(struct scsi_control_page) - 2,
261 	/*rlec*/SCP_DSENSE,
262 	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
263 	/*eca_and_aen*/SCP_SWP,
264 	/*flags4*/0,
265 	/*aen_holdoff_period*/{0, 0},
266 	/*busy_timeout_period*/{0, 0},
267 	/*extended_selftest_completion_time*/{0, 0}
268 };
269 
270 #define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
271 
272 const static struct scsi_control_ext_page control_ext_page_default = {
273 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
274 	/*subpage_code*/0x01,
275 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
276 	/*flags*/0,
277 	/*prio*/0,
278 	/*max_sense*/0
279 };
280 
281 const static struct scsi_control_ext_page control_ext_page_changeable = {
282 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
283 	/*subpage_code*/0x01,
284 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
285 	/*flags*/0,
286 	/*prio*/0,
287 	/*max_sense*/0xff
288 };
289 
290 const static struct scsi_info_exceptions_page ie_page_default = {
291 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
292 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
293 	/*info_flags*/SIEP_FLAGS_EWASC,
294 	/*mrie*/SIEP_MRIE_NO,
295 	/*interval_timer*/{0, 0, 0, 0},
296 	/*report_count*/{0, 0, 0, 1}
297 };
298 
299 const static struct scsi_info_exceptions_page ie_page_changeable = {
300 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
301 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
302 	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
303 	    SIEP_FLAGS_LOGERR,
304 	/*mrie*/0x0f,
305 	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
306 	/*report_count*/{0xff, 0xff, 0xff, 0xff}
307 };
308 
309 #define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
310 
311 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
312 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
313 	/*subpage_code*/0x02,
314 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
315 	/*flags*/0,
316 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
317 	/*descr*/{}},
318 	{{/*flags*/0,
319 	  /*resource*/0x01,
320 	  /*reserved*/{0, 0},
321 	  /*count*/{0, 0, 0, 0}},
322 	 {/*flags*/0,
323 	  /*resource*/0x02,
324 	  /*reserved*/{0, 0},
325 	  /*count*/{0, 0, 0, 0}},
326 	 {/*flags*/0,
327 	  /*resource*/0xf1,
328 	  /*reserved*/{0, 0},
329 	  /*count*/{0, 0, 0, 0}},
330 	 {/*flags*/0,
331 	  /*resource*/0xf2,
332 	  /*reserved*/{0, 0},
333 	  /*count*/{0, 0, 0, 0}}
334 	}
335 };
336 
337 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
338 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
339 	/*subpage_code*/0x02,
340 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
341 	/*flags*/SLBPP_SITUA,
342 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
343 	/*descr*/{}},
344 	{{/*flags*/0,
345 	  /*resource*/0,
346 	  /*reserved*/{0, 0},
347 	  /*count*/{0, 0, 0, 0}},
348 	 {/*flags*/0,
349 	  /*resource*/0,
350 	  /*reserved*/{0, 0},
351 	  /*count*/{0, 0, 0, 0}},
352 	 {/*flags*/0,
353 	  /*resource*/0,
354 	  /*reserved*/{0, 0},
355 	  /*count*/{0, 0, 0, 0}},
356 	 {/*flags*/0,
357 	  /*resource*/0,
358 	  /*reserved*/{0, 0},
359 	  /*count*/{0, 0, 0, 0}}
360 	}
361 };
362 
363 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
364 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
365 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
366 	/*caps1*/0x3f,
367 	/*caps2*/0x00,
368 	/*caps3*/0xf0,
369 	/*caps4*/0x00,
370 	/*caps5*/0x29,
371 	/*caps6*/0x00,
372 	/*obsolete*/{0, 0},
373 	/*nvol_levels*/{0, 0},
374 	/*buffer_size*/{8, 0},
375 	/*obsolete2*/{0, 0},
376 	/*reserved*/0,
377 	/*digital*/0,
378 	/*obsolete3*/0,
379 	/*copy_management*/0,
380 	/*reserved2*/0,
381 	/*rotation_control*/0,
382 	/*cur_write_speed*/0,
383 	/*num_speed_descr*/0,
384 };
385 
386 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
387 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
388 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
389 	/*caps1*/0,
390 	/*caps2*/0,
391 	/*caps3*/0,
392 	/*caps4*/0,
393 	/*caps5*/0,
394 	/*caps6*/0,
395 	/*obsolete*/{0, 0},
396 	/*nvol_levels*/{0, 0},
397 	/*buffer_size*/{0, 0},
398 	/*obsolete2*/{0, 0},
399 	/*reserved*/0,
400 	/*digital*/0,
401 	/*obsolete3*/0,
402 	/*copy_management*/0,
403 	/*reserved2*/0,
404 	/*rotation_control*/0,
405 	/*cur_write_speed*/0,
406 	/*num_speed_descr*/0,
407 };
408 
409 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
410     "CAM Target Layer");
411 static int worker_threads = -1;
412 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
413     &worker_threads, 1, "Number of worker threads");
414 static int ctl_debug = CTL_DEBUG_NONE;
415 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
416     &ctl_debug, 0, "Enabled debug flags");
417 static int ctl_lun_map_size = 1024;
418 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
419     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
420 #ifdef  CTL_TIME_IO
421 static int ctl_time_io_secs = CTL_TIME_IO_DEFAULT_SECS;
422 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, time_io_secs, CTLFLAG_RWTUN,
423     &ctl_time_io_secs, 0, "Log requests taking more seconds");
424 #endif
425 
426 /*
427  * Maximum number of LUNs we support.  MUST be a power of 2.
428  */
429 #define	CTL_DEFAULT_MAX_LUNS	1024
430 static int ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
431 TUNABLE_INT("kern.cam.ctl.max_luns", &ctl_max_luns);
432 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_luns, CTLFLAG_RDTUN,
433     &ctl_max_luns, CTL_DEFAULT_MAX_LUNS, "Maximum number of LUNs");
434 
435 /*
436  * Maximum number of ports registered at one time.
437  */
438 #define	CTL_DEFAULT_MAX_PORTS		256
439 static int ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
440 TUNABLE_INT("kern.cam.ctl.max_ports", &ctl_max_ports);
441 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_ports, CTLFLAG_RDTUN,
442     &ctl_max_ports, CTL_DEFAULT_MAX_LUNS, "Maximum number of ports");
443 
444 /*
445  * Maximum number of initiators we support.
446  */
447 #define	CTL_MAX_INITIATORS	(CTL_MAX_INIT_PER_PORT * ctl_max_ports)
448 
449 /*
450  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
451  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
452  * SCSI Ports (0x88), Third-party Copy (0x8F), SCSI Feature Sets (0x92),
453  * Block limits (0xB0), Block Device Characteristics (0xB1) and
454  * Logical Block Provisioning (0xB2)
455  */
456 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	11
457 
458 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
459 				  int param);
460 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
461 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
462 static int ctl_init(void);
463 static int ctl_shutdown(void);
464 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
465 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
466 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
467 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
468 			      struct ctl_ooa *ooa_hdr,
469 			      struct ctl_ooa_entry *kern_entries);
470 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
471 		     struct thread *td);
472 static int ctl_enable_lun(struct ctl_lun *lun);
473 static int ctl_disable_lun(struct ctl_lun *lun);
474 static int ctl_free_lun(struct ctl_lun *lun);
475 
476 static int ctl_do_mode_select(union ctl_io *io);
477 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
478 			   uint64_t res_key, uint64_t sa_res_key,
479 			   uint8_t type, uint32_t residx,
480 			   struct ctl_scsiio *ctsio,
481 			   struct scsi_per_res_out *cdb,
482 			   struct scsi_per_res_out_parms* param);
483 static void ctl_pro_preempt_other(struct ctl_lun *lun,
484 				  union ctl_ha_msg *msg);
485 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
486 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
487 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
488 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
489 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
490 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
491 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
492 					 int alloc_len);
493 static int ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len);
494 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
495 					 int alloc_len);
496 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
497 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
498 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
499 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
500 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
501 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
502     bool seq);
503 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
504 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
505     union ctl_io *pending_io, union ctl_io *ooa_io);
506 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
507 				union ctl_io **starting_io);
508 static void ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io,
509     bool skip);
510 static void ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *io,
511     bool skip);
512 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
513 				const struct ctl_cmd_entry *entry,
514 				struct ctl_scsiio *ctsio);
515 static void ctl_failover_lun(union ctl_io *io);
516 static void ctl_scsiio_precheck(struct ctl_scsiio *ctsio);
517 static int ctl_scsiio(struct ctl_scsiio *ctsio);
518 
519 static int ctl_target_reset(union ctl_io *io);
520 static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
521 			 ctl_ua_type ua_type);
522 static int ctl_lun_reset(union ctl_io *io);
523 static int ctl_abort_task(union ctl_io *io);
524 static int ctl_abort_task_set(union ctl_io *io);
525 static int ctl_query_task(union ctl_io *io, int task_set);
526 static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
527 			      ctl_ua_type ua_type);
528 static int ctl_i_t_nexus_reset(union ctl_io *io);
529 static int ctl_query_async_event(union ctl_io *io);
530 static void ctl_run_task(union ctl_io *io);
531 #ifdef CTL_IO_DELAY
532 static void ctl_datamove_timer_wakeup(void *arg);
533 static void ctl_done_timer_wakeup(void *arg);
534 #endif /* CTL_IO_DELAY */
535 
536 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
537 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
538 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
539 static void ctl_datamove_remote_write(union ctl_io *io);
540 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
541 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
542 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
543 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
544 				    ctl_ha_dt_cb callback);
545 static void ctl_datamove_remote_read(union ctl_io *io);
546 static void ctl_datamove_remote(union ctl_io *io);
547 static void ctl_process_done(union ctl_io *io);
548 static void ctl_thresh_thread(void *arg);
549 static void ctl_work_thread(void *arg);
550 static void ctl_enqueue_incoming(union ctl_io *io);
551 static void ctl_enqueue_rtr(union ctl_io *io);
552 static void ctl_enqueue_done(union ctl_io *io);
553 static void ctl_enqueue_isc(union ctl_io *io);
554 static const struct ctl_cmd_entry *
555     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
556 static const struct ctl_cmd_entry *
557     ctl_validate_command(struct ctl_scsiio *ctsio);
558 static int ctl_cmd_applicable(uint8_t lun_type,
559     const struct ctl_cmd_entry *entry);
560 static int ctl_ha_init(void);
561 static int ctl_ha_shutdown(void);
562 
563 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
564 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
565 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
566 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
567 
568 /*
569  * Load the serialization table.  This isn't very pretty, but is probably
570  * the easiest way to do it.
571  */
572 #include "ctl_ser_table.c"
573 
574 /*
575  * We only need to define open, close and ioctl routines for this driver.
576  */
577 static struct cdevsw ctl_cdevsw = {
578 	.d_version =	D_VERSION,
579 	.d_flags =	0,
580 	.d_open =	ctl_open,
581 	.d_close =	ctl_close,
582 	.d_ioctl =	ctl_ioctl,
583 	.d_name =	"ctl",
584 };
585 
586 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
587 
588 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
589 
590 static moduledata_t ctl_moduledata = {
591 	"ctl",
592 	ctl_module_event_handler,
593 	NULL
594 };
595 
596 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
597 MODULE_VERSION(ctl, 1);
598 
599 static struct ctl_frontend ha_frontend =
600 {
601 	.name = "ha",
602 	.init = ctl_ha_init,
603 	.shutdown = ctl_ha_shutdown,
604 };
605 
606 static int
607 ctl_ha_init(void)
608 {
609 	struct ctl_softc *softc = control_softc;
610 
611 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
612 	                    &softc->othersc_pool) != 0)
613 		return (ENOMEM);
614 	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
615 		ctl_pool_free(softc->othersc_pool);
616 		return (EIO);
617 	}
618 	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
619 	    != CTL_HA_STATUS_SUCCESS) {
620 		ctl_ha_msg_destroy(softc);
621 		ctl_pool_free(softc->othersc_pool);
622 		return (EIO);
623 	}
624 	return (0);
625 };
626 
627 static int
628 ctl_ha_shutdown(void)
629 {
630 	struct ctl_softc *softc = control_softc;
631 	struct ctl_port *port;
632 
633 	ctl_ha_msg_shutdown(softc);
634 	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
635 		return (EIO);
636 	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
637 		return (EIO);
638 	ctl_pool_free(softc->othersc_pool);
639 	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
640 		ctl_port_deregister(port);
641 		free(port->port_name, M_CTL);
642 		free(port, M_CTL);
643 	}
644 	return (0);
645 };
646 
647 static void
648 ctl_ha_datamove(union ctl_io *io)
649 {
650 	struct ctl_lun *lun = CTL_LUN(io);
651 	struct ctl_sg_entry *sgl;
652 	union ctl_ha_msg msg;
653 	uint32_t sg_entries_sent;
654 	int do_sg_copy, i, j;
655 
656 	memset(&msg.dt, 0, sizeof(msg.dt));
657 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
658 	msg.hdr.original_sc = io->io_hdr.remote_io;
659 	msg.hdr.serializing_sc = io;
660 	msg.hdr.nexus = io->io_hdr.nexus;
661 	msg.hdr.status = io->io_hdr.status;
662 	msg.dt.flags = io->io_hdr.flags;
663 
664 	/*
665 	 * We convert everything into a S/G list here.  We can't
666 	 * pass by reference, only by value between controllers.
667 	 * So we can't pass a pointer to the S/G list, only as many
668 	 * S/G entries as we can fit in here.  If it's possible for
669 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
670 	 * then we need to break this up into multiple transfers.
671 	 */
672 	if (io->scsiio.kern_sg_entries == 0) {
673 		msg.dt.kern_sg_entries = 1;
674 #if 0
675 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
676 			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
677 		} else {
678 			/* XXX KDM use busdma here! */
679 			msg.dt.sg_list[0].addr =
680 			    (void *)vtophys(io->scsiio.kern_data_ptr);
681 		}
682 #else
683 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
684 		    ("HA does not support BUS_ADDR"));
685 		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
686 #endif
687 		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
688 		do_sg_copy = 0;
689 	} else {
690 		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
691 		do_sg_copy = 1;
692 	}
693 
694 	msg.dt.kern_data_len = io->scsiio.kern_data_len;
695 	msg.dt.kern_total_len = io->scsiio.kern_total_len;
696 	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
697 	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
698 	msg.dt.sg_sequence = 0;
699 
700 	/*
701 	 * Loop until we've sent all of the S/G entries.  On the
702 	 * other end, we'll recompose these S/G entries into one
703 	 * contiguous list before processing.
704 	 */
705 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
706 	    msg.dt.sg_sequence++) {
707 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
708 		    sizeof(msg.dt.sg_list[0])),
709 		    msg.dt.kern_sg_entries - sg_entries_sent);
710 		if (do_sg_copy != 0) {
711 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
712 			for (i = sg_entries_sent, j = 0;
713 			     i < msg.dt.cur_sg_entries; i++, j++) {
714 #if 0
715 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
716 					msg.dt.sg_list[j].addr = sgl[i].addr;
717 				} else {
718 					/* XXX KDM use busdma here! */
719 					msg.dt.sg_list[j].addr =
720 					    (void *)vtophys(sgl[i].addr);
721 				}
722 #else
723 				KASSERT((io->io_hdr.flags &
724 				    CTL_FLAG_BUS_ADDR) == 0,
725 				    ("HA does not support BUS_ADDR"));
726 				msg.dt.sg_list[j].addr = sgl[i].addr;
727 #endif
728 				msg.dt.sg_list[j].len = sgl[i].len;
729 			}
730 		}
731 
732 		sg_entries_sent += msg.dt.cur_sg_entries;
733 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
734 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
735 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
736 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
737 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
738 			io->io_hdr.port_status = 31341;
739 			io->scsiio.be_move_done(io);
740 			return;
741 		}
742 		msg.dt.sent_sg_entries = sg_entries_sent;
743 	}
744 
745 	/*
746 	 * Officially handover the request from us to peer.
747 	 * If failover has just happened, then we must return error.
748 	 * If failover happen just after, then it is not our problem.
749 	 */
750 	if (lun)
751 		mtx_lock(&lun->lun_lock);
752 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
753 		if (lun)
754 			mtx_unlock(&lun->lun_lock);
755 		io->io_hdr.port_status = 31342;
756 		io->scsiio.be_move_done(io);
757 		return;
758 	}
759 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
760 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
761 	if (lun)
762 		mtx_unlock(&lun->lun_lock);
763 }
764 
765 static void
766 ctl_ha_done(union ctl_io *io)
767 {
768 	union ctl_ha_msg msg;
769 
770 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
771 		memset(&msg, 0, sizeof(msg));
772 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
773 		msg.hdr.original_sc = io->io_hdr.remote_io;
774 		msg.hdr.nexus = io->io_hdr.nexus;
775 		msg.hdr.status = io->io_hdr.status;
776 		msg.scsi.scsi_status = io->scsiio.scsi_status;
777 		msg.scsi.tag_num = io->scsiio.tag_num;
778 		msg.scsi.tag_type = io->scsiio.tag_type;
779 		msg.scsi.sense_len = io->scsiio.sense_len;
780 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
781 		    io->scsiio.sense_len);
782 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
783 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
784 		    msg.scsi.sense_len, M_WAITOK);
785 	}
786 	ctl_free_io(io);
787 }
788 
789 static void
790 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
791 			    union ctl_ha_msg *msg_info)
792 {
793 	struct ctl_scsiio *ctsio;
794 
795 	if (msg_info->hdr.original_sc == NULL) {
796 		printf("%s: original_sc == NULL!\n", __func__);
797 		/* XXX KDM now what? */
798 		return;
799 	}
800 
801 	ctsio = &msg_info->hdr.original_sc->scsiio;
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->port, sizeof(msg->port) + 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;
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 	bzero(&msg.mode, sizeof(msg.mode));
1014 	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
1015 	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
1016 	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
1017 	msg.hdr.nexus.targ_lun = lun->lun;
1018 	msg.hdr.nexus.targ_mapped_lun = lun->lun;
1019 	msg.mode.page_code = page;
1020 	msg.mode.subpage = subpage;
1021 	msg.mode.page_len = lun->mode_pages.index[i].page_len;
1022 	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
1023 	    msg.mode.page_len);
1024 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
1025 	    M_WAITOK);
1026 }
1027 
1028 static void
1029 ctl_isc_ha_link_up(struct ctl_softc *softc)
1030 {
1031 	struct ctl_port *port;
1032 	struct ctl_lun *lun;
1033 	union ctl_ha_msg msg;
1034 	int i;
1035 
1036 	/* Announce this node parameters to peer for validation. */
1037 	msg.login.msg_type = CTL_MSG_LOGIN;
1038 	msg.login.version = CTL_HA_VERSION;
1039 	msg.login.ha_mode = softc->ha_mode;
1040 	msg.login.ha_id = softc->ha_id;
1041 	msg.login.max_luns = ctl_max_luns;
1042 	msg.login.max_ports = ctl_max_ports;
1043 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1044 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1045 	    M_WAITOK);
1046 
1047 	STAILQ_FOREACH(port, &softc->port_list, links) {
1048 		ctl_isc_announce_port(port);
1049 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1050 			if (port->wwpn_iid[i].in_use)
1051 				ctl_isc_announce_iid(port, i);
1052 		}
1053 	}
1054 	STAILQ_FOREACH(lun, &softc->lun_list, links)
1055 		ctl_isc_announce_lun(lun);
1056 }
1057 
1058 static void
1059 ctl_isc_ha_link_down(struct ctl_softc *softc)
1060 {
1061 	struct ctl_port *port;
1062 	struct ctl_lun *lun;
1063 	union ctl_io *io;
1064 	int i;
1065 
1066 	mtx_lock(&softc->ctl_lock);
1067 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1068 		mtx_lock(&lun->lun_lock);
1069 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1070 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1071 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1072 		}
1073 		mtx_unlock(&lun->lun_lock);
1074 
1075 		mtx_unlock(&softc->ctl_lock);
1076 		io = ctl_alloc_io(softc->othersc_pool);
1077 		mtx_lock(&softc->ctl_lock);
1078 		ctl_zero_io(io);
1079 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1080 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1081 		ctl_enqueue_isc(io);
1082 	}
1083 
1084 	STAILQ_FOREACH(port, &softc->port_list, links) {
1085 		if (port->targ_port >= softc->port_min &&
1086 		    port->targ_port < softc->port_max)
1087 			continue;
1088 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1089 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1090 			port->wwpn_iid[i].in_use = 0;
1091 			free(port->wwpn_iid[i].name, M_CTL);
1092 			port->wwpn_iid[i].name = NULL;
1093 		}
1094 	}
1095 	mtx_unlock(&softc->ctl_lock);
1096 }
1097 
1098 static void
1099 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1100 {
1101 	struct ctl_lun *lun;
1102 	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1103 
1104 	mtx_lock(&softc->ctl_lock);
1105 	if (msg->hdr.nexus.targ_mapped_lun >= ctl_max_luns ||
1106 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1107 		mtx_unlock(&softc->ctl_lock);
1108 		return;
1109 	}
1110 	mtx_lock(&lun->lun_lock);
1111 	mtx_unlock(&softc->ctl_lock);
1112 	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1113 		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1114 	if (msg->ua.ua_all) {
1115 		if (msg->ua.ua_set)
1116 			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1117 		else
1118 			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1119 	} else {
1120 		if (msg->ua.ua_set)
1121 			ctl_est_ua(lun, iid, msg->ua.ua_type);
1122 		else
1123 			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1124 	}
1125 	mtx_unlock(&lun->lun_lock);
1126 }
1127 
1128 static void
1129 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1130 {
1131 	struct ctl_lun *lun;
1132 	struct ctl_ha_msg_lun_pr_key pr_key;
1133 	int i, k;
1134 	ctl_lun_flags oflags;
1135 	uint32_t targ_lun;
1136 
1137 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1138 	mtx_lock(&softc->ctl_lock);
1139 	if (targ_lun >= ctl_max_luns ||
1140 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1141 		mtx_unlock(&softc->ctl_lock);
1142 		return;
1143 	}
1144 	mtx_lock(&lun->lun_lock);
1145 	mtx_unlock(&softc->ctl_lock);
1146 	if (lun->flags & CTL_LUN_DISABLED) {
1147 		mtx_unlock(&lun->lun_lock);
1148 		return;
1149 	}
1150 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1151 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1152 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1153 		mtx_unlock(&lun->lun_lock);
1154 		printf("%s: Received conflicting HA LUN %d\n",
1155 		    __func__, targ_lun);
1156 		return;
1157 	} else {
1158 		/* Record whether peer is primary. */
1159 		oflags = lun->flags;
1160 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1161 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1162 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1163 		else
1164 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1165 		if (oflags != lun->flags)
1166 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1167 
1168 		/* If peer is primary and we are not -- use data */
1169 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1170 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1171 			lun->pr_generation = msg->lun.pr_generation;
1172 			lun->pr_res_idx = msg->lun.pr_res_idx;
1173 			lun->pr_res_type = msg->lun.pr_res_type;
1174 			lun->pr_key_count = msg->lun.pr_key_count;
1175 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1176 				ctl_clr_prkey(lun, k);
1177 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1178 				memcpy(&pr_key, &msg->lun.data[i],
1179 				    sizeof(pr_key));
1180 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1181 				ctl_set_prkey(lun, pr_key.pr_iid,
1182 				    pr_key.pr_key);
1183 				i += sizeof(pr_key);
1184 			}
1185 		}
1186 
1187 		mtx_unlock(&lun->lun_lock);
1188 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1189 		    __func__, targ_lun,
1190 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1191 		    "primary" : "secondary"));
1192 
1193 		/* If we are primary but peer doesn't know -- notify */
1194 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1195 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1196 			ctl_isc_announce_lun(lun);
1197 	}
1198 }
1199 
1200 static void
1201 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1202 {
1203 	struct ctl_port *port;
1204 	struct ctl_lun *lun;
1205 	int i, new;
1206 
1207 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1208 	if (port == NULL) {
1209 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1210 		    msg->hdr.nexus.targ_port));
1211 		new = 1;
1212 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1213 		port->frontend = &ha_frontend;
1214 		port->targ_port = msg->hdr.nexus.targ_port;
1215 		port->fe_datamove = ctl_ha_datamove;
1216 		port->fe_done = ctl_ha_done;
1217 	} else if (port->frontend == &ha_frontend) {
1218 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1219 		    msg->hdr.nexus.targ_port));
1220 		new = 0;
1221 	} else {
1222 		printf("%s: Received conflicting HA port %d\n",
1223 		    __func__, msg->hdr.nexus.targ_port);
1224 		return;
1225 	}
1226 	port->port_type = msg->port.port_type;
1227 	port->physical_port = msg->port.physical_port;
1228 	port->virtual_port = msg->port.virtual_port;
1229 	port->status = msg->port.status;
1230 	i = 0;
1231 	free(port->port_name, M_CTL);
1232 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1233 	    M_CTL);
1234 	i += msg->port.name_len;
1235 	if (msg->port.lun_map_len != 0) {
1236 		if (port->lun_map == NULL ||
1237 		    port->lun_map_size * sizeof(uint32_t) <
1238 		    msg->port.lun_map_len) {
1239 			port->lun_map_size = 0;
1240 			free(port->lun_map, M_CTL);
1241 			port->lun_map = malloc(msg->port.lun_map_len,
1242 			    M_CTL, M_WAITOK);
1243 		}
1244 		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1245 		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1246 		i += msg->port.lun_map_len;
1247 	} else {
1248 		port->lun_map_size = 0;
1249 		free(port->lun_map, M_CTL);
1250 		port->lun_map = NULL;
1251 	}
1252 	if (msg->port.port_devid_len != 0) {
1253 		if (port->port_devid == NULL ||
1254 		    port->port_devid->len < msg->port.port_devid_len) {
1255 			free(port->port_devid, M_CTL);
1256 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1257 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1258 		}
1259 		memcpy(port->port_devid->data, &msg->port.data[i],
1260 		    msg->port.port_devid_len);
1261 		port->port_devid->len = msg->port.port_devid_len;
1262 		i += msg->port.port_devid_len;
1263 	} else {
1264 		free(port->port_devid, M_CTL);
1265 		port->port_devid = NULL;
1266 	}
1267 	if (msg->port.target_devid_len != 0) {
1268 		if (port->target_devid == NULL ||
1269 		    port->target_devid->len < msg->port.target_devid_len) {
1270 			free(port->target_devid, M_CTL);
1271 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1272 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1273 		}
1274 		memcpy(port->target_devid->data, &msg->port.data[i],
1275 		    msg->port.target_devid_len);
1276 		port->target_devid->len = msg->port.target_devid_len;
1277 		i += msg->port.target_devid_len;
1278 	} else {
1279 		free(port->target_devid, M_CTL);
1280 		port->target_devid = NULL;
1281 	}
1282 	if (msg->port.init_devid_len != 0) {
1283 		if (port->init_devid == NULL ||
1284 		    port->init_devid->len < msg->port.init_devid_len) {
1285 			free(port->init_devid, M_CTL);
1286 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1287 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1288 		}
1289 		memcpy(port->init_devid->data, &msg->port.data[i],
1290 		    msg->port.init_devid_len);
1291 		port->init_devid->len = msg->port.init_devid_len;
1292 		i += msg->port.init_devid_len;
1293 	} else {
1294 		free(port->init_devid, M_CTL);
1295 		port->init_devid = NULL;
1296 	}
1297 	if (new) {
1298 		if (ctl_port_register(port) != 0) {
1299 			printf("%s: ctl_port_register() failed with error\n",
1300 			    __func__);
1301 		}
1302 	}
1303 	mtx_lock(&softc->ctl_lock);
1304 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1305 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1306 			continue;
1307 		mtx_lock(&lun->lun_lock);
1308 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1309 		mtx_unlock(&lun->lun_lock);
1310 	}
1311 	mtx_unlock(&softc->ctl_lock);
1312 }
1313 
1314 static void
1315 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1316 {
1317 	struct ctl_port *port;
1318 	int iid;
1319 
1320 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1321 	if (port == NULL) {
1322 		printf("%s: Received IID for unknown port %d\n",
1323 		    __func__, msg->hdr.nexus.targ_port);
1324 		return;
1325 	}
1326 	iid = msg->hdr.nexus.initid;
1327 	if (port->wwpn_iid[iid].in_use != 0 &&
1328 	    msg->iid.in_use == 0)
1329 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1330 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1331 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1332 	free(port->wwpn_iid[iid].name, M_CTL);
1333 	if (msg->iid.name_len) {
1334 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1335 		    msg->iid.name_len, M_CTL);
1336 	} else
1337 		port->wwpn_iid[iid].name = NULL;
1338 }
1339 
1340 static void
1341 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1342 {
1343 
1344 	if (msg->login.version != CTL_HA_VERSION) {
1345 		printf("CTL HA peers have different versions %d != %d\n",
1346 		    msg->login.version, CTL_HA_VERSION);
1347 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1348 		return;
1349 	}
1350 	if (msg->login.ha_mode != softc->ha_mode) {
1351 		printf("CTL HA peers have different ha_mode %d != %d\n",
1352 		    msg->login.ha_mode, softc->ha_mode);
1353 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1354 		return;
1355 	}
1356 	if (msg->login.ha_id == softc->ha_id) {
1357 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1358 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1359 		return;
1360 	}
1361 	if (msg->login.max_luns != ctl_max_luns ||
1362 	    msg->login.max_ports != ctl_max_ports ||
1363 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1364 		printf("CTL HA peers have different limits\n");
1365 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1366 		return;
1367 	}
1368 }
1369 
1370 static void
1371 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1372 {
1373 	struct ctl_lun *lun;
1374 	u_int i;
1375 	uint32_t initidx, targ_lun;
1376 
1377 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1378 	mtx_lock(&softc->ctl_lock);
1379 	if (targ_lun >= ctl_max_luns ||
1380 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1381 		mtx_unlock(&softc->ctl_lock);
1382 		return;
1383 	}
1384 	mtx_lock(&lun->lun_lock);
1385 	mtx_unlock(&softc->ctl_lock);
1386 	if (lun->flags & CTL_LUN_DISABLED) {
1387 		mtx_unlock(&lun->lun_lock);
1388 		return;
1389 	}
1390 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1391 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1392 		    msg->mode.page_code &&
1393 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1394 			break;
1395 	}
1396 	if (i == CTL_NUM_MODE_PAGES) {
1397 		mtx_unlock(&lun->lun_lock);
1398 		return;
1399 	}
1400 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1401 	    lun->mode_pages.index[i].page_len);
1402 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1403 	if (initidx != -1)
1404 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1405 	mtx_unlock(&lun->lun_lock);
1406 }
1407 
1408 /*
1409  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1410  * subsystem come in here.
1411  */
1412 static void
1413 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1414 {
1415 	struct ctl_softc *softc = control_softc;
1416 	union ctl_io *io;
1417 	struct ctl_prio *presio;
1418 	ctl_ha_status isc_status;
1419 
1420 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1421 	if (event == CTL_HA_EVT_MSG_RECV) {
1422 		union ctl_ha_msg *msg, msgbuf;
1423 
1424 		if (param > sizeof(msgbuf))
1425 			msg = malloc(param, M_CTL, M_WAITOK);
1426 		else
1427 			msg = &msgbuf;
1428 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1429 		    M_WAITOK);
1430 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1431 			printf("%s: Error receiving message: %d\n",
1432 			    __func__, isc_status);
1433 			if (msg != &msgbuf)
1434 				free(msg, M_CTL);
1435 			return;
1436 		}
1437 
1438 		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->hdr.msg_type));
1439 		switch (msg->hdr.msg_type) {
1440 		case CTL_MSG_SERIALIZE:
1441 			io = ctl_alloc_io(softc->othersc_pool);
1442 			ctl_zero_io(io);
1443 			// populate ctsio from msg
1444 			io->io_hdr.io_type = CTL_IO_SCSI;
1445 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1446 			io->io_hdr.remote_io = msg->hdr.original_sc;
1447 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1448 					    CTL_FLAG_IO_ACTIVE;
1449 			/*
1450 			 * If we're in serialization-only mode, we don't
1451 			 * want to go through full done processing.  Thus
1452 			 * the COPY flag.
1453 			 *
1454 			 * XXX KDM add another flag that is more specific.
1455 			 */
1456 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1457 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1458 			io->io_hdr.nexus = msg->hdr.nexus;
1459 			io->scsiio.priority = msg->scsi.priority;
1460 			io->scsiio.tag_num = msg->scsi.tag_num;
1461 			io->scsiio.tag_type = msg->scsi.tag_type;
1462 #ifdef CTL_TIME_IO
1463 			io->io_hdr.start_time = time_uptime;
1464 			getbinuptime(&io->io_hdr.start_bt);
1465 #endif /* CTL_TIME_IO */
1466 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1467 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1468 			       CTL_MAX_CDBLEN);
1469 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1470 				const struct ctl_cmd_entry *entry;
1471 
1472 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1473 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1474 				io->io_hdr.flags |=
1475 					entry->flags & CTL_FLAG_DATA_MASK;
1476 			}
1477 			ctl_enqueue_isc(io);
1478 			break;
1479 
1480 		/* Performed on the Originating SC, XFER mode only */
1481 		case CTL_MSG_DATAMOVE: {
1482 			struct ctl_sg_entry *sgl;
1483 			int i, j;
1484 
1485 			io = msg->hdr.original_sc;
1486 			if (io == NULL) {
1487 				printf("%s: original_sc == NULL!\n", __func__);
1488 				/* XXX KDM do something here */
1489 				break;
1490 			}
1491 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1492 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1493 			/*
1494 			 * Keep track of this, we need to send it back over
1495 			 * when the datamove is complete.
1496 			 */
1497 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1498 			if (msg->hdr.status == CTL_SUCCESS)
1499 				io->io_hdr.status = msg->hdr.status;
1500 
1501 			if (msg->dt.sg_sequence == 0) {
1502 #ifdef CTL_TIME_IO
1503 				getbinuptime(&io->io_hdr.dma_start_bt);
1504 #endif
1505 				i = msg->dt.kern_sg_entries +
1506 				    msg->dt.kern_data_len /
1507 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1508 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1509 				    M_WAITOK | M_ZERO);
1510 				CTL_RSGL(io) = sgl;
1511 				CTL_LSGL(io) = &sgl[msg->dt.kern_sg_entries];
1512 
1513 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1514 
1515 				io->scsiio.kern_sg_entries =
1516 					msg->dt.kern_sg_entries;
1517 				io->scsiio.rem_sg_entries =
1518 					msg->dt.kern_sg_entries;
1519 				io->scsiio.kern_data_len =
1520 					msg->dt.kern_data_len;
1521 				io->scsiio.kern_total_len =
1522 					msg->dt.kern_total_len;
1523 				io->scsiio.kern_data_resid =
1524 					msg->dt.kern_data_resid;
1525 				io->scsiio.kern_rel_offset =
1526 					msg->dt.kern_rel_offset;
1527 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1528 				io->io_hdr.flags |= msg->dt.flags &
1529 				    CTL_FLAG_BUS_ADDR;
1530 			} else
1531 				sgl = (struct ctl_sg_entry *)
1532 					io->scsiio.kern_data_ptr;
1533 
1534 			for (i = msg->dt.sent_sg_entries, j = 0;
1535 			     i < (msg->dt.sent_sg_entries +
1536 			     msg->dt.cur_sg_entries); i++, j++) {
1537 				sgl[i].addr = msg->dt.sg_list[j].addr;
1538 				sgl[i].len = msg->dt.sg_list[j].len;
1539 			}
1540 
1541 			/*
1542 			 * If this is the last piece of the I/O, we've got
1543 			 * the full S/G list.  Queue processing in the thread.
1544 			 * Otherwise wait for the next piece.
1545 			 */
1546 			if (msg->dt.sg_last != 0)
1547 				ctl_enqueue_isc(io);
1548 			break;
1549 		}
1550 		/* Performed on the Serializing (primary) SC, XFER mode only */
1551 		case CTL_MSG_DATAMOVE_DONE: {
1552 			if (msg->hdr.serializing_sc == NULL) {
1553 				printf("%s: serializing_sc == NULL!\n",
1554 				       __func__);
1555 				/* XXX KDM now what? */
1556 				break;
1557 			}
1558 			/*
1559 			 * We grab the sense information here in case
1560 			 * there was a failure, so we can return status
1561 			 * back to the initiator.
1562 			 */
1563 			io = msg->hdr.serializing_sc;
1564 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1565 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1566 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1567 			io->io_hdr.port_status = msg->scsi.port_status;
1568 			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1569 			if (msg->hdr.status != CTL_STATUS_NONE) {
1570 				io->io_hdr.status = msg->hdr.status;
1571 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1572 				io->scsiio.sense_len = msg->scsi.sense_len;
1573 				memcpy(&io->scsiio.sense_data,
1574 				    &msg->scsi.sense_data,
1575 				    msg->scsi.sense_len);
1576 				if (msg->hdr.status == CTL_SUCCESS)
1577 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1578 			}
1579 			ctl_enqueue_isc(io);
1580 			break;
1581 		}
1582 
1583 		/* Preformed on Originating SC, SER_ONLY mode */
1584 		case CTL_MSG_R2R:
1585 			io = msg->hdr.original_sc;
1586 			if (io == NULL) {
1587 				printf("%s: original_sc == NULL!\n",
1588 				    __func__);
1589 				break;
1590 			}
1591 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1592 			io->io_hdr.msg_type = CTL_MSG_R2R;
1593 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1594 			ctl_enqueue_isc(io);
1595 			break;
1596 
1597 		/*
1598 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1599 		 * mode.
1600 		 * Performed on the Originating (i.e. secondary) SC in XFER
1601 		 * mode
1602 		 */
1603 		case CTL_MSG_FINISH_IO:
1604 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1605 				ctl_isc_handler_finish_xfer(softc, msg);
1606 			else
1607 				ctl_isc_handler_finish_ser_only(softc, msg);
1608 			break;
1609 
1610 		/* Preformed on Originating SC */
1611 		case CTL_MSG_BAD_JUJU:
1612 			io = msg->hdr.original_sc;
1613 			if (io == NULL) {
1614 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1615 				       __func__);
1616 				break;
1617 			}
1618 			ctl_copy_sense_data(msg, io);
1619 			/*
1620 			 * IO should have already been cleaned up on other
1621 			 * SC so clear this flag so we won't send a message
1622 			 * back to finish the IO there.
1623 			 */
1624 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1625 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1626 
1627 			/* io = msg->hdr.serializing_sc; */
1628 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1629 			ctl_enqueue_isc(io);
1630 			break;
1631 
1632 		/* Handle resets sent from the other side */
1633 		case CTL_MSG_MANAGE_TASKS: {
1634 			struct ctl_taskio *taskio;
1635 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1636 			    softc->othersc_pool);
1637 			ctl_zero_io((union ctl_io *)taskio);
1638 			taskio->io_hdr.io_type = CTL_IO_TASK;
1639 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1640 			taskio->io_hdr.nexus = msg->hdr.nexus;
1641 			taskio->task_action = msg->task.task_action;
1642 			taskio->tag_num = msg->task.tag_num;
1643 			taskio->tag_type = msg->task.tag_type;
1644 #ifdef CTL_TIME_IO
1645 			taskio->io_hdr.start_time = time_uptime;
1646 			getbinuptime(&taskio->io_hdr.start_bt);
1647 #endif /* CTL_TIME_IO */
1648 			ctl_run_task((union ctl_io *)taskio);
1649 			break;
1650 		}
1651 		/* Persistent Reserve action which needs attention */
1652 		case CTL_MSG_PERS_ACTION:
1653 			presio = (struct ctl_prio *)ctl_alloc_io(
1654 			    softc->othersc_pool);
1655 			ctl_zero_io((union ctl_io *)presio);
1656 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1657 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1658 			presio->io_hdr.nexus = msg->hdr.nexus;
1659 			presio->pr_msg = msg->pr;
1660 			ctl_enqueue_isc((union ctl_io *)presio);
1661 			break;
1662 		case CTL_MSG_UA:
1663 			ctl_isc_ua(softc, msg, param);
1664 			break;
1665 		case CTL_MSG_PORT_SYNC:
1666 			ctl_isc_port_sync(softc, msg, param);
1667 			break;
1668 		case CTL_MSG_LUN_SYNC:
1669 			ctl_isc_lun_sync(softc, msg, param);
1670 			break;
1671 		case CTL_MSG_IID_SYNC:
1672 			ctl_isc_iid_sync(softc, msg, param);
1673 			break;
1674 		case CTL_MSG_LOGIN:
1675 			ctl_isc_login(softc, msg, param);
1676 			break;
1677 		case CTL_MSG_MODE_SYNC:
1678 			ctl_isc_mode_sync(softc, msg, param);
1679 			break;
1680 		default:
1681 			printf("Received HA message of unknown type %d\n",
1682 			    msg->hdr.msg_type);
1683 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1684 			break;
1685 		}
1686 		if (msg != &msgbuf)
1687 			free(msg, M_CTL);
1688 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1689 		printf("CTL: HA link status changed from %d to %d\n",
1690 		    softc->ha_link, param);
1691 		if (param == softc->ha_link)
1692 			return;
1693 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1694 			softc->ha_link = param;
1695 			ctl_isc_ha_link_down(softc);
1696 		} else {
1697 			softc->ha_link = param;
1698 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1699 				ctl_isc_ha_link_up(softc);
1700 		}
1701 		return;
1702 	} else {
1703 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1704 		return;
1705 	}
1706 }
1707 
1708 static void
1709 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1710 {
1711 
1712 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1713 	    src->scsi.sense_len);
1714 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1715 	dest->scsiio.sense_len = src->scsi.sense_len;
1716 	dest->io_hdr.status = src->hdr.status;
1717 }
1718 
1719 static void
1720 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1721 {
1722 
1723 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1724 	    src->scsiio.sense_len);
1725 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1726 	dest->scsi.sense_len = src->scsiio.sense_len;
1727 	dest->hdr.status = src->io_hdr.status;
1728 }
1729 
1730 void
1731 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1732 {
1733 	struct ctl_softc *softc = lun->ctl_softc;
1734 	ctl_ua_type *pu;
1735 
1736 	if (initidx < softc->init_min || initidx >= softc->init_max)
1737 		return;
1738 	mtx_assert(&lun->lun_lock, MA_OWNED);
1739 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1740 	if (pu == NULL)
1741 		return;
1742 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1743 }
1744 
1745 void
1746 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1747 {
1748 	int i;
1749 
1750 	mtx_assert(&lun->lun_lock, MA_OWNED);
1751 	if (lun->pending_ua[port] == NULL)
1752 		return;
1753 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1754 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1755 			continue;
1756 		lun->pending_ua[port][i] |= ua;
1757 	}
1758 }
1759 
1760 void
1761 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1762 {
1763 	struct ctl_softc *softc = lun->ctl_softc;
1764 	int i;
1765 
1766 	mtx_assert(&lun->lun_lock, MA_OWNED);
1767 	for (i = softc->port_min; i < softc->port_max; i++)
1768 		ctl_est_ua_port(lun, i, except, ua);
1769 }
1770 
1771 void
1772 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1773 {
1774 	struct ctl_softc *softc = lun->ctl_softc;
1775 	ctl_ua_type *pu;
1776 
1777 	if (initidx < softc->init_min || initidx >= softc->init_max)
1778 		return;
1779 	mtx_assert(&lun->lun_lock, MA_OWNED);
1780 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1781 	if (pu == NULL)
1782 		return;
1783 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1784 }
1785 
1786 void
1787 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1788 {
1789 	struct ctl_softc *softc = lun->ctl_softc;
1790 	int i, j;
1791 
1792 	mtx_assert(&lun->lun_lock, MA_OWNED);
1793 	for (i = softc->port_min; i < softc->port_max; i++) {
1794 		if (lun->pending_ua[i] == NULL)
1795 			continue;
1796 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1797 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1798 				continue;
1799 			lun->pending_ua[i][j] &= ~ua;
1800 		}
1801 	}
1802 }
1803 
1804 void
1805 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1806     ctl_ua_type ua_type)
1807 {
1808 	struct ctl_lun *lun;
1809 
1810 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1811 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1812 		mtx_lock(&lun->lun_lock);
1813 		ctl_clr_ua(lun, initidx, ua_type);
1814 		mtx_unlock(&lun->lun_lock);
1815 	}
1816 }
1817 
1818 static int
1819 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1820 {
1821 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1822 	struct ctl_lun *lun;
1823 	struct ctl_lun_req ireq;
1824 	int error, value;
1825 
1826 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1827 	error = sysctl_handle_int(oidp, &value, 0, req);
1828 	if ((error != 0) || (req->newptr == NULL))
1829 		return (error);
1830 
1831 	mtx_lock(&softc->ctl_lock);
1832 	if (value == 0)
1833 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1834 	else
1835 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1836 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1837 		mtx_unlock(&softc->ctl_lock);
1838 		bzero(&ireq, sizeof(ireq));
1839 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1840 		ireq.reqdata.modify.lun_id = lun->lun;
1841 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1842 		    curthread);
1843 		if (ireq.status != CTL_LUN_OK) {
1844 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1845 			    __func__, ireq.status, ireq.error_str);
1846 		}
1847 		mtx_lock(&softc->ctl_lock);
1848 	}
1849 	mtx_unlock(&softc->ctl_lock);
1850 	return (0);
1851 }
1852 
1853 static int
1854 ctl_init(void)
1855 {
1856 	struct make_dev_args args;
1857 	struct ctl_softc *softc;
1858 	int i, error;
1859 
1860 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1861 			       M_WAITOK | M_ZERO);
1862 
1863 	make_dev_args_init(&args);
1864 	args.mda_devsw = &ctl_cdevsw;
1865 	args.mda_uid = UID_ROOT;
1866 	args.mda_gid = GID_OPERATOR;
1867 	args.mda_mode = 0600;
1868 	args.mda_si_drv1 = softc;
1869 	args.mda_si_drv2 = NULL;
1870 	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1871 	if (error != 0) {
1872 		free(softc, M_DEVBUF);
1873 		control_softc = NULL;
1874 		return (error);
1875 	}
1876 
1877 	sysctl_ctx_init(&softc->sysctl_ctx);
1878 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1879 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1880 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "CAM Target Layer");
1881 
1882 	if (softc->sysctl_tree == NULL) {
1883 		printf("%s: unable to allocate sysctl tree\n", __func__);
1884 		destroy_dev(softc->dev);
1885 		free(softc, M_DEVBUF);
1886 		control_softc = NULL;
1887 		return (ENOMEM);
1888 	}
1889 
1890 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1891 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1892 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1893 	softc->flags = 0;
1894 
1895 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1896 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1897 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1898 
1899 	if (ctl_max_luns <= 0 || powerof2(ctl_max_luns) == 0) {
1900 		printf("Bad value %d for kern.cam.ctl.max_luns, must be a power of two, using %d\n",
1901 		    ctl_max_luns, CTL_DEFAULT_MAX_LUNS);
1902 		ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
1903 	}
1904 	softc->ctl_luns = malloc(sizeof(struct ctl_lun *) * ctl_max_luns,
1905 	    M_DEVBUF, M_WAITOK | M_ZERO);
1906 	softc->ctl_lun_mask = malloc(sizeof(uint32_t) *
1907 	    ((ctl_max_luns + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1908 	if (ctl_max_ports <= 0 || powerof2(ctl_max_ports) == 0) {
1909 		printf("Bad value %d for kern.cam.ctl.max_ports, must be a power of two, using %d\n",
1910 		    ctl_max_ports, CTL_DEFAULT_MAX_PORTS);
1911 		ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
1912 	}
1913 	softc->ctl_port_mask = malloc(sizeof(uint32_t) *
1914 	  ((ctl_max_ports + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1915 	softc->ctl_ports = malloc(sizeof(struct ctl_port *) * ctl_max_ports,
1916 	     M_DEVBUF, M_WAITOK | M_ZERO);
1917 
1918 	/*
1919 	 * In Copan's HA scheme, the "master" and "slave" roles are
1920 	 * figured out through the slot the controller is in.  Although it
1921 	 * is an active/active system, someone has to be in charge.
1922 	 */
1923 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1924 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1925 	    "HA head ID (0 - no HA)");
1926 	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1927 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1928 		softc->is_single = 1;
1929 		softc->port_cnt = ctl_max_ports;
1930 		softc->port_min = 0;
1931 	} else {
1932 		softc->port_cnt = ctl_max_ports / NUM_HA_SHELVES;
1933 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1934 	}
1935 	softc->port_max = softc->port_min + softc->port_cnt;
1936 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1937 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1938 
1939 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1940 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1941 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1942 
1943 	STAILQ_INIT(&softc->lun_list);
1944 	STAILQ_INIT(&softc->fe_list);
1945 	STAILQ_INIT(&softc->port_list);
1946 	STAILQ_INIT(&softc->be_list);
1947 	ctl_tpc_init(softc);
1948 
1949 	if (worker_threads <= 0)
1950 		worker_threads = max(1, mp_ncpus / 4);
1951 	if (worker_threads > CTL_MAX_THREADS)
1952 		worker_threads = CTL_MAX_THREADS;
1953 
1954 	for (i = 0; i < worker_threads; i++) {
1955 		struct ctl_thread *thr = &softc->threads[i];
1956 
1957 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1958 		thr->ctl_softc = softc;
1959 		STAILQ_INIT(&thr->incoming_queue);
1960 		STAILQ_INIT(&thr->rtr_queue);
1961 		STAILQ_INIT(&thr->done_queue);
1962 		STAILQ_INIT(&thr->isc_queue);
1963 
1964 		error = kproc_kthread_add(ctl_work_thread, thr,
1965 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1966 		if (error != 0) {
1967 			printf("error creating CTL work thread!\n");
1968 			return (error);
1969 		}
1970 	}
1971 	error = kproc_kthread_add(ctl_thresh_thread, softc,
1972 	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
1973 	if (error != 0) {
1974 		printf("error creating CTL threshold thread!\n");
1975 		return (error);
1976 	}
1977 
1978 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1979 	    OID_AUTO, "ha_role",
1980 	    CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_NEEDGIANT,
1981 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1982 
1983 	if (softc->is_single == 0) {
1984 		if (ctl_frontend_register(&ha_frontend) != 0)
1985 			softc->is_single = 1;
1986 	}
1987 	return (0);
1988 }
1989 
1990 static int
1991 ctl_shutdown(void)
1992 {
1993 	struct ctl_softc *softc = control_softc;
1994 	int i;
1995 
1996 	if (softc->is_single == 0)
1997 		ctl_frontend_deregister(&ha_frontend);
1998 
1999 	destroy_dev(softc->dev);
2000 
2001 	/* Shutdown CTL threads. */
2002 	softc->shutdown = 1;
2003 	for (i = 0; i < worker_threads; i++) {
2004 		struct ctl_thread *thr = &softc->threads[i];
2005 		while (thr->thread != NULL) {
2006 			wakeup(thr);
2007 			if (thr->thread != NULL)
2008 				pause("CTL thr shutdown", 1);
2009 		}
2010 		mtx_destroy(&thr->queue_lock);
2011 	}
2012 	while (softc->thresh_thread != NULL) {
2013 		wakeup(softc->thresh_thread);
2014 		if (softc->thresh_thread != NULL)
2015 			pause("CTL thr shutdown", 1);
2016 	}
2017 
2018 	ctl_tpc_shutdown(softc);
2019 	uma_zdestroy(softc->io_zone);
2020 	mtx_destroy(&softc->ctl_lock);
2021 
2022 	free(softc->ctl_luns, M_DEVBUF);
2023 	free(softc->ctl_lun_mask, M_DEVBUF);
2024 	free(softc->ctl_port_mask, M_DEVBUF);
2025 	free(softc->ctl_ports, M_DEVBUF);
2026 
2027 	sysctl_ctx_free(&softc->sysctl_ctx);
2028 
2029 	free(softc, M_DEVBUF);
2030 	control_softc = NULL;
2031 	return (0);
2032 }
2033 
2034 static int
2035 ctl_module_event_handler(module_t mod, int what, void *arg)
2036 {
2037 
2038 	switch (what) {
2039 	case MOD_LOAD:
2040 		return (ctl_init());
2041 	case MOD_UNLOAD:
2042 		return (ctl_shutdown());
2043 	default:
2044 		return (EOPNOTSUPP);
2045 	}
2046 }
2047 
2048 /*
2049  * XXX KDM should we do some access checks here?  Bump a reference count to
2050  * prevent a CTL module from being unloaded while someone has it open?
2051  */
2052 static int
2053 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2054 {
2055 	return (0);
2056 }
2057 
2058 static int
2059 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2060 {
2061 	return (0);
2062 }
2063 
2064 /*
2065  * Remove an initiator by port number and initiator ID.
2066  * Returns 0 for success, -1 for failure.
2067  */
2068 int
2069 ctl_remove_initiator(struct ctl_port *port, int iid)
2070 {
2071 	struct ctl_softc *softc = port->ctl_softc;
2072 	int last;
2073 
2074 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2075 
2076 	if (iid > CTL_MAX_INIT_PER_PORT) {
2077 		printf("%s: initiator ID %u > maximun %u!\n",
2078 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2079 		return (-1);
2080 	}
2081 
2082 	mtx_lock(&softc->ctl_lock);
2083 	last = (--port->wwpn_iid[iid].in_use == 0);
2084 	port->wwpn_iid[iid].last_use = time_uptime;
2085 	mtx_unlock(&softc->ctl_lock);
2086 	if (last)
2087 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2088 	ctl_isc_announce_iid(port, iid);
2089 
2090 	return (0);
2091 }
2092 
2093 /*
2094  * Add an initiator to the initiator map.
2095  * Returns iid for success, < 0 for failure.
2096  */
2097 int
2098 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2099 {
2100 	struct ctl_softc *softc = port->ctl_softc;
2101 	time_t best_time;
2102 	int i, best;
2103 
2104 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2105 
2106 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2107 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2108 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2109 		free(name, M_CTL);
2110 		return (-1);
2111 	}
2112 
2113 	mtx_lock(&softc->ctl_lock);
2114 
2115 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2116 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2117 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2118 				iid = i;
2119 				break;
2120 			}
2121 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2122 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2123 				iid = i;
2124 				break;
2125 			}
2126 		}
2127 	}
2128 
2129 	if (iid < 0) {
2130 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2131 			if (port->wwpn_iid[i].in_use == 0 &&
2132 			    port->wwpn_iid[i].wwpn == 0 &&
2133 			    port->wwpn_iid[i].name == NULL) {
2134 				iid = i;
2135 				break;
2136 			}
2137 		}
2138 	}
2139 
2140 	if (iid < 0) {
2141 		best = -1;
2142 		best_time = INT32_MAX;
2143 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2144 			if (port->wwpn_iid[i].in_use == 0) {
2145 				if (port->wwpn_iid[i].last_use < best_time) {
2146 					best = i;
2147 					best_time = port->wwpn_iid[i].last_use;
2148 				}
2149 			}
2150 		}
2151 		iid = best;
2152 	}
2153 
2154 	if (iid < 0) {
2155 		mtx_unlock(&softc->ctl_lock);
2156 		free(name, M_CTL);
2157 		return (-2);
2158 	}
2159 
2160 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2161 		/*
2162 		 * This is not an error yet.
2163 		 */
2164 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2165 #if 0
2166 			printf("%s: port %d iid %u WWPN %#jx arrived"
2167 			    " again\n", __func__, port->targ_port,
2168 			    iid, (uintmax_t)wwpn);
2169 #endif
2170 			goto take;
2171 		}
2172 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2173 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2174 #if 0
2175 			printf("%s: port %d iid %u name '%s' arrived"
2176 			    " again\n", __func__, port->targ_port,
2177 			    iid, name);
2178 #endif
2179 			goto take;
2180 		}
2181 
2182 		/*
2183 		 * This is an error, but what do we do about it?  The
2184 		 * driver is telling us we have a new WWPN for this
2185 		 * initiator ID, so we pretty much need to use it.
2186 		 */
2187 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2188 		    " but WWPN %#jx '%s' is still at that address\n",
2189 		    __func__, port->targ_port, iid, wwpn, name,
2190 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2191 		    port->wwpn_iid[iid].name);
2192 	}
2193 take:
2194 	free(port->wwpn_iid[iid].name, M_CTL);
2195 	port->wwpn_iid[iid].name = name;
2196 	port->wwpn_iid[iid].wwpn = wwpn;
2197 	port->wwpn_iid[iid].in_use++;
2198 	mtx_unlock(&softc->ctl_lock);
2199 	ctl_isc_announce_iid(port, iid);
2200 
2201 	return (iid);
2202 }
2203 
2204 static int
2205 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2206 {
2207 	int len;
2208 
2209 	switch (port->port_type) {
2210 	case CTL_PORT_FC:
2211 	{
2212 		struct scsi_transportid_fcp *id =
2213 		    (struct scsi_transportid_fcp *)buf;
2214 		if (port->wwpn_iid[iid].wwpn == 0)
2215 			return (0);
2216 		memset(id, 0, sizeof(*id));
2217 		id->format_protocol = SCSI_PROTO_FC;
2218 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2219 		return (sizeof(*id));
2220 	}
2221 	case CTL_PORT_ISCSI:
2222 	{
2223 		struct scsi_transportid_iscsi_port *id =
2224 		    (struct scsi_transportid_iscsi_port *)buf;
2225 		if (port->wwpn_iid[iid].name == NULL)
2226 			return (0);
2227 		memset(id, 0, 256);
2228 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2229 		    SCSI_PROTO_ISCSI;
2230 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2231 		len = roundup2(min(len, 252), 4);
2232 		scsi_ulto2b(len, id->additional_length);
2233 		return (sizeof(*id) + len);
2234 	}
2235 	case CTL_PORT_SAS:
2236 	{
2237 		struct scsi_transportid_sas *id =
2238 		    (struct scsi_transportid_sas *)buf;
2239 		if (port->wwpn_iid[iid].wwpn == 0)
2240 			return (0);
2241 		memset(id, 0, sizeof(*id));
2242 		id->format_protocol = SCSI_PROTO_SAS;
2243 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2244 		return (sizeof(*id));
2245 	}
2246 	default:
2247 	{
2248 		struct scsi_transportid_spi *id =
2249 		    (struct scsi_transportid_spi *)buf;
2250 		memset(id, 0, sizeof(*id));
2251 		id->format_protocol = SCSI_PROTO_SPI;
2252 		scsi_ulto2b(iid, id->scsi_addr);
2253 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2254 		return (sizeof(*id));
2255 	}
2256 	}
2257 }
2258 
2259 /*
2260  * Serialize a command that went down the "wrong" side, and so was sent to
2261  * this controller for execution.  The logic is a little different than the
2262  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2263  * sent back to the other side, but in the success case, we execute the
2264  * command on this side (XFER mode) or tell the other side to execute it
2265  * (SER_ONLY mode).
2266  */
2267 static void
2268 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2269 {
2270 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2271 	struct ctl_port *port = CTL_PORT(ctsio);
2272 	union ctl_ha_msg msg_info;
2273 	struct ctl_lun *lun;
2274 	const struct ctl_cmd_entry *entry;
2275 	union ctl_io *bio;
2276 	uint32_t targ_lun;
2277 
2278 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2279 
2280 	/* Make sure that we know about this port. */
2281 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2282 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2283 					 /*retry_count*/ 1);
2284 		goto badjuju;
2285 	}
2286 
2287 	/* Make sure that we know about this LUN. */
2288 	mtx_lock(&softc->ctl_lock);
2289 	if (targ_lun >= ctl_max_luns ||
2290 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2291 		mtx_unlock(&softc->ctl_lock);
2292 
2293 		/*
2294 		 * The other node would not send this request to us unless
2295 		 * received announce that we are primary node for this LUN.
2296 		 * If this LUN does not exist now, it is probably result of
2297 		 * a race, so respond to initiator in the most opaque way.
2298 		 */
2299 		ctl_set_busy(ctsio);
2300 		goto badjuju;
2301 	}
2302 	mtx_lock(&lun->lun_lock);
2303 	mtx_unlock(&softc->ctl_lock);
2304 
2305 	/*
2306 	 * If the LUN is invalid, pretend that it doesn't exist.
2307 	 * It will go away as soon as all pending I/Os completed.
2308 	 */
2309 	if (lun->flags & CTL_LUN_DISABLED) {
2310 		mtx_unlock(&lun->lun_lock);
2311 		ctl_set_busy(ctsio);
2312 		goto badjuju;
2313 	}
2314 
2315 	entry = ctl_get_cmd_entry(ctsio, NULL);
2316 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2317 		mtx_unlock(&lun->lun_lock);
2318 		goto badjuju;
2319 	}
2320 
2321 	CTL_LUN(ctsio) = lun;
2322 	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2323 
2324 	/*
2325 	 * Every I/O goes into the OOA queue for a
2326 	 * particular LUN, and stays there until completion.
2327 	 */
2328 #ifdef CTL_TIME_IO
2329 	if (LIST_EMPTY(&lun->ooa_queue))
2330 		lun->idle_time += getsbinuptime() - lun->last_busy;
2331 #endif
2332 	LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2333 
2334 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
2335 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
2336 	case CTL_ACTION_BLOCK:
2337 		ctsio->io_hdr.blocker = bio;
2338 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
2339 				  blocked_links);
2340 		mtx_unlock(&lun->lun_lock);
2341 		break;
2342 	case CTL_ACTION_PASS:
2343 	case CTL_ACTION_SKIP:
2344 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2345 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2346 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2347 			mtx_unlock(&lun->lun_lock);
2348 		} else {
2349 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2350 			mtx_unlock(&lun->lun_lock);
2351 
2352 			/* send msg back to other side */
2353 			msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2354 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2355 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2356 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2357 			    sizeof(msg_info.hdr), M_WAITOK);
2358 		}
2359 		break;
2360 	case CTL_ACTION_OVERLAP:
2361 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2362 		mtx_unlock(&lun->lun_lock);
2363 		ctl_set_overlapped_cmd(ctsio);
2364 		goto badjuju;
2365 	case CTL_ACTION_OVERLAP_TAG:
2366 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2367 		mtx_unlock(&lun->lun_lock);
2368 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2369 		goto badjuju;
2370 	case CTL_ACTION_ERROR:
2371 	default:
2372 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2373 		mtx_unlock(&lun->lun_lock);
2374 
2375 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2376 					 /*retry_count*/ 0);
2377 badjuju:
2378 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2379 		msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2380 		msg_info.hdr.serializing_sc = NULL;
2381 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2382 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2383 		    sizeof(msg_info.scsi), M_WAITOK);
2384 		ctl_free_io((union ctl_io *)ctsio);
2385 		break;
2386 	}
2387 }
2388 
2389 /*
2390  * Returns 0 for success, errno for failure.
2391  */
2392 static void
2393 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2394 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2395 {
2396 	struct ctl_io_hdr *ioh;
2397 
2398 	mtx_lock(&lun->lun_lock);
2399 	ioh = LIST_FIRST(&lun->ooa_queue);
2400 	if (ioh == NULL) {
2401 		mtx_unlock(&lun->lun_lock);
2402 		return;
2403 	}
2404 	while (LIST_NEXT(ioh, ooa_links) != NULL)
2405 		ioh = LIST_NEXT(ioh, ooa_links);
2406 	for ( ; ioh; ioh = LIST_PREV(ioh, &lun->ooa_queue, ctl_io_hdr, ooa_links)) {
2407 		union ctl_io *io = (union ctl_io *)ioh;
2408 		struct ctl_ooa_entry *entry;
2409 
2410 		/*
2411 		 * If we've got more than we can fit, just count the
2412 		 * remaining entries.
2413 		 */
2414 		if (*cur_fill_num >= ooa_hdr->alloc_num) {
2415 			(*cur_fill_num)++;
2416 			continue;
2417 		}
2418 
2419 		entry = &kern_entries[*cur_fill_num];
2420 
2421 		entry->tag_num = io->scsiio.tag_num;
2422 		entry->lun_num = lun->lun;
2423 #ifdef CTL_TIME_IO
2424 		entry->start_bt = io->io_hdr.start_bt;
2425 #endif
2426 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2427 		entry->cdb_len = io->scsiio.cdb_len;
2428 		if (io->io_hdr.blocker != NULL)
2429 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2430 
2431 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2432 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2433 
2434 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2435 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2436 
2437 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2438 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2439 
2440 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2441 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2442 
2443 		if (io->io_hdr.flags & CTL_FLAG_STATUS_QUEUED)
2444 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_QUEUED;
2445 
2446 		if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT)
2447 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_SENT;
2448 		(*cur_fill_num)++;
2449 	}
2450 	mtx_unlock(&lun->lun_lock);
2451 }
2452 
2453 /*
2454  * Escape characters that are illegal or not recommended in XML.
2455  */
2456 int
2457 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2458 {
2459 	char *end = str + size;
2460 	int retval;
2461 
2462 	retval = 0;
2463 
2464 	for (; *str && str < end; str++) {
2465 		switch (*str) {
2466 		case '&':
2467 			retval = sbuf_printf(sb, "&amp;");
2468 			break;
2469 		case '>':
2470 			retval = sbuf_printf(sb, "&gt;");
2471 			break;
2472 		case '<':
2473 			retval = sbuf_printf(sb, "&lt;");
2474 			break;
2475 		default:
2476 			retval = sbuf_putc(sb, *str);
2477 			break;
2478 		}
2479 
2480 		if (retval != 0)
2481 			break;
2482 	}
2483 
2484 	return (retval);
2485 }
2486 
2487 static void
2488 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2489 {
2490 	struct scsi_vpd_id_descriptor *desc;
2491 	int i;
2492 
2493 	if (id == NULL || id->len < 4)
2494 		return;
2495 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2496 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2497 	case SVPD_ID_TYPE_T10:
2498 		sbuf_printf(sb, "t10.");
2499 		break;
2500 	case SVPD_ID_TYPE_EUI64:
2501 		sbuf_printf(sb, "eui.");
2502 		break;
2503 	case SVPD_ID_TYPE_NAA:
2504 		sbuf_printf(sb, "naa.");
2505 		break;
2506 	case SVPD_ID_TYPE_SCSI_NAME:
2507 		break;
2508 	}
2509 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2510 	case SVPD_ID_CODESET_BINARY:
2511 		for (i = 0; i < desc->length; i++)
2512 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2513 		break;
2514 	case SVPD_ID_CODESET_ASCII:
2515 		sbuf_printf(sb, "%.*s", (int)desc->length,
2516 		    (char *)desc->identifier);
2517 		break;
2518 	case SVPD_ID_CODESET_UTF8:
2519 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2520 		break;
2521 	}
2522 }
2523 
2524 static int
2525 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2526 	  struct thread *td)
2527 {
2528 	struct ctl_softc *softc = dev->si_drv1;
2529 	struct ctl_port *port;
2530 	struct ctl_lun *lun;
2531 	int retval;
2532 
2533 	retval = 0;
2534 
2535 	switch (cmd) {
2536 	case CTL_IO:
2537 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2538 		break;
2539 	case CTL_ENABLE_PORT:
2540 	case CTL_DISABLE_PORT:
2541 	case CTL_SET_PORT_WWNS: {
2542 		struct ctl_port *port;
2543 		struct ctl_port_entry *entry;
2544 
2545 		entry = (struct ctl_port_entry *)addr;
2546 
2547 		mtx_lock(&softc->ctl_lock);
2548 		STAILQ_FOREACH(port, &softc->port_list, links) {
2549 			int action, done;
2550 
2551 			if (port->targ_port < softc->port_min ||
2552 			    port->targ_port >= softc->port_max)
2553 				continue;
2554 
2555 			action = 0;
2556 			done = 0;
2557 			if ((entry->port_type == CTL_PORT_NONE)
2558 			 && (entry->targ_port == port->targ_port)) {
2559 				/*
2560 				 * If the user only wants to enable or
2561 				 * disable or set WWNs on a specific port,
2562 				 * do the operation and we're done.
2563 				 */
2564 				action = 1;
2565 				done = 1;
2566 			} else if (entry->port_type & port->port_type) {
2567 				/*
2568 				 * Compare the user's type mask with the
2569 				 * particular frontend type to see if we
2570 				 * have a match.
2571 				 */
2572 				action = 1;
2573 				done = 0;
2574 
2575 				/*
2576 				 * Make sure the user isn't trying to set
2577 				 * WWNs on multiple ports at the same time.
2578 				 */
2579 				if (cmd == CTL_SET_PORT_WWNS) {
2580 					printf("%s: Can't set WWNs on "
2581 					       "multiple ports\n", __func__);
2582 					retval = EINVAL;
2583 					break;
2584 				}
2585 			}
2586 			if (action == 0)
2587 				continue;
2588 
2589 			/*
2590 			 * XXX KDM we have to drop the lock here, because
2591 			 * the online/offline operations can potentially
2592 			 * block.  We need to reference count the frontends
2593 			 * so they can't go away,
2594 			 */
2595 			if (cmd == CTL_ENABLE_PORT) {
2596 				mtx_unlock(&softc->ctl_lock);
2597 				ctl_port_online(port);
2598 				mtx_lock(&softc->ctl_lock);
2599 			} else if (cmd == CTL_DISABLE_PORT) {
2600 				mtx_unlock(&softc->ctl_lock);
2601 				ctl_port_offline(port);
2602 				mtx_lock(&softc->ctl_lock);
2603 			} else if (cmd == CTL_SET_PORT_WWNS) {
2604 				ctl_port_set_wwns(port,
2605 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2606 				    1 : 0, entry->wwnn,
2607 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2608 				    1 : 0, entry->wwpn);
2609 			}
2610 			if (done != 0)
2611 				break;
2612 		}
2613 		mtx_unlock(&softc->ctl_lock);
2614 		break;
2615 	}
2616 	case CTL_GET_OOA: {
2617 		struct ctl_ooa *ooa_hdr;
2618 		struct ctl_ooa_entry *entries;
2619 		uint32_t cur_fill_num;
2620 
2621 		ooa_hdr = (struct ctl_ooa *)addr;
2622 
2623 		if ((ooa_hdr->alloc_len == 0)
2624 		 || (ooa_hdr->alloc_num == 0)) {
2625 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2626 			       "must be non-zero\n", __func__,
2627 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2628 			retval = EINVAL;
2629 			break;
2630 		}
2631 
2632 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2633 		    sizeof(struct ctl_ooa_entry))) {
2634 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2635 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2636 			       __func__, ooa_hdr->alloc_len,
2637 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2638 			retval = EINVAL;
2639 			break;
2640 		}
2641 
2642 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2643 		if (entries == NULL) {
2644 			printf("%s: could not allocate %d bytes for OOA "
2645 			       "dump\n", __func__, ooa_hdr->alloc_len);
2646 			retval = ENOMEM;
2647 			break;
2648 		}
2649 
2650 		mtx_lock(&softc->ctl_lock);
2651 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2652 		    (ooa_hdr->lun_num >= ctl_max_luns ||
2653 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2654 			mtx_unlock(&softc->ctl_lock);
2655 			free(entries, M_CTL);
2656 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2657 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2658 			retval = EINVAL;
2659 			break;
2660 		}
2661 
2662 		cur_fill_num = 0;
2663 
2664 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2665 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2666 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2667 				    ooa_hdr, entries);
2668 			}
2669 		} else {
2670 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2671 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2672 			    entries);
2673 		}
2674 		mtx_unlock(&softc->ctl_lock);
2675 
2676 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2677 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2678 			sizeof(struct ctl_ooa_entry);
2679 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2680 		if (retval != 0) {
2681 			printf("%s: error copying out %d bytes for OOA dump\n",
2682 			       __func__, ooa_hdr->fill_len);
2683 		}
2684 
2685 		getbinuptime(&ooa_hdr->cur_bt);
2686 
2687 		if (cur_fill_num > ooa_hdr->alloc_num) {
2688 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2689 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2690 		} else {
2691 			ooa_hdr->dropped_num = 0;
2692 			ooa_hdr->status = CTL_OOA_OK;
2693 		}
2694 
2695 		free(entries, M_CTL);
2696 		break;
2697 	}
2698 	case CTL_DELAY_IO: {
2699 		struct ctl_io_delay_info *delay_info;
2700 
2701 		delay_info = (struct ctl_io_delay_info *)addr;
2702 
2703 #ifdef CTL_IO_DELAY
2704 		mtx_lock(&softc->ctl_lock);
2705 		if (delay_info->lun_id >= ctl_max_luns ||
2706 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2707 			mtx_unlock(&softc->ctl_lock);
2708 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2709 			break;
2710 		}
2711 		mtx_lock(&lun->lun_lock);
2712 		mtx_unlock(&softc->ctl_lock);
2713 		delay_info->status = CTL_DELAY_STATUS_OK;
2714 		switch (delay_info->delay_type) {
2715 		case CTL_DELAY_TYPE_CONT:
2716 		case CTL_DELAY_TYPE_ONESHOT:
2717 			break;
2718 		default:
2719 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2720 			break;
2721 		}
2722 		switch (delay_info->delay_loc) {
2723 		case CTL_DELAY_LOC_DATAMOVE:
2724 			lun->delay_info.datamove_type = delay_info->delay_type;
2725 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2726 			break;
2727 		case CTL_DELAY_LOC_DONE:
2728 			lun->delay_info.done_type = delay_info->delay_type;
2729 			lun->delay_info.done_delay = delay_info->delay_secs;
2730 			break;
2731 		default:
2732 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2733 			break;
2734 		}
2735 		mtx_unlock(&lun->lun_lock);
2736 #else
2737 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2738 #endif /* CTL_IO_DELAY */
2739 		break;
2740 	}
2741 	case CTL_ERROR_INJECT: {
2742 		struct ctl_error_desc *err_desc, *new_err_desc;
2743 
2744 		err_desc = (struct ctl_error_desc *)addr;
2745 
2746 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2747 				      M_WAITOK | M_ZERO);
2748 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2749 
2750 		mtx_lock(&softc->ctl_lock);
2751 		if (err_desc->lun_id >= ctl_max_luns ||
2752 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2753 			mtx_unlock(&softc->ctl_lock);
2754 			free(new_err_desc, M_CTL);
2755 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2756 			       __func__, (uintmax_t)err_desc->lun_id);
2757 			retval = EINVAL;
2758 			break;
2759 		}
2760 		mtx_lock(&lun->lun_lock);
2761 		mtx_unlock(&softc->ctl_lock);
2762 
2763 		/*
2764 		 * We could do some checking here to verify the validity
2765 		 * of the request, but given the complexity of error
2766 		 * injection requests, the checking logic would be fairly
2767 		 * complex.
2768 		 *
2769 		 * For now, if the request is invalid, it just won't get
2770 		 * executed and might get deleted.
2771 		 */
2772 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2773 
2774 		/*
2775 		 * XXX KDM check to make sure the serial number is unique,
2776 		 * in case we somehow manage to wrap.  That shouldn't
2777 		 * happen for a very long time, but it's the right thing to
2778 		 * do.
2779 		 */
2780 		new_err_desc->serial = lun->error_serial;
2781 		err_desc->serial = lun->error_serial;
2782 		lun->error_serial++;
2783 
2784 		mtx_unlock(&lun->lun_lock);
2785 		break;
2786 	}
2787 	case CTL_ERROR_INJECT_DELETE: {
2788 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2789 		int delete_done;
2790 
2791 		delete_desc = (struct ctl_error_desc *)addr;
2792 		delete_done = 0;
2793 
2794 		mtx_lock(&softc->ctl_lock);
2795 		if (delete_desc->lun_id >= ctl_max_luns ||
2796 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2797 			mtx_unlock(&softc->ctl_lock);
2798 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2799 			       __func__, (uintmax_t)delete_desc->lun_id);
2800 			retval = EINVAL;
2801 			break;
2802 		}
2803 		mtx_lock(&lun->lun_lock);
2804 		mtx_unlock(&softc->ctl_lock);
2805 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2806 			if (desc->serial != delete_desc->serial)
2807 				continue;
2808 
2809 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2810 				      links);
2811 			free(desc, M_CTL);
2812 			delete_done = 1;
2813 		}
2814 		mtx_unlock(&lun->lun_lock);
2815 		if (delete_done == 0) {
2816 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2817 			       "error serial %ju on LUN %u\n", __func__,
2818 			       delete_desc->serial, delete_desc->lun_id);
2819 			retval = EINVAL;
2820 			break;
2821 		}
2822 		break;
2823 	}
2824 	case CTL_DUMP_STRUCTS: {
2825 		int j, k;
2826 		struct ctl_port *port;
2827 		struct ctl_frontend *fe;
2828 
2829 		mtx_lock(&softc->ctl_lock);
2830 		printf("CTL Persistent Reservation information start:\n");
2831 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2832 			mtx_lock(&lun->lun_lock);
2833 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2834 				mtx_unlock(&lun->lun_lock);
2835 				continue;
2836 			}
2837 
2838 			for (j = 0; j < ctl_max_ports; j++) {
2839 				if (lun->pr_keys[j] == NULL)
2840 					continue;
2841 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2842 					if (lun->pr_keys[j][k] == 0)
2843 						continue;
2844 					printf("  LUN %ju port %d iid %d key "
2845 					       "%#jx\n", lun->lun, j, k,
2846 					       (uintmax_t)lun->pr_keys[j][k]);
2847 				}
2848 			}
2849 			mtx_unlock(&lun->lun_lock);
2850 		}
2851 		printf("CTL Persistent Reservation information end\n");
2852 		printf("CTL Ports:\n");
2853 		STAILQ_FOREACH(port, &softc->port_list, links) {
2854 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2855 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2856 			       port->frontend->name, port->port_type,
2857 			       port->physical_port, port->virtual_port,
2858 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2859 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2860 				if (port->wwpn_iid[j].in_use == 0 &&
2861 				    port->wwpn_iid[j].wwpn == 0 &&
2862 				    port->wwpn_iid[j].name == NULL)
2863 					continue;
2864 
2865 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2866 				    j, port->wwpn_iid[j].in_use,
2867 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2868 				    port->wwpn_iid[j].name);
2869 			}
2870 		}
2871 		printf("CTL Port information end\n");
2872 		mtx_unlock(&softc->ctl_lock);
2873 		/*
2874 		 * XXX KDM calling this without a lock.  We'd likely want
2875 		 * to drop the lock before calling the frontend's dump
2876 		 * routine anyway.
2877 		 */
2878 		printf("CTL Frontends:\n");
2879 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2880 			printf("  Frontend '%s'\n", fe->name);
2881 			if (fe->fe_dump != NULL)
2882 				fe->fe_dump();
2883 		}
2884 		printf("CTL Frontend information end\n");
2885 		break;
2886 	}
2887 	case CTL_LUN_REQ: {
2888 		struct ctl_lun_req *lun_req;
2889 		struct ctl_backend_driver *backend;
2890 		void *packed;
2891 		nvlist_t *tmp_args_nvl;
2892 		size_t packed_len;
2893 
2894 		lun_req = (struct ctl_lun_req *)addr;
2895 		tmp_args_nvl = lun_req->args_nvl;
2896 
2897 		backend = ctl_backend_find(lun_req->backend);
2898 		if (backend == NULL) {
2899 			lun_req->status = CTL_LUN_ERROR;
2900 			snprintf(lun_req->error_str,
2901 				 sizeof(lun_req->error_str),
2902 				 "Backend \"%s\" not found.",
2903 				 lun_req->backend);
2904 			break;
2905 		}
2906 
2907 		if (lun_req->args != NULL) {
2908 			packed = malloc(lun_req->args_len, M_CTL, M_WAITOK);
2909 			if (copyin(lun_req->args, packed, lun_req->args_len) != 0) {
2910 				free(packed, M_CTL);
2911 				lun_req->status = CTL_LUN_ERROR;
2912 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2913 				    "Cannot copyin args.");
2914 				break;
2915 			}
2916 			lun_req->args_nvl = nvlist_unpack(packed,
2917 			    lun_req->args_len, 0);
2918 			free(packed, M_CTL);
2919 
2920 			if (lun_req->args_nvl == NULL) {
2921 				lun_req->status = CTL_LUN_ERROR;
2922 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2923 				    "Cannot unpack args nvlist.");
2924 				break;
2925 			}
2926 		} else
2927 			lun_req->args_nvl = nvlist_create(0);
2928 
2929 		retval = backend->ioctl(dev, cmd, addr, flag, td);
2930 		nvlist_destroy(lun_req->args_nvl);
2931 		lun_req->args_nvl = tmp_args_nvl;
2932 
2933 		if (lun_req->result_nvl != NULL) {
2934 			if (lun_req->result != NULL) {
2935 				packed = nvlist_pack(lun_req->result_nvl,
2936 				    &packed_len);
2937 				if (packed == NULL) {
2938 					lun_req->status = CTL_LUN_ERROR;
2939 					snprintf(lun_req->error_str,
2940 					    sizeof(lun_req->error_str),
2941 					    "Cannot pack result nvlist.");
2942 					break;
2943 				}
2944 
2945 				if (packed_len > lun_req->result_len) {
2946 					lun_req->status = CTL_LUN_ERROR;
2947 					snprintf(lun_req->error_str,
2948 					    sizeof(lun_req->error_str),
2949 					    "Result nvlist too large.");
2950 					free(packed, M_NVLIST);
2951 					break;
2952 				}
2953 
2954 				if (copyout(packed, lun_req->result, packed_len)) {
2955 					lun_req->status = CTL_LUN_ERROR;
2956 					snprintf(lun_req->error_str,
2957 					    sizeof(lun_req->error_str),
2958 					    "Cannot copyout() the result.");
2959 					free(packed, M_NVLIST);
2960 					break;
2961 				}
2962 
2963 				lun_req->result_len = packed_len;
2964 				free(packed, M_NVLIST);
2965 			}
2966 
2967 			nvlist_destroy(lun_req->result_nvl);
2968 		}
2969 		break;
2970 	}
2971 	case CTL_LUN_LIST: {
2972 		struct sbuf *sb;
2973 		struct ctl_lun_list *list;
2974 		const char *name, *value;
2975 		void *cookie;
2976 		int type;
2977 
2978 		list = (struct ctl_lun_list *)addr;
2979 
2980 		/*
2981 		 * Allocate a fixed length sbuf here, based on the length
2982 		 * of the user's buffer.  We could allocate an auto-extending
2983 		 * buffer, and then tell the user how much larger our
2984 		 * amount of data is than his buffer, but that presents
2985 		 * some problems:
2986 		 *
2987 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2988 		 *     we can't hold a lock while calling them with an
2989 		 *     auto-extending buffer.
2990  		 *
2991 		 * 2.  There is not currently a LUN reference counting
2992 		 *     mechanism, outside of outstanding transactions on
2993 		 *     the LUN's OOA queue.  So a LUN could go away on us
2994 		 *     while we're getting the LUN number, backend-specific
2995 		 *     information, etc.  Thus, given the way things
2996 		 *     currently work, we need to hold the CTL lock while
2997 		 *     grabbing LUN information.
2998 		 *
2999 		 * So, from the user's standpoint, the best thing to do is
3000 		 * allocate what he thinks is a reasonable buffer length,
3001 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3002 		 * double the buffer length and try again.  (And repeat
3003 		 * that until he succeeds.)
3004 		 */
3005 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3006 		if (sb == NULL) {
3007 			list->status = CTL_LUN_LIST_ERROR;
3008 			snprintf(list->error_str, sizeof(list->error_str),
3009 				 "Unable to allocate %d bytes for LUN list",
3010 				 list->alloc_len);
3011 			break;
3012 		}
3013 
3014 		sbuf_printf(sb, "<ctllunlist>\n");
3015 
3016 		mtx_lock(&softc->ctl_lock);
3017 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3018 			mtx_lock(&lun->lun_lock);
3019 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3020 					     (uintmax_t)lun->lun);
3021 
3022 			/*
3023 			 * Bail out as soon as we see that we've overfilled
3024 			 * the buffer.
3025 			 */
3026 			if (retval != 0)
3027 				break;
3028 
3029 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3030 					     "</backend_type>\n",
3031 					     (lun->backend == NULL) ?  "none" :
3032 					     lun->backend->name);
3033 
3034 			if (retval != 0)
3035 				break;
3036 
3037 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3038 					     lun->be_lun->lun_type);
3039 
3040 			if (retval != 0)
3041 				break;
3042 
3043 			if (lun->backend == NULL) {
3044 				retval = sbuf_printf(sb, "</lun>\n");
3045 				if (retval != 0)
3046 					break;
3047 				continue;
3048 			}
3049 
3050 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3051 					     (lun->be_lun->maxlba > 0) ?
3052 					     lun->be_lun->maxlba + 1 : 0);
3053 
3054 			if (retval != 0)
3055 				break;
3056 
3057 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3058 					     lun->be_lun->blocksize);
3059 
3060 			if (retval != 0)
3061 				break;
3062 
3063 			retval = sbuf_printf(sb, "\t<serial_number>");
3064 
3065 			if (retval != 0)
3066 				break;
3067 
3068 			retval = ctl_sbuf_printf_esc(sb,
3069 			    lun->be_lun->serial_num,
3070 			    sizeof(lun->be_lun->serial_num));
3071 
3072 			if (retval != 0)
3073 				break;
3074 
3075 			retval = sbuf_printf(sb, "</serial_number>\n");
3076 
3077 			if (retval != 0)
3078 				break;
3079 
3080 			retval = sbuf_printf(sb, "\t<device_id>");
3081 
3082 			if (retval != 0)
3083 				break;
3084 
3085 			retval = ctl_sbuf_printf_esc(sb,
3086 			    lun->be_lun->device_id,
3087 			    sizeof(lun->be_lun->device_id));
3088 
3089 			if (retval != 0)
3090 				break;
3091 
3092 			retval = sbuf_printf(sb, "</device_id>\n");
3093 
3094 			if (retval != 0)
3095 				break;
3096 
3097 			if (lun->backend->lun_info != NULL) {
3098 				retval = lun->backend->lun_info(lun->be_lun, sb);
3099 				if (retval != 0)
3100 					break;
3101 			}
3102 
3103 			cookie = NULL;
3104 			while ((name = nvlist_next(lun->be_lun->options, &type,
3105 			    &cookie)) != NULL) {
3106 				sbuf_printf(sb, "\t<%s>", name);
3107 
3108 				if (type == NV_TYPE_STRING) {
3109 					value = dnvlist_get_string(
3110 					    lun->be_lun->options, name, NULL);
3111 					if (value != NULL)
3112 						sbuf_printf(sb, "%s", value);
3113 				}
3114 
3115 				sbuf_printf(sb, "</%s>\n", name);
3116 			}
3117 
3118 			retval = sbuf_printf(sb, "</lun>\n");
3119 
3120 			if (retval != 0)
3121 				break;
3122 			mtx_unlock(&lun->lun_lock);
3123 		}
3124 		if (lun != NULL)
3125 			mtx_unlock(&lun->lun_lock);
3126 		mtx_unlock(&softc->ctl_lock);
3127 
3128 		if ((retval != 0)
3129 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3130 			retval = 0;
3131 			sbuf_delete(sb);
3132 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3133 			snprintf(list->error_str, sizeof(list->error_str),
3134 				 "Out of space, %d bytes is too small",
3135 				 list->alloc_len);
3136 			break;
3137 		}
3138 
3139 		sbuf_finish(sb);
3140 
3141 		retval = copyout(sbuf_data(sb), list->lun_xml,
3142 				 sbuf_len(sb) + 1);
3143 
3144 		list->fill_len = sbuf_len(sb) + 1;
3145 		list->status = CTL_LUN_LIST_OK;
3146 		sbuf_delete(sb);
3147 		break;
3148 	}
3149 	case CTL_ISCSI: {
3150 		struct ctl_iscsi *ci;
3151 		struct ctl_frontend *fe;
3152 
3153 		ci = (struct ctl_iscsi *)addr;
3154 
3155 		fe = ctl_frontend_find("iscsi");
3156 		if (fe == NULL) {
3157 			ci->status = CTL_ISCSI_ERROR;
3158 			snprintf(ci->error_str, sizeof(ci->error_str),
3159 			    "Frontend \"iscsi\" not found.");
3160 			break;
3161 		}
3162 
3163 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3164 		break;
3165 	}
3166 	case CTL_PORT_REQ: {
3167 		struct ctl_req *req;
3168 		struct ctl_frontend *fe;
3169 		void *packed;
3170 		nvlist_t *tmp_args_nvl;
3171 		size_t packed_len;
3172 
3173 		req = (struct ctl_req *)addr;
3174 		tmp_args_nvl = req->args_nvl;
3175 
3176 		fe = ctl_frontend_find(req->driver);
3177 		if (fe == NULL) {
3178 			req->status = CTL_LUN_ERROR;
3179 			snprintf(req->error_str, sizeof(req->error_str),
3180 			    "Frontend \"%s\" not found.", req->driver);
3181 			break;
3182 		}
3183 
3184 		if (req->args != NULL) {
3185 			packed = malloc(req->args_len, M_CTL, M_WAITOK);
3186 			if (copyin(req->args, packed, req->args_len) != 0) {
3187 				free(packed, M_CTL);
3188 				req->status = CTL_LUN_ERROR;
3189 				snprintf(req->error_str, sizeof(req->error_str),
3190 				    "Cannot copyin args.");
3191 				break;
3192 			}
3193 			req->args_nvl = nvlist_unpack(packed,
3194 			    req->args_len, 0);
3195 			free(packed, M_CTL);
3196 
3197 			if (req->args_nvl == NULL) {
3198 				req->status = CTL_LUN_ERROR;
3199 				snprintf(req->error_str, sizeof(req->error_str),
3200 				    "Cannot unpack args nvlist.");
3201 				break;
3202 			}
3203 		} else
3204 			req->args_nvl = nvlist_create(0);
3205 
3206 		if (fe->ioctl)
3207 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3208 		else
3209 			retval = ENODEV;
3210 
3211 		nvlist_destroy(req->args_nvl);
3212 		req->args_nvl = tmp_args_nvl;
3213 
3214 		if (req->result_nvl != NULL) {
3215 			if (req->result != NULL) {
3216 				packed = nvlist_pack(req->result_nvl,
3217 				    &packed_len);
3218 				if (packed == NULL) {
3219 					req->status = CTL_LUN_ERROR;
3220 					snprintf(req->error_str,
3221 					    sizeof(req->error_str),
3222 					    "Cannot pack result nvlist.");
3223 					break;
3224 				}
3225 
3226 				if (packed_len > req->result_len) {
3227 					req->status = CTL_LUN_ERROR;
3228 					snprintf(req->error_str,
3229 					    sizeof(req->error_str),
3230 					    "Result nvlist too large.");
3231 					free(packed, M_NVLIST);
3232 					break;
3233 				}
3234 
3235 				if (copyout(packed, req->result, packed_len)) {
3236 					req->status = CTL_LUN_ERROR;
3237 					snprintf(req->error_str,
3238 					    sizeof(req->error_str),
3239 					    "Cannot copyout() the result.");
3240 					free(packed, M_NVLIST);
3241 					break;
3242 				}
3243 
3244 				req->result_len = packed_len;
3245 				free(packed, M_NVLIST);
3246 			}
3247 
3248 			nvlist_destroy(req->result_nvl);
3249 		}
3250 		break;
3251 	}
3252 	case CTL_PORT_LIST: {
3253 		struct sbuf *sb;
3254 		struct ctl_port *port;
3255 		struct ctl_lun_list *list;
3256 		const char *name, *value;
3257 		void *cookie;
3258 		int j, type;
3259 		uint32_t plun;
3260 
3261 		list = (struct ctl_lun_list *)addr;
3262 
3263 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3264 		if (sb == NULL) {
3265 			list->status = CTL_LUN_LIST_ERROR;
3266 			snprintf(list->error_str, sizeof(list->error_str),
3267 				 "Unable to allocate %d bytes for LUN list",
3268 				 list->alloc_len);
3269 			break;
3270 		}
3271 
3272 		sbuf_printf(sb, "<ctlportlist>\n");
3273 
3274 		mtx_lock(&softc->ctl_lock);
3275 		STAILQ_FOREACH(port, &softc->port_list, links) {
3276 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3277 					     (uintmax_t)port->targ_port);
3278 
3279 			/*
3280 			 * Bail out as soon as we see that we've overfilled
3281 			 * the buffer.
3282 			 */
3283 			if (retval != 0)
3284 				break;
3285 
3286 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3287 			    "</frontend_type>\n", port->frontend->name);
3288 			if (retval != 0)
3289 				break;
3290 
3291 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3292 					     port->port_type);
3293 			if (retval != 0)
3294 				break;
3295 
3296 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3297 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3298 			if (retval != 0)
3299 				break;
3300 
3301 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3302 			    port->port_name);
3303 			if (retval != 0)
3304 				break;
3305 
3306 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3307 			    port->physical_port);
3308 			if (retval != 0)
3309 				break;
3310 
3311 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3312 			    port->virtual_port);
3313 			if (retval != 0)
3314 				break;
3315 
3316 			if (port->target_devid != NULL) {
3317 				sbuf_printf(sb, "\t<target>");
3318 				ctl_id_sbuf(port->target_devid, sb);
3319 				sbuf_printf(sb, "</target>\n");
3320 			}
3321 
3322 			if (port->port_devid != NULL) {
3323 				sbuf_printf(sb, "\t<port>");
3324 				ctl_id_sbuf(port->port_devid, sb);
3325 				sbuf_printf(sb, "</port>\n");
3326 			}
3327 
3328 			if (port->port_info != NULL) {
3329 				retval = port->port_info(port->onoff_arg, sb);
3330 				if (retval != 0)
3331 					break;
3332 			}
3333 
3334 			cookie = NULL;
3335 			while ((name = nvlist_next(port->options, &type,
3336 			    &cookie)) != NULL) {
3337 				sbuf_printf(sb, "\t<%s>", name);
3338 
3339 				if (type == NV_TYPE_STRING) {
3340 					value = dnvlist_get_string(port->options,
3341 					    name, NULL);
3342 					if (value != NULL)
3343 						sbuf_printf(sb, "%s", value);
3344 				}
3345 
3346 				sbuf_printf(sb, "</%s>\n", name);
3347 			}
3348 
3349 			if (port->lun_map != NULL) {
3350 				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3351 				for (j = 0; j < port->lun_map_size; j++) {
3352 					plun = ctl_lun_map_from_port(port, j);
3353 					if (plun == UINT32_MAX)
3354 						continue;
3355 					sbuf_printf(sb,
3356 					    "\t<lun id=\"%u\">%u</lun>\n",
3357 					    j, plun);
3358 				}
3359 			}
3360 
3361 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3362 				if (port->wwpn_iid[j].in_use == 0 ||
3363 				    (port->wwpn_iid[j].wwpn == 0 &&
3364 				     port->wwpn_iid[j].name == NULL))
3365 					continue;
3366 
3367 				if (port->wwpn_iid[j].name != NULL)
3368 					retval = sbuf_printf(sb,
3369 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3370 					    j, port->wwpn_iid[j].name);
3371 				else
3372 					retval = sbuf_printf(sb,
3373 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3374 					    j, port->wwpn_iid[j].wwpn);
3375 				if (retval != 0)
3376 					break;
3377 			}
3378 			if (retval != 0)
3379 				break;
3380 
3381 			retval = sbuf_printf(sb, "</targ_port>\n");
3382 			if (retval != 0)
3383 				break;
3384 		}
3385 		mtx_unlock(&softc->ctl_lock);
3386 
3387 		if ((retval != 0)
3388 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3389 			retval = 0;
3390 			sbuf_delete(sb);
3391 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3392 			snprintf(list->error_str, sizeof(list->error_str),
3393 				 "Out of space, %d bytes is too small",
3394 				 list->alloc_len);
3395 			break;
3396 		}
3397 
3398 		sbuf_finish(sb);
3399 
3400 		retval = copyout(sbuf_data(sb), list->lun_xml,
3401 				 sbuf_len(sb) + 1);
3402 
3403 		list->fill_len = sbuf_len(sb) + 1;
3404 		list->status = CTL_LUN_LIST_OK;
3405 		sbuf_delete(sb);
3406 		break;
3407 	}
3408 	case CTL_LUN_MAP: {
3409 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3410 		struct ctl_port *port;
3411 
3412 		mtx_lock(&softc->ctl_lock);
3413 		if (lm->port < softc->port_min ||
3414 		    lm->port >= softc->port_max ||
3415 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3416 			mtx_unlock(&softc->ctl_lock);
3417 			return (ENXIO);
3418 		}
3419 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3420 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3421 				if (ctl_lun_map_to_port(port, lun->lun) ==
3422 				    UINT32_MAX)
3423 					continue;
3424 				mtx_lock(&lun->lun_lock);
3425 				ctl_est_ua_port(lun, lm->port, -1,
3426 				    CTL_UA_LUN_CHANGE);
3427 				mtx_unlock(&lun->lun_lock);
3428 			}
3429 		}
3430 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3431 		if (lm->plun != UINT32_MAX) {
3432 			if (lm->lun == UINT32_MAX)
3433 				retval = ctl_lun_map_unset(port, lm->plun);
3434 			else if (lm->lun < ctl_max_luns &&
3435 			    softc->ctl_luns[lm->lun] != NULL)
3436 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3437 			else
3438 				return (ENXIO);
3439 		} else {
3440 			if (lm->lun == UINT32_MAX)
3441 				retval = ctl_lun_map_deinit(port);
3442 			else
3443 				retval = ctl_lun_map_init(port);
3444 		}
3445 		if (port->status & CTL_PORT_STATUS_ONLINE)
3446 			ctl_isc_announce_port(port);
3447 		break;
3448 	}
3449 	case CTL_GET_LUN_STATS: {
3450 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3451 		int i;
3452 
3453 		/*
3454 		 * XXX KDM no locking here.  If the LUN list changes,
3455 		 * things can blow up.
3456 		 */
3457 		i = 0;
3458 		stats->status = CTL_SS_OK;
3459 		stats->fill_len = 0;
3460 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3461 			if (lun->lun < stats->first_item)
3462 				continue;
3463 			if (stats->fill_len + sizeof(lun->stats) >
3464 			    stats->alloc_len) {
3465 				stats->status = CTL_SS_NEED_MORE_SPACE;
3466 				break;
3467 			}
3468 			retval = copyout(&lun->stats, &stats->stats[i++],
3469 					 sizeof(lun->stats));
3470 			if (retval != 0)
3471 				break;
3472 			stats->fill_len += sizeof(lun->stats);
3473 		}
3474 		stats->num_items = softc->num_luns;
3475 		stats->flags = CTL_STATS_FLAG_NONE;
3476 #ifdef CTL_TIME_IO
3477 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3478 #endif
3479 		getnanouptime(&stats->timestamp);
3480 		break;
3481 	}
3482 	case CTL_GET_PORT_STATS: {
3483 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3484 		int i;
3485 
3486 		/*
3487 		 * XXX KDM no locking here.  If the LUN list changes,
3488 		 * things can blow up.
3489 		 */
3490 		i = 0;
3491 		stats->status = CTL_SS_OK;
3492 		stats->fill_len = 0;
3493 		STAILQ_FOREACH(port, &softc->port_list, links) {
3494 			if (port->targ_port < stats->first_item)
3495 				continue;
3496 			if (stats->fill_len + sizeof(port->stats) >
3497 			    stats->alloc_len) {
3498 				stats->status = CTL_SS_NEED_MORE_SPACE;
3499 				break;
3500 			}
3501 			retval = copyout(&port->stats, &stats->stats[i++],
3502 					 sizeof(port->stats));
3503 			if (retval != 0)
3504 				break;
3505 			stats->fill_len += sizeof(port->stats);
3506 		}
3507 		stats->num_items = softc->num_ports;
3508 		stats->flags = CTL_STATS_FLAG_NONE;
3509 #ifdef CTL_TIME_IO
3510 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3511 #endif
3512 		getnanouptime(&stats->timestamp);
3513 		break;
3514 	}
3515 	default: {
3516 		/* XXX KDM should we fix this? */
3517 #if 0
3518 		struct ctl_backend_driver *backend;
3519 		unsigned int type;
3520 		int found;
3521 
3522 		found = 0;
3523 
3524 		/*
3525 		 * We encode the backend type as the ioctl type for backend
3526 		 * ioctls.  So parse it out here, and then search for a
3527 		 * backend of this type.
3528 		 */
3529 		type = _IOC_TYPE(cmd);
3530 
3531 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3532 			if (backend->type == type) {
3533 				found = 1;
3534 				break;
3535 			}
3536 		}
3537 		if (found == 0) {
3538 			printf("ctl: unknown ioctl command %#lx or backend "
3539 			       "%d\n", cmd, type);
3540 			retval = EINVAL;
3541 			break;
3542 		}
3543 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3544 #endif
3545 		retval = ENOTTY;
3546 		break;
3547 	}
3548 	}
3549 	return (retval);
3550 }
3551 
3552 uint32_t
3553 ctl_get_initindex(struct ctl_nexus *nexus)
3554 {
3555 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3556 }
3557 
3558 int
3559 ctl_lun_map_init(struct ctl_port *port)
3560 {
3561 	struct ctl_softc *softc = port->ctl_softc;
3562 	struct ctl_lun *lun;
3563 	int size = ctl_lun_map_size;
3564 	uint32_t i;
3565 
3566 	if (port->lun_map == NULL || port->lun_map_size < size) {
3567 		port->lun_map_size = 0;
3568 		free(port->lun_map, M_CTL);
3569 		port->lun_map = malloc(size * sizeof(uint32_t),
3570 		    M_CTL, M_NOWAIT);
3571 	}
3572 	if (port->lun_map == NULL)
3573 		return (ENOMEM);
3574 	for (i = 0; i < size; i++)
3575 		port->lun_map[i] = UINT32_MAX;
3576 	port->lun_map_size = size;
3577 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3578 		if (port->lun_disable != NULL) {
3579 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3580 				port->lun_disable(port->targ_lun_arg, lun->lun);
3581 		}
3582 		ctl_isc_announce_port(port);
3583 	}
3584 	return (0);
3585 }
3586 
3587 int
3588 ctl_lun_map_deinit(struct ctl_port *port)
3589 {
3590 	struct ctl_softc *softc = port->ctl_softc;
3591 	struct ctl_lun *lun;
3592 
3593 	if (port->lun_map == NULL)
3594 		return (0);
3595 	port->lun_map_size = 0;
3596 	free(port->lun_map, M_CTL);
3597 	port->lun_map = NULL;
3598 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3599 		if (port->lun_enable != NULL) {
3600 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3601 				port->lun_enable(port->targ_lun_arg, lun->lun);
3602 		}
3603 		ctl_isc_announce_port(port);
3604 	}
3605 	return (0);
3606 }
3607 
3608 int
3609 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3610 {
3611 	int status;
3612 	uint32_t old;
3613 
3614 	if (port->lun_map == NULL) {
3615 		status = ctl_lun_map_init(port);
3616 		if (status != 0)
3617 			return (status);
3618 	}
3619 	if (plun >= port->lun_map_size)
3620 		return (EINVAL);
3621 	old = port->lun_map[plun];
3622 	port->lun_map[plun] = glun;
3623 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3624 		if (port->lun_enable != NULL)
3625 			port->lun_enable(port->targ_lun_arg, plun);
3626 		ctl_isc_announce_port(port);
3627 	}
3628 	return (0);
3629 }
3630 
3631 int
3632 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3633 {
3634 	uint32_t old;
3635 
3636 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3637 		return (0);
3638 	old = port->lun_map[plun];
3639 	port->lun_map[plun] = UINT32_MAX;
3640 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3641 		if (port->lun_disable != NULL)
3642 			port->lun_disable(port->targ_lun_arg, plun);
3643 		ctl_isc_announce_port(port);
3644 	}
3645 	return (0);
3646 }
3647 
3648 uint32_t
3649 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3650 {
3651 
3652 	if (port == NULL)
3653 		return (UINT32_MAX);
3654 	if (port->lun_map == NULL)
3655 		return (lun_id);
3656 	if (lun_id > port->lun_map_size)
3657 		return (UINT32_MAX);
3658 	return (port->lun_map[lun_id]);
3659 }
3660 
3661 uint32_t
3662 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3663 {
3664 	uint32_t i;
3665 
3666 	if (port == NULL)
3667 		return (UINT32_MAX);
3668 	if (port->lun_map == NULL)
3669 		return (lun_id);
3670 	for (i = 0; i < port->lun_map_size; i++) {
3671 		if (port->lun_map[i] == lun_id)
3672 			return (i);
3673 	}
3674 	return (UINT32_MAX);
3675 }
3676 
3677 uint32_t
3678 ctl_decode_lun(uint64_t encoded)
3679 {
3680 	uint8_t lun[8];
3681 	uint32_t result = 0xffffffff;
3682 
3683 	be64enc(lun, encoded);
3684 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3685 	case RPL_LUNDATA_ATYP_PERIPH:
3686 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3687 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3688 			result = lun[1];
3689 		break;
3690 	case RPL_LUNDATA_ATYP_FLAT:
3691 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3692 		    lun[6] == 0 && lun[7] == 0)
3693 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3694 		break;
3695 	case RPL_LUNDATA_ATYP_EXTLUN:
3696 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3697 		case 0x02:
3698 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3699 			case 0x00:
3700 				result = lun[1];
3701 				break;
3702 			case 0x10:
3703 				result = (lun[1] << 16) + (lun[2] << 8) +
3704 				    lun[3];
3705 				break;
3706 			case 0x20:
3707 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3708 					result = (lun[2] << 24) +
3709 					    (lun[3] << 16) + (lun[4] << 8) +
3710 					    lun[5];
3711 				break;
3712 			}
3713 			break;
3714 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3715 			result = 0xffffffff;
3716 			break;
3717 		}
3718 		break;
3719 	}
3720 	return (result);
3721 }
3722 
3723 uint64_t
3724 ctl_encode_lun(uint32_t decoded)
3725 {
3726 	uint64_t l = decoded;
3727 
3728 	if (l <= 0xff)
3729 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3730 	if (l <= 0x3fff)
3731 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3732 	if (l <= 0xffffff)
3733 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3734 		    (l << 32));
3735 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3736 }
3737 
3738 int
3739 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3740 {
3741 	int i;
3742 
3743 	for (i = first; i < last; i++) {
3744 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3745 			return (i);
3746 	}
3747 	return (-1);
3748 }
3749 
3750 int
3751 ctl_set_mask(uint32_t *mask, uint32_t bit)
3752 {
3753 	uint32_t chunk, piece;
3754 
3755 	chunk = bit >> 5;
3756 	piece = bit % (sizeof(uint32_t) * 8);
3757 
3758 	if ((mask[chunk] & (1 << piece)) != 0)
3759 		return (-1);
3760 	else
3761 		mask[chunk] |= (1 << piece);
3762 
3763 	return (0);
3764 }
3765 
3766 int
3767 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3768 {
3769 	uint32_t chunk, piece;
3770 
3771 	chunk = bit >> 5;
3772 	piece = bit % (sizeof(uint32_t) * 8);
3773 
3774 	if ((mask[chunk] & (1 << piece)) == 0)
3775 		return (-1);
3776 	else
3777 		mask[chunk] &= ~(1 << piece);
3778 
3779 	return (0);
3780 }
3781 
3782 int
3783 ctl_is_set(uint32_t *mask, uint32_t bit)
3784 {
3785 	uint32_t chunk, piece;
3786 
3787 	chunk = bit >> 5;
3788 	piece = bit % (sizeof(uint32_t) * 8);
3789 
3790 	if ((mask[chunk] & (1 << piece)) == 0)
3791 		return (0);
3792 	else
3793 		return (1);
3794 }
3795 
3796 static uint64_t
3797 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3798 {
3799 	uint64_t *t;
3800 
3801 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3802 	if (t == NULL)
3803 		return (0);
3804 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3805 }
3806 
3807 static void
3808 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3809 {
3810 	uint64_t *t;
3811 
3812 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3813 	if (t == NULL)
3814 		return;
3815 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3816 }
3817 
3818 static void
3819 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3820 {
3821 	uint64_t *p;
3822 	u_int i;
3823 
3824 	i = residx/CTL_MAX_INIT_PER_PORT;
3825 	if (lun->pr_keys[i] != NULL)
3826 		return;
3827 	mtx_unlock(&lun->lun_lock);
3828 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3829 	    M_WAITOK | M_ZERO);
3830 	mtx_lock(&lun->lun_lock);
3831 	if (lun->pr_keys[i] == NULL)
3832 		lun->pr_keys[i] = p;
3833 	else
3834 		free(p, M_CTL);
3835 }
3836 
3837 static void
3838 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3839 {
3840 	uint64_t *t;
3841 
3842 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3843 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3844 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3845 }
3846 
3847 /*
3848  * ctl_softc, pool_name, total_ctl_io are passed in.
3849  * npool is passed out.
3850  */
3851 int
3852 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3853 		uint32_t total_ctl_io, void **npool)
3854 {
3855 	struct ctl_io_pool *pool;
3856 
3857 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3858 					    M_NOWAIT | M_ZERO);
3859 	if (pool == NULL)
3860 		return (ENOMEM);
3861 
3862 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3863 	pool->ctl_softc = ctl_softc;
3864 #ifdef IO_POOLS
3865 	pool->zone = uma_zsecond_create(pool->name, NULL,
3866 	    NULL, NULL, NULL, ctl_softc->io_zone);
3867 	/* uma_prealloc(pool->zone, total_ctl_io); */
3868 #else
3869 	pool->zone = ctl_softc->io_zone;
3870 #endif
3871 
3872 	*npool = pool;
3873 	return (0);
3874 }
3875 
3876 void
3877 ctl_pool_free(struct ctl_io_pool *pool)
3878 {
3879 
3880 	if (pool == NULL)
3881 		return;
3882 
3883 #ifdef IO_POOLS
3884 	uma_zdestroy(pool->zone);
3885 #endif
3886 	free(pool, M_CTL);
3887 }
3888 
3889 union ctl_io *
3890 ctl_alloc_io(void *pool_ref)
3891 {
3892 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3893 	union ctl_io *io;
3894 
3895 	io = uma_zalloc(pool->zone, M_WAITOK);
3896 	if (io != NULL) {
3897 		io->io_hdr.pool = pool_ref;
3898 		CTL_SOFTC(io) = pool->ctl_softc;
3899 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3900 	}
3901 	return (io);
3902 }
3903 
3904 union ctl_io *
3905 ctl_alloc_io_nowait(void *pool_ref)
3906 {
3907 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3908 	union ctl_io *io;
3909 
3910 	io = uma_zalloc(pool->zone, M_NOWAIT);
3911 	if (io != NULL) {
3912 		io->io_hdr.pool = pool_ref;
3913 		CTL_SOFTC(io) = pool->ctl_softc;
3914 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3915 	}
3916 	return (io);
3917 }
3918 
3919 void
3920 ctl_free_io(union ctl_io *io)
3921 {
3922 	struct ctl_io_pool *pool;
3923 
3924 	if (io == NULL)
3925 		return;
3926 
3927 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3928 	uma_zfree(pool->zone, io);
3929 }
3930 
3931 void
3932 ctl_zero_io(union ctl_io *io)
3933 {
3934 	struct ctl_io_pool *pool;
3935 
3936 	if (io == NULL)
3937 		return;
3938 
3939 	/*
3940 	 * May need to preserve linked list pointers at some point too.
3941 	 */
3942 	pool = io->io_hdr.pool;
3943 	memset(io, 0, sizeof(*io));
3944 	io->io_hdr.pool = pool;
3945 	CTL_SOFTC(io) = pool->ctl_softc;
3946 	TAILQ_INIT(&io->io_hdr.blocked_queue);
3947 }
3948 
3949 int
3950 ctl_expand_number(const char *buf, uint64_t *num)
3951 {
3952 	char *endptr;
3953 	uint64_t number;
3954 	unsigned shift;
3955 
3956 	number = strtoq(buf, &endptr, 0);
3957 
3958 	switch (tolower((unsigned char)*endptr)) {
3959 	case 'e':
3960 		shift = 60;
3961 		break;
3962 	case 'p':
3963 		shift = 50;
3964 		break;
3965 	case 't':
3966 		shift = 40;
3967 		break;
3968 	case 'g':
3969 		shift = 30;
3970 		break;
3971 	case 'm':
3972 		shift = 20;
3973 		break;
3974 	case 'k':
3975 		shift = 10;
3976 		break;
3977 	case 'b':
3978 	case '\0': /* No unit. */
3979 		*num = number;
3980 		return (0);
3981 	default:
3982 		/* Unrecognized unit. */
3983 		return (-1);
3984 	}
3985 
3986 	if ((number << shift) >> shift != number) {
3987 		/* Overflow */
3988 		return (-1);
3989 	}
3990 	*num = number << shift;
3991 	return (0);
3992 }
3993 
3994 /*
3995  * This routine could be used in the future to load default and/or saved
3996  * mode page parameters for a particuar lun.
3997  */
3998 static int
3999 ctl_init_page_index(struct ctl_lun *lun)
4000 {
4001 	int i, page_code;
4002 	struct ctl_page_index *page_index;
4003 	const char *value;
4004 	uint64_t ival;
4005 
4006 	memcpy(&lun->mode_pages.index, page_index_template,
4007 	       sizeof(page_index_template));
4008 
4009 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4010 		page_index = &lun->mode_pages.index[i];
4011 		if (lun->be_lun->lun_type == T_DIRECT &&
4012 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4013 			continue;
4014 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4015 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4016 			continue;
4017 		if (lun->be_lun->lun_type == T_CDROM &&
4018 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4019 			continue;
4020 
4021 		page_code = page_index->page_code & SMPH_PC_MASK;
4022 		switch (page_code) {
4023 		case SMS_RW_ERROR_RECOVERY_PAGE: {
4024 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4025 			    ("subpage %#x for page %#x is incorrect!",
4026 			    page_index->subpage, page_code));
4027 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4028 			       &rw_er_page_default,
4029 			       sizeof(rw_er_page_default));
4030 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4031 			       &rw_er_page_changeable,
4032 			       sizeof(rw_er_page_changeable));
4033 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4034 			       &rw_er_page_default,
4035 			       sizeof(rw_er_page_default));
4036 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4037 			       &rw_er_page_default,
4038 			       sizeof(rw_er_page_default));
4039 			page_index->page_data =
4040 				(uint8_t *)lun->mode_pages.rw_er_page;
4041 			break;
4042 		}
4043 		case SMS_FORMAT_DEVICE_PAGE: {
4044 			struct scsi_format_page *format_page;
4045 
4046 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4047 			    ("subpage %#x for page %#x is incorrect!",
4048 			    page_index->subpage, page_code));
4049 
4050 			/*
4051 			 * Sectors per track are set above.  Bytes per
4052 			 * sector need to be set here on a per-LUN basis.
4053 			 */
4054 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4055 			       &format_page_default,
4056 			       sizeof(format_page_default));
4057 			memcpy(&lun->mode_pages.format_page[
4058 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4059 			       sizeof(format_page_changeable));
4060 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4061 			       &format_page_default,
4062 			       sizeof(format_page_default));
4063 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4064 			       &format_page_default,
4065 			       sizeof(format_page_default));
4066 
4067 			format_page = &lun->mode_pages.format_page[
4068 				CTL_PAGE_CURRENT];
4069 			scsi_ulto2b(lun->be_lun->blocksize,
4070 				    format_page->bytes_per_sector);
4071 
4072 			format_page = &lun->mode_pages.format_page[
4073 				CTL_PAGE_DEFAULT];
4074 			scsi_ulto2b(lun->be_lun->blocksize,
4075 				    format_page->bytes_per_sector);
4076 
4077 			format_page = &lun->mode_pages.format_page[
4078 				CTL_PAGE_SAVED];
4079 			scsi_ulto2b(lun->be_lun->blocksize,
4080 				    format_page->bytes_per_sector);
4081 
4082 			page_index->page_data =
4083 				(uint8_t *)lun->mode_pages.format_page;
4084 			break;
4085 		}
4086 		case SMS_RIGID_DISK_PAGE: {
4087 			struct scsi_rigid_disk_page *rigid_disk_page;
4088 			uint32_t sectors_per_cylinder;
4089 			uint64_t cylinders;
4090 #ifndef	__XSCALE__
4091 			int shift;
4092 #endif /* !__XSCALE__ */
4093 
4094 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4095 			    ("subpage %#x for page %#x is incorrect!",
4096 			    page_index->subpage, page_code));
4097 
4098 			/*
4099 			 * Rotation rate and sectors per track are set
4100 			 * above.  We calculate the cylinders here based on
4101 			 * capacity.  Due to the number of heads and
4102 			 * sectors per track we're using, smaller arrays
4103 			 * may turn out to have 0 cylinders.  Linux and
4104 			 * FreeBSD don't pay attention to these mode pages
4105 			 * to figure out capacity, but Solaris does.  It
4106 			 * seems to deal with 0 cylinders just fine, and
4107 			 * works out a fake geometry based on the capacity.
4108 			 */
4109 			memcpy(&lun->mode_pages.rigid_disk_page[
4110 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4111 			       sizeof(rigid_disk_page_default));
4112 			memcpy(&lun->mode_pages.rigid_disk_page[
4113 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4114 			       sizeof(rigid_disk_page_changeable));
4115 
4116 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4117 				CTL_DEFAULT_HEADS;
4118 
4119 			/*
4120 			 * The divide method here will be more accurate,
4121 			 * probably, but results in floating point being
4122 			 * used in the kernel on i386 (__udivdi3()).  On the
4123 			 * XScale, though, __udivdi3() is implemented in
4124 			 * software.
4125 			 *
4126 			 * The shift method for cylinder calculation is
4127 			 * accurate if sectors_per_cylinder is a power of
4128 			 * 2.  Otherwise it might be slightly off -- you
4129 			 * might have a bit of a truncation problem.
4130 			 */
4131 #ifdef	__XSCALE__
4132 			cylinders = (lun->be_lun->maxlba + 1) /
4133 				sectors_per_cylinder;
4134 #else
4135 			for (shift = 31; shift > 0; shift--) {
4136 				if (sectors_per_cylinder & (1 << shift))
4137 					break;
4138 			}
4139 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4140 #endif
4141 
4142 			/*
4143 			 * We've basically got 3 bytes, or 24 bits for the
4144 			 * cylinder size in the mode page.  If we're over,
4145 			 * just round down to 2^24.
4146 			 */
4147 			if (cylinders > 0xffffff)
4148 				cylinders = 0xffffff;
4149 
4150 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4151 				CTL_PAGE_DEFAULT];
4152 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4153 
4154 			if ((value = dnvlist_get_string(lun->be_lun->options,
4155 			    "rpm", NULL)) != NULL) {
4156 				scsi_ulto2b(strtol(value, NULL, 0),
4157 				     rigid_disk_page->rotation_rate);
4158 			}
4159 
4160 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4161 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4162 			       sizeof(rigid_disk_page_default));
4163 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4164 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4165 			       sizeof(rigid_disk_page_default));
4166 
4167 			page_index->page_data =
4168 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4169 			break;
4170 		}
4171 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4172 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4173 			    ("subpage %#x for page %#x is incorrect!",
4174 			    page_index->subpage, page_code));
4175 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4176 			       &verify_er_page_default,
4177 			       sizeof(verify_er_page_default));
4178 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4179 			       &verify_er_page_changeable,
4180 			       sizeof(verify_er_page_changeable));
4181 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4182 			       &verify_er_page_default,
4183 			       sizeof(verify_er_page_default));
4184 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4185 			       &verify_er_page_default,
4186 			       sizeof(verify_er_page_default));
4187 			page_index->page_data =
4188 				(uint8_t *)lun->mode_pages.verify_er_page;
4189 			break;
4190 		}
4191 		case SMS_CACHING_PAGE: {
4192 			struct scsi_caching_page *caching_page;
4193 
4194 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4195 			    ("subpage %#x for page %#x is incorrect!",
4196 			    page_index->subpage, page_code));
4197 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4198 			       &caching_page_default,
4199 			       sizeof(caching_page_default));
4200 			memcpy(&lun->mode_pages.caching_page[
4201 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4202 			       sizeof(caching_page_changeable));
4203 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4204 			       &caching_page_default,
4205 			       sizeof(caching_page_default));
4206 			caching_page = &lun->mode_pages.caching_page[
4207 			    CTL_PAGE_SAVED];
4208 			value = dnvlist_get_string(lun->be_lun->options,
4209 			    "writecache", NULL);
4210 			if (value != NULL && strcmp(value, "off") == 0)
4211 				caching_page->flags1 &= ~SCP_WCE;
4212 			value = dnvlist_get_string(lun->be_lun->options,
4213 			    "readcache", NULL);
4214 			if (value != NULL && strcmp(value, "off") == 0)
4215 				caching_page->flags1 |= SCP_RCD;
4216 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4217 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4218 			       sizeof(caching_page_default));
4219 			page_index->page_data =
4220 				(uint8_t *)lun->mode_pages.caching_page;
4221 			break;
4222 		}
4223 		case SMS_CONTROL_MODE_PAGE: {
4224 			switch (page_index->subpage) {
4225 			case SMS_SUBPAGE_PAGE_0: {
4226 				struct scsi_control_page *control_page;
4227 
4228 				memcpy(&lun->mode_pages.control_page[
4229 				    CTL_PAGE_DEFAULT],
4230 				       &control_page_default,
4231 				       sizeof(control_page_default));
4232 				memcpy(&lun->mode_pages.control_page[
4233 				    CTL_PAGE_CHANGEABLE],
4234 				       &control_page_changeable,
4235 				       sizeof(control_page_changeable));
4236 				memcpy(&lun->mode_pages.control_page[
4237 				    CTL_PAGE_SAVED],
4238 				       &control_page_default,
4239 				       sizeof(control_page_default));
4240 				control_page = &lun->mode_pages.control_page[
4241 				    CTL_PAGE_SAVED];
4242 				value = dnvlist_get_string(lun->be_lun->options,
4243 				    "reordering", NULL);
4244 				if (value != NULL &&
4245 				    strcmp(value, "unrestricted") == 0) {
4246 					control_page->queue_flags &=
4247 					    ~SCP_QUEUE_ALG_MASK;
4248 					control_page->queue_flags |=
4249 					    SCP_QUEUE_ALG_UNRESTRICTED;
4250 				}
4251 				memcpy(&lun->mode_pages.control_page[
4252 				    CTL_PAGE_CURRENT],
4253 				       &lun->mode_pages.control_page[
4254 				    CTL_PAGE_SAVED],
4255 				       sizeof(control_page_default));
4256 				page_index->page_data =
4257 				    (uint8_t *)lun->mode_pages.control_page;
4258 				break;
4259 			}
4260 			case 0x01:
4261 				memcpy(&lun->mode_pages.control_ext_page[
4262 				    CTL_PAGE_DEFAULT],
4263 				       &control_ext_page_default,
4264 				       sizeof(control_ext_page_default));
4265 				memcpy(&lun->mode_pages.control_ext_page[
4266 				    CTL_PAGE_CHANGEABLE],
4267 				       &control_ext_page_changeable,
4268 				       sizeof(control_ext_page_changeable));
4269 				memcpy(&lun->mode_pages.control_ext_page[
4270 				    CTL_PAGE_SAVED],
4271 				       &control_ext_page_default,
4272 				       sizeof(control_ext_page_default));
4273 				memcpy(&lun->mode_pages.control_ext_page[
4274 				    CTL_PAGE_CURRENT],
4275 				       &lun->mode_pages.control_ext_page[
4276 				    CTL_PAGE_SAVED],
4277 				       sizeof(control_ext_page_default));
4278 				page_index->page_data =
4279 				    (uint8_t *)lun->mode_pages.control_ext_page;
4280 				break;
4281 			default:
4282 				panic("subpage %#x for page %#x is incorrect!",
4283 				      page_index->subpage, page_code);
4284 			}
4285 			break;
4286 		}
4287 		case SMS_INFO_EXCEPTIONS_PAGE: {
4288 			switch (page_index->subpage) {
4289 			case SMS_SUBPAGE_PAGE_0:
4290 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4291 				       &ie_page_default,
4292 				       sizeof(ie_page_default));
4293 				memcpy(&lun->mode_pages.ie_page[
4294 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4295 				       sizeof(ie_page_changeable));
4296 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4297 				       &ie_page_default,
4298 				       sizeof(ie_page_default));
4299 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4300 				       &ie_page_default,
4301 				       sizeof(ie_page_default));
4302 				page_index->page_data =
4303 					(uint8_t *)lun->mode_pages.ie_page;
4304 				break;
4305 			case 0x02: {
4306 				struct ctl_logical_block_provisioning_page *page;
4307 
4308 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4309 				       &lbp_page_default,
4310 				       sizeof(lbp_page_default));
4311 				memcpy(&lun->mode_pages.lbp_page[
4312 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4313 				       sizeof(lbp_page_changeable));
4314 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4315 				       &lbp_page_default,
4316 				       sizeof(lbp_page_default));
4317 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4318 				value = dnvlist_get_string(lun->be_lun->options,
4319 				    "avail-threshold", NULL);
4320 				if (value != NULL &&
4321 				    ctl_expand_number(value, &ival) == 0) {
4322 					page->descr[0].flags |= SLBPPD_ENABLED |
4323 					    SLBPPD_ARMING_DEC;
4324 					if (lun->be_lun->blocksize)
4325 						ival /= lun->be_lun->blocksize;
4326 					else
4327 						ival /= 512;
4328 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4329 					    page->descr[0].count);
4330 				}
4331 				value = dnvlist_get_string(lun->be_lun->options,
4332 				    "used-threshold", NULL);
4333 				if (value != NULL &&
4334 				    ctl_expand_number(value, &ival) == 0) {
4335 					page->descr[1].flags |= SLBPPD_ENABLED |
4336 					    SLBPPD_ARMING_INC;
4337 					if (lun->be_lun->blocksize)
4338 						ival /= lun->be_lun->blocksize;
4339 					else
4340 						ival /= 512;
4341 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4342 					    page->descr[1].count);
4343 				}
4344 				value = dnvlist_get_string(lun->be_lun->options,
4345 				    "pool-avail-threshold", NULL);
4346 				if (value != NULL &&
4347 				    ctl_expand_number(value, &ival) == 0) {
4348 					page->descr[2].flags |= SLBPPD_ENABLED |
4349 					    SLBPPD_ARMING_DEC;
4350 					if (lun->be_lun->blocksize)
4351 						ival /= lun->be_lun->blocksize;
4352 					else
4353 						ival /= 512;
4354 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4355 					    page->descr[2].count);
4356 				}
4357 				value = dnvlist_get_string(lun->be_lun->options,
4358 				    "pool-used-threshold", NULL);
4359 				if (value != NULL &&
4360 				    ctl_expand_number(value, &ival) == 0) {
4361 					page->descr[3].flags |= SLBPPD_ENABLED |
4362 					    SLBPPD_ARMING_INC;
4363 					if (lun->be_lun->blocksize)
4364 						ival /= lun->be_lun->blocksize;
4365 					else
4366 						ival /= 512;
4367 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4368 					    page->descr[3].count);
4369 				}
4370 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4371 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4372 				       sizeof(lbp_page_default));
4373 				page_index->page_data =
4374 					(uint8_t *)lun->mode_pages.lbp_page;
4375 				break;
4376 			}
4377 			default:
4378 				panic("subpage %#x for page %#x is incorrect!",
4379 				      page_index->subpage, page_code);
4380 			}
4381 			break;
4382 		}
4383 		case SMS_CDDVD_CAPS_PAGE:{
4384 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4385 			    ("subpage %#x for page %#x is incorrect!",
4386 			    page_index->subpage, page_code));
4387 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4388 			       &cddvd_page_default,
4389 			       sizeof(cddvd_page_default));
4390 			memcpy(&lun->mode_pages.cddvd_page[
4391 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4392 			       sizeof(cddvd_page_changeable));
4393 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4394 			       &cddvd_page_default,
4395 			       sizeof(cddvd_page_default));
4396 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4397 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4398 			       sizeof(cddvd_page_default));
4399 			page_index->page_data =
4400 				(uint8_t *)lun->mode_pages.cddvd_page;
4401 			break;
4402 		}
4403 		default:
4404 			panic("invalid page code value %#x", page_code);
4405 		}
4406 	}
4407 
4408 	return (CTL_RETVAL_COMPLETE);
4409 }
4410 
4411 static int
4412 ctl_init_log_page_index(struct ctl_lun *lun)
4413 {
4414 	struct ctl_page_index *page_index;
4415 	int i, j, k, prev;
4416 
4417 	memcpy(&lun->log_pages.index, log_page_index_template,
4418 	       sizeof(log_page_index_template));
4419 
4420 	prev = -1;
4421 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4422 		page_index = &lun->log_pages.index[i];
4423 		if (lun->be_lun->lun_type == T_DIRECT &&
4424 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4425 			continue;
4426 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4427 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4428 			continue;
4429 		if (lun->be_lun->lun_type == T_CDROM &&
4430 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4431 			continue;
4432 
4433 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4434 		    lun->backend->lun_attr == NULL)
4435 			continue;
4436 
4437 		if (page_index->page_code != prev) {
4438 			lun->log_pages.pages_page[j] = page_index->page_code;
4439 			prev = page_index->page_code;
4440 			j++;
4441 		}
4442 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4443 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4444 		k++;
4445 	}
4446 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4447 	lun->log_pages.index[0].page_len = j;
4448 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4449 	lun->log_pages.index[1].page_len = k * 2;
4450 	lun->log_pages.index[2].page_data = (uint8_t *)&lun->log_pages.temp_page;
4451 	lun->log_pages.index[2].page_len = sizeof(lun->log_pages.temp_page);
4452 	lun->log_pages.index[3].page_data = &lun->log_pages.lbp_page[0];
4453 	lun->log_pages.index[3].page_len = 12*CTL_NUM_LBP_PARAMS;
4454 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.stat_page;
4455 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.stat_page);
4456 	lun->log_pages.index[5].page_data = (uint8_t *)&lun->log_pages.ie_page;
4457 	lun->log_pages.index[5].page_len = sizeof(lun->log_pages.ie_page);
4458 
4459 	return (CTL_RETVAL_COMPLETE);
4460 }
4461 
4462 static int
4463 hex2bin(const char *str, uint8_t *buf, int buf_size)
4464 {
4465 	int i;
4466 	u_char c;
4467 
4468 	memset(buf, 0, buf_size);
4469 	while (isspace(str[0]))
4470 		str++;
4471 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4472 		str += 2;
4473 	buf_size *= 2;
4474 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4475 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4476 			str++;
4477 		c = str[i];
4478 		if (isdigit(c))
4479 			c -= '0';
4480 		else if (isalpha(c))
4481 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4482 		else
4483 			break;
4484 		if (c >= 16)
4485 			break;
4486 		if ((i & 1) == 0)
4487 			buf[i / 2] |= (c << 4);
4488 		else
4489 			buf[i / 2] |= c;
4490 	}
4491 	return ((i + 1) / 2);
4492 }
4493 
4494 /*
4495  * Add LUN.
4496  *
4497  * Returns 0 for success, non-zero (errno) for failure.
4498  */
4499 int
4500 ctl_add_lun(struct ctl_be_lun *be_lun)
4501 {
4502 	struct ctl_softc *ctl_softc = control_softc;
4503 	struct ctl_lun *nlun, *lun;
4504 	struct scsi_vpd_id_descriptor *desc;
4505 	struct scsi_vpd_id_t10 *t10id;
4506 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4507 	int lun_number;
4508 	int devidlen, idlen1, idlen2 = 0, len;
4509 
4510 	/*
4511 	 * We support only Direct Access, CD-ROM or Processor LUN types.
4512 	 */
4513 	switch (be_lun->lun_type) {
4514 	case T_DIRECT:
4515 	case T_PROCESSOR:
4516 	case T_CDROM:
4517 		break;
4518 	case T_SEQUENTIAL:
4519 	case T_CHANGER:
4520 	default:
4521 		return (EINVAL);
4522 	}
4523 	lun = malloc(sizeof(*lun), M_CTL, M_WAITOK | M_ZERO);
4524 
4525 	lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4526 	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4527 	lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4528 	    M_DEVBUF, M_WAITOK | M_ZERO);
4529 	lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4530 	    M_DEVBUF, M_WAITOK | M_ZERO);
4531 
4532 	/* Generate LUN ID. */
4533 	devidlen = max(CTL_DEVID_MIN_LEN,
4534 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4535 	idlen1 = sizeof(*t10id) + devidlen;
4536 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4537 	scsiname = dnvlist_get_string(be_lun->options, "scsiname", NULL);
4538 	if (scsiname != NULL) {
4539 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4540 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4541 	}
4542 	eui = dnvlist_get_string(be_lun->options, "eui", NULL);
4543 	if (eui != NULL) {
4544 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4545 	}
4546 	naa = dnvlist_get_string(be_lun->options, "naa", NULL);
4547 	if (naa != NULL) {
4548 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4549 	}
4550 	uuid = dnvlist_get_string(be_lun->options, "uuid", NULL);
4551 	if (uuid != NULL) {
4552 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4553 	}
4554 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4555 	    M_CTL, M_WAITOK | M_ZERO);
4556 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4557 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4558 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4559 	desc->length = idlen1;
4560 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4561 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4562 	if ((vendor = dnvlist_get_string(be_lun->options, "vendor", NULL)) == NULL) {
4563 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4564 	} else {
4565 		strncpy(t10id->vendor, vendor,
4566 		    min(sizeof(t10id->vendor), strlen(vendor)));
4567 	}
4568 	strncpy((char *)t10id->vendor_spec_id,
4569 	    (char *)be_lun->device_id, devidlen);
4570 	if (scsiname != NULL) {
4571 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4572 		    desc->length);
4573 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4574 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4575 		    SVPD_ID_TYPE_SCSI_NAME;
4576 		desc->length = idlen2;
4577 		strlcpy(desc->identifier, scsiname, idlen2);
4578 	}
4579 	if (eui != NULL) {
4580 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4581 		    desc->length);
4582 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4583 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4584 		    SVPD_ID_TYPE_EUI64;
4585 		desc->length = hex2bin(eui, desc->identifier, 16);
4586 		desc->length = desc->length > 12 ? 16 :
4587 		    (desc->length > 8 ? 12 : 8);
4588 		len -= 16 - desc->length;
4589 	}
4590 	if (naa != NULL) {
4591 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4592 		    desc->length);
4593 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4594 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4595 		    SVPD_ID_TYPE_NAA;
4596 		desc->length = hex2bin(naa, desc->identifier, 16);
4597 		desc->length = desc->length > 8 ? 16 : 8;
4598 		len -= 16 - desc->length;
4599 	}
4600 	if (uuid != NULL) {
4601 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4602 		    desc->length);
4603 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4604 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4605 		    SVPD_ID_TYPE_UUID;
4606 		desc->identifier[0] = 0x10;
4607 		hex2bin(uuid, &desc->identifier[2], 16);
4608 		desc->length = 18;
4609 	}
4610 	lun->lun_devid->len = len;
4611 
4612 	mtx_lock(&ctl_softc->ctl_lock);
4613 	/*
4614 	 * See if the caller requested a particular LUN number.  If so, see
4615 	 * if it is available.  Otherwise, allocate the first available LUN.
4616 	 */
4617 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4618 		if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4619 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4620 			mtx_unlock(&ctl_softc->ctl_lock);
4621 			if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4622 				printf("ctl: requested LUN ID %d is higher "
4623 				       "than ctl_max_luns - 1 (%d)\n",
4624 				       be_lun->req_lun_id, ctl_max_luns - 1);
4625 			} else {
4626 				/*
4627 				 * XXX KDM return an error, or just assign
4628 				 * another LUN ID in this case??
4629 				 */
4630 				printf("ctl: requested LUN ID %d is already "
4631 				       "in use\n", be_lun->req_lun_id);
4632 			}
4633 fail:
4634 			free(lun->lun_devid, M_CTL);
4635 			free(lun, M_CTL);
4636 			return (ENOSPC);
4637 		}
4638 		lun_number = be_lun->req_lun_id;
4639 	} else {
4640 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4641 		if (lun_number == -1) {
4642 			mtx_unlock(&ctl_softc->ctl_lock);
4643 			printf("ctl: can't allocate LUN, out of LUNs\n");
4644 			goto fail;
4645 		}
4646 	}
4647 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4648 	mtx_unlock(&ctl_softc->ctl_lock);
4649 
4650 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4651 	lun->lun = lun_number;
4652 	lun->be_lun = be_lun;
4653 	/*
4654 	 * The processor LUN is always enabled.  Disk LUNs come on line
4655 	 * disabled, and must be enabled by the backend.
4656 	 */
4657 	lun->flags |= CTL_LUN_DISABLED;
4658 	lun->backend = be_lun->be;
4659 	be_lun->ctl_lun = lun;
4660 	be_lun->lun_id = lun_number;
4661 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4662 		lun->flags |= CTL_LUN_EJECTED;
4663 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4664 		lun->flags |= CTL_LUN_NO_MEDIA;
4665 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4666 		lun->flags |= CTL_LUN_STOPPED;
4667 
4668 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4669 		lun->flags |= CTL_LUN_PRIMARY_SC;
4670 
4671 	value = dnvlist_get_string(be_lun->options, "removable", NULL);
4672 	if (value != NULL) {
4673 		if (strcmp(value, "on") == 0)
4674 			lun->flags |= CTL_LUN_REMOVABLE;
4675 	} else if (be_lun->lun_type == T_CDROM)
4676 		lun->flags |= CTL_LUN_REMOVABLE;
4677 
4678 	lun->ctl_softc = ctl_softc;
4679 #ifdef CTL_TIME_IO
4680 	lun->last_busy = getsbinuptime();
4681 #endif
4682 	LIST_INIT(&lun->ooa_queue);
4683 	STAILQ_INIT(&lun->error_list);
4684 	lun->ie_reported = 1;
4685 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4686 	ctl_tpc_lun_init(lun);
4687 	if (lun->flags & CTL_LUN_REMOVABLE) {
4688 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4689 		    M_CTL, M_WAITOK);
4690 	}
4691 
4692 	/*
4693 	 * Initialize the mode and log page index.
4694 	 */
4695 	ctl_init_page_index(lun);
4696 	ctl_init_log_page_index(lun);
4697 
4698 	/* Setup statistics gathering */
4699 	lun->stats.item = lun_number;
4700 
4701 	/*
4702 	 * Now, before we insert this lun on the lun list, set the lun
4703 	 * inventory changed UA for all other luns.
4704 	 */
4705 	mtx_lock(&ctl_softc->ctl_lock);
4706 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4707 		mtx_lock(&nlun->lun_lock);
4708 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4709 		mtx_unlock(&nlun->lun_lock);
4710 	}
4711 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4712 	ctl_softc->ctl_luns[lun_number] = lun;
4713 	ctl_softc->num_luns++;
4714 	mtx_unlock(&ctl_softc->ctl_lock);
4715 
4716 	/*
4717 	 * We successfully added the LUN, attempt to enable it.
4718 	 */
4719 	if (ctl_enable_lun(lun) != 0) {
4720 		printf("%s: ctl_enable_lun() failed!\n", __func__);
4721 		mtx_lock(&ctl_softc->ctl_lock);
4722 		STAILQ_REMOVE(&ctl_softc->lun_list, lun, ctl_lun, links);
4723 		ctl_clear_mask(ctl_softc->ctl_lun_mask, lun_number);
4724 		ctl_softc->ctl_luns[lun_number] = NULL;
4725 		ctl_softc->num_luns--;
4726 		mtx_unlock(&ctl_softc->ctl_lock);
4727 		free(lun->lun_devid, M_CTL);
4728 		free(lun, M_CTL);
4729 		return (EIO);
4730 	}
4731 
4732 	return (0);
4733 }
4734 
4735 /*
4736  * Free LUN that has no active requests.
4737  */
4738 static int
4739 ctl_free_lun(struct ctl_lun *lun)
4740 {
4741 	struct ctl_softc *softc = lun->ctl_softc;
4742 	struct ctl_lun *nlun;
4743 	int i;
4744 
4745 	KASSERT(LIST_EMPTY(&lun->ooa_queue),
4746 	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4747 
4748 	mtx_lock(&softc->ctl_lock);
4749 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4750 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4751 	softc->ctl_luns[lun->lun] = NULL;
4752 	softc->num_luns--;
4753 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4754 		mtx_lock(&nlun->lun_lock);
4755 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4756 		mtx_unlock(&nlun->lun_lock);
4757 	}
4758 	mtx_unlock(&softc->ctl_lock);
4759 
4760 	/*
4761 	 * Tell the backend to free resources, if this LUN has a backend.
4762 	 */
4763 	lun->be_lun->lun_shutdown(lun->be_lun);
4764 
4765 	lun->ie_reportcnt = UINT32_MAX;
4766 	callout_drain(&lun->ie_callout);
4767 	ctl_tpc_lun_shutdown(lun);
4768 	mtx_destroy(&lun->lun_lock);
4769 	free(lun->lun_devid, M_CTL);
4770 	for (i = 0; i < ctl_max_ports; i++)
4771 		free(lun->pending_ua[i], M_CTL);
4772 	free(lun->pending_ua, M_DEVBUF);
4773 	for (i = 0; i < ctl_max_ports; i++)
4774 		free(lun->pr_keys[i], M_CTL);
4775 	free(lun->pr_keys, M_DEVBUF);
4776 	free(lun->write_buffer, M_CTL);
4777 	free(lun->prevent, M_CTL);
4778 	free(lun, M_CTL);
4779 
4780 	return (0);
4781 }
4782 
4783 static int
4784 ctl_enable_lun(struct ctl_lun *lun)
4785 {
4786 	struct ctl_softc *softc;
4787 	struct ctl_port *port, *nport;
4788 	int retval;
4789 
4790 	softc = lun->ctl_softc;
4791 
4792 	mtx_lock(&softc->ctl_lock);
4793 	mtx_lock(&lun->lun_lock);
4794 	KASSERT((lun->flags & CTL_LUN_DISABLED) != 0,
4795 	    ("%s: LUN not disabled", __func__));
4796 	lun->flags &= ~CTL_LUN_DISABLED;
4797 	mtx_unlock(&lun->lun_lock);
4798 
4799 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4800 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4801 		    port->lun_map != NULL || port->lun_enable == NULL)
4802 			continue;
4803 
4804 		/*
4805 		 * Drop the lock while we call the FETD's enable routine.
4806 		 * This can lead to a callback into CTL (at least in the
4807 		 * case of the internal initiator frontend.
4808 		 */
4809 		mtx_unlock(&softc->ctl_lock);
4810 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4811 		mtx_lock(&softc->ctl_lock);
4812 		if (retval != 0) {
4813 			printf("%s: FETD %s port %d returned error "
4814 			       "%d for lun_enable on lun %jd\n",
4815 			       __func__, port->port_name, port->targ_port,
4816 			       retval, (intmax_t)lun->lun);
4817 		}
4818 	}
4819 
4820 	mtx_unlock(&softc->ctl_lock);
4821 	ctl_isc_announce_lun(lun);
4822 
4823 	return (0);
4824 }
4825 
4826 static int
4827 ctl_disable_lun(struct ctl_lun *lun)
4828 {
4829 	struct ctl_softc *softc;
4830 	struct ctl_port *port;
4831 	int retval;
4832 
4833 	softc = lun->ctl_softc;
4834 
4835 	mtx_lock(&softc->ctl_lock);
4836 	mtx_lock(&lun->lun_lock);
4837 	KASSERT((lun->flags & CTL_LUN_DISABLED) == 0,
4838 	    ("%s: LUN not enabled", __func__));
4839 	lun->flags |= CTL_LUN_DISABLED;
4840 	mtx_unlock(&lun->lun_lock);
4841 
4842 	STAILQ_FOREACH(port, &softc->port_list, links) {
4843 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4844 		    port->lun_map != NULL || port->lun_disable == NULL)
4845 			continue;
4846 
4847 		/*
4848 		 * Drop the lock before we call the frontend's disable
4849 		 * routine, to avoid lock order reversals.
4850 		 *
4851 		 * XXX KDM what happens if the frontend list changes while
4852 		 * we're traversing it?  It's unlikely, but should be handled.
4853 		 */
4854 		mtx_unlock(&softc->ctl_lock);
4855 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4856 		mtx_lock(&softc->ctl_lock);
4857 		if (retval != 0) {
4858 			printf("%s: FETD %s port %d returned error "
4859 			       "%d for lun_disable on lun %jd\n",
4860 			       __func__, port->port_name, port->targ_port,
4861 			       retval, (intmax_t)lun->lun);
4862 		}
4863 	}
4864 
4865 	mtx_unlock(&softc->ctl_lock);
4866 	ctl_isc_announce_lun(lun);
4867 
4868 	return (0);
4869 }
4870 
4871 int
4872 ctl_start_lun(struct ctl_be_lun *be_lun)
4873 {
4874 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4875 
4876 	mtx_lock(&lun->lun_lock);
4877 	lun->flags &= ~CTL_LUN_STOPPED;
4878 	mtx_unlock(&lun->lun_lock);
4879 	return (0);
4880 }
4881 
4882 int
4883 ctl_stop_lun(struct ctl_be_lun *be_lun)
4884 {
4885 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4886 
4887 	mtx_lock(&lun->lun_lock);
4888 	lun->flags |= CTL_LUN_STOPPED;
4889 	mtx_unlock(&lun->lun_lock);
4890 	return (0);
4891 }
4892 
4893 int
4894 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4895 {
4896 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4897 
4898 	mtx_lock(&lun->lun_lock);
4899 	lun->flags |= CTL_LUN_NO_MEDIA;
4900 	mtx_unlock(&lun->lun_lock);
4901 	return (0);
4902 }
4903 
4904 int
4905 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4906 {
4907 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4908 	union ctl_ha_msg msg;
4909 
4910 	mtx_lock(&lun->lun_lock);
4911 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4912 	if (lun->flags & CTL_LUN_REMOVABLE)
4913 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4914 	mtx_unlock(&lun->lun_lock);
4915 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4916 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4917 		bzero(&msg.ua, sizeof(msg.ua));
4918 		msg.hdr.msg_type = CTL_MSG_UA;
4919 		msg.hdr.nexus.initid = -1;
4920 		msg.hdr.nexus.targ_port = -1;
4921 		msg.hdr.nexus.targ_lun = lun->lun;
4922 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4923 		msg.ua.ua_all = 1;
4924 		msg.ua.ua_set = 1;
4925 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4926 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4927 		    M_WAITOK);
4928 	}
4929 	return (0);
4930 }
4931 
4932 int
4933 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4934 {
4935 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4936 
4937 	mtx_lock(&lun->lun_lock);
4938 	lun->flags |= CTL_LUN_EJECTED;
4939 	mtx_unlock(&lun->lun_lock);
4940 	return (0);
4941 }
4942 
4943 int
4944 ctl_lun_primary(struct ctl_be_lun *be_lun)
4945 {
4946 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4947 
4948 	mtx_lock(&lun->lun_lock);
4949 	lun->flags |= CTL_LUN_PRIMARY_SC;
4950 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4951 	mtx_unlock(&lun->lun_lock);
4952 	ctl_isc_announce_lun(lun);
4953 	return (0);
4954 }
4955 
4956 int
4957 ctl_lun_secondary(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_PRIMARY_SC;
4963 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4964 	mtx_unlock(&lun->lun_lock);
4965 	ctl_isc_announce_lun(lun);
4966 	return (0);
4967 }
4968 
4969 /*
4970  * Remove LUN.  If there are active requests, wait for completion.
4971  *
4972  * Returns 0 for success, non-zero (errno) for failure.
4973  * Completion is reported to backed via the lun_shutdown() method.
4974  */
4975 int
4976 ctl_remove_lun(struct ctl_be_lun *be_lun)
4977 {
4978 	struct ctl_lun *lun;
4979 
4980 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4981 
4982 	ctl_disable_lun(lun);
4983 
4984 	mtx_lock(&lun->lun_lock);
4985 	lun->flags |= CTL_LUN_INVALID;
4986 
4987 	/*
4988 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4989 	 * If we have something in the OOA queue, we'll free it when the
4990 	 * last I/O completes.
4991 	 */
4992 	if (LIST_EMPTY(&lun->ooa_queue)) {
4993 		mtx_unlock(&lun->lun_lock);
4994 		ctl_free_lun(lun);
4995 	} else
4996 		mtx_unlock(&lun->lun_lock);
4997 
4998 	return (0);
4999 }
5000 
5001 void
5002 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5003 {
5004 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5005 	union ctl_ha_msg msg;
5006 
5007 	mtx_lock(&lun->lun_lock);
5008 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5009 	mtx_unlock(&lun->lun_lock);
5010 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5011 		/* Send msg to other side. */
5012 		bzero(&msg.ua, sizeof(msg.ua));
5013 		msg.hdr.msg_type = CTL_MSG_UA;
5014 		msg.hdr.nexus.initid = -1;
5015 		msg.hdr.nexus.targ_port = -1;
5016 		msg.hdr.nexus.targ_lun = lun->lun;
5017 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5018 		msg.ua.ua_all = 1;
5019 		msg.ua.ua_set = 1;
5020 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5021 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5022 		    M_WAITOK);
5023 	}
5024 }
5025 
5026 /*
5027  * Backend "memory move is complete" callback for requests that never
5028  * make it down to say RAIDCore's configuration code.
5029  */
5030 int
5031 ctl_config_move_done(union ctl_io *io)
5032 {
5033 	int retval;
5034 
5035 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5036 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5037 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
5038 
5039 	if ((io->io_hdr.port_status != 0) &&
5040 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5041 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5042 		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
5043 		    /*retry_count*/ io->io_hdr.port_status);
5044 	} else if (io->scsiio.kern_data_resid != 0 &&
5045 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
5046 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5047 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5048 		ctl_set_invalid_field_ciu(&io->scsiio);
5049 	}
5050 
5051 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5052 		ctl_data_print(io);
5053 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5054 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5055 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5056 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5057 		/*
5058 		 * XXX KDM just assuming a single pointer here, and not a
5059 		 * S/G list.  If we start using S/G lists for config data,
5060 		 * we'll need to know how to clean them up here as well.
5061 		 */
5062 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5063 			free(io->scsiio.kern_data_ptr, M_CTL);
5064 		ctl_done(io);
5065 		retval = CTL_RETVAL_COMPLETE;
5066 	} else {
5067 		/*
5068 		 * XXX KDM now we need to continue data movement.  Some
5069 		 * options:
5070 		 * - call ctl_scsiio() again?  We don't do this for data
5071 		 *   writes, because for those at least we know ahead of
5072 		 *   time where the write will go and how long it is.  For
5073 		 *   config writes, though, that information is largely
5074 		 *   contained within the write itself, thus we need to
5075 		 *   parse out the data again.
5076 		 *
5077 		 * - Call some other function once the data is in?
5078 		 */
5079 
5080 		/*
5081 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5082 		 * bits to see whether we're allocated or not.
5083 		 */
5084 		retval = ctl_scsiio(&io->scsiio);
5085 	}
5086 	return (retval);
5087 }
5088 
5089 /*
5090  * This gets called by a backend driver when it is done with a
5091  * data_submit method.
5092  */
5093 void
5094 ctl_data_submit_done(union ctl_io *io)
5095 {
5096 	/*
5097 	 * If the IO_CONT flag is set, we need to call the supplied
5098 	 * function to continue processing the I/O, instead of completing
5099 	 * the I/O just yet.
5100 	 *
5101 	 * If there is an error, though, we don't want to keep processing.
5102 	 * Instead, just send status back to the initiator.
5103 	 */
5104 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5105 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5106 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5107 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5108 		io->scsiio.io_cont(io);
5109 		return;
5110 	}
5111 	ctl_done(io);
5112 }
5113 
5114 /*
5115  * This gets called by a backend driver when it is done with a
5116  * configuration write.
5117  */
5118 void
5119 ctl_config_write_done(union ctl_io *io)
5120 {
5121 	uint8_t *buf;
5122 
5123 	/*
5124 	 * If the IO_CONT flag is set, we need to call the supplied
5125 	 * function to continue processing the I/O, instead of completing
5126 	 * the I/O just yet.
5127 	 *
5128 	 * If there is an error, though, we don't want to keep processing.
5129 	 * Instead, just send status back to the initiator.
5130 	 */
5131 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5132 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5133 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5134 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5135 		io->scsiio.io_cont(io);
5136 		return;
5137 	}
5138 	/*
5139 	 * Since a configuration write can be done for commands that actually
5140 	 * have data allocated, like write buffer, and commands that have
5141 	 * no data, like start/stop unit, we need to check here.
5142 	 */
5143 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5144 		buf = io->scsiio.kern_data_ptr;
5145 	else
5146 		buf = NULL;
5147 	ctl_done(io);
5148 	if (buf)
5149 		free(buf, M_CTL);
5150 }
5151 
5152 void
5153 ctl_config_read_done(union ctl_io *io)
5154 {
5155 	uint8_t *buf;
5156 
5157 	/*
5158 	 * If there is some error -- we are done, skip data transfer.
5159 	 */
5160 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5161 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5162 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5163 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5164 			buf = io->scsiio.kern_data_ptr;
5165 		else
5166 			buf = NULL;
5167 		ctl_done(io);
5168 		if (buf)
5169 			free(buf, M_CTL);
5170 		return;
5171 	}
5172 
5173 	/*
5174 	 * If the IO_CONT flag is set, we need to call the supplied
5175 	 * function to continue processing the I/O, instead of completing
5176 	 * the I/O just yet.
5177 	 */
5178 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5179 		io->scsiio.io_cont(io);
5180 		return;
5181 	}
5182 
5183 	ctl_datamove(io);
5184 }
5185 
5186 /*
5187  * SCSI release command.
5188  */
5189 int
5190 ctl_scsi_release(struct ctl_scsiio *ctsio)
5191 {
5192 	struct ctl_lun *lun = CTL_LUN(ctsio);
5193 	uint32_t residx;
5194 
5195 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5196 
5197 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5198 
5199 	/*
5200 	 * XXX KDM right now, we only support LUN reservation.  We don't
5201 	 * support 3rd party reservations, or extent reservations, which
5202 	 * might actually need the parameter list.  If we've gotten this
5203 	 * far, we've got a LUN reservation.  Anything else got kicked out
5204 	 * above.  So, according to SPC, ignore the length.
5205 	 */
5206 
5207 	mtx_lock(&lun->lun_lock);
5208 
5209 	/*
5210 	 * According to SPC, it is not an error for an intiator to attempt
5211 	 * to release a reservation on a LUN that isn't reserved, or that
5212 	 * is reserved by another initiator.  The reservation can only be
5213 	 * released, though, by the initiator who made it or by one of
5214 	 * several reset type events.
5215 	 */
5216 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5217 			lun->flags &= ~CTL_LUN_RESERVED;
5218 
5219 	mtx_unlock(&lun->lun_lock);
5220 
5221 	ctl_set_success(ctsio);
5222 	ctl_done((union ctl_io *)ctsio);
5223 	return (CTL_RETVAL_COMPLETE);
5224 }
5225 
5226 int
5227 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5228 {
5229 	struct ctl_lun *lun = CTL_LUN(ctsio);
5230 	uint32_t residx;
5231 
5232 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5233 
5234 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5235 
5236 	/*
5237 	 * XXX KDM right now, we only support LUN reservation.  We don't
5238 	 * support 3rd party reservations, or extent reservations, which
5239 	 * might actually need the parameter list.  If we've gotten this
5240 	 * far, we've got a LUN reservation.  Anything else got kicked out
5241 	 * above.  So, according to SPC, ignore the length.
5242 	 */
5243 
5244 	mtx_lock(&lun->lun_lock);
5245 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5246 		ctl_set_reservation_conflict(ctsio);
5247 		goto bailout;
5248 	}
5249 
5250 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5251 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5252 		ctl_set_success(ctsio);
5253 		goto bailout;
5254 	}
5255 
5256 	lun->flags |= CTL_LUN_RESERVED;
5257 	lun->res_idx = residx;
5258 	ctl_set_success(ctsio);
5259 
5260 bailout:
5261 	mtx_unlock(&lun->lun_lock);
5262 	ctl_done((union ctl_io *)ctsio);
5263 	return (CTL_RETVAL_COMPLETE);
5264 }
5265 
5266 int
5267 ctl_start_stop(struct ctl_scsiio *ctsio)
5268 {
5269 	struct ctl_lun *lun = CTL_LUN(ctsio);
5270 	struct scsi_start_stop_unit *cdb;
5271 	int retval;
5272 
5273 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5274 
5275 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5276 
5277 	if ((cdb->how & SSS_PC_MASK) == 0) {
5278 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5279 		    (cdb->how & SSS_START) == 0) {
5280 			uint32_t residx;
5281 
5282 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5283 			if (ctl_get_prkey(lun, residx) == 0 ||
5284 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5285 				ctl_set_reservation_conflict(ctsio);
5286 				ctl_done((union ctl_io *)ctsio);
5287 				return (CTL_RETVAL_COMPLETE);
5288 			}
5289 		}
5290 
5291 		if ((cdb->how & SSS_LOEJ) &&
5292 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5293 			ctl_set_invalid_field(ctsio,
5294 					      /*sks_valid*/ 1,
5295 					      /*command*/ 1,
5296 					      /*field*/ 4,
5297 					      /*bit_valid*/ 1,
5298 					      /*bit*/ 1);
5299 			ctl_done((union ctl_io *)ctsio);
5300 			return (CTL_RETVAL_COMPLETE);
5301 		}
5302 
5303 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5304 		    lun->prevent_count > 0) {
5305 			/* "Medium removal prevented" */
5306 			ctl_set_sense(ctsio, /*current_error*/ 1,
5307 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5308 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5309 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5310 			ctl_done((union ctl_io *)ctsio);
5311 			return (CTL_RETVAL_COMPLETE);
5312 		}
5313 	}
5314 
5315 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5316 	return (retval);
5317 }
5318 
5319 int
5320 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5321 {
5322 	struct ctl_lun *lun = CTL_LUN(ctsio);
5323 	struct scsi_prevent *cdb;
5324 	int retval;
5325 	uint32_t initidx;
5326 
5327 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5328 
5329 	cdb = (struct scsi_prevent *)ctsio->cdb;
5330 
5331 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5332 		ctl_set_invalid_opcode(ctsio);
5333 		ctl_done((union ctl_io *)ctsio);
5334 		return (CTL_RETVAL_COMPLETE);
5335 	}
5336 
5337 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5338 	mtx_lock(&lun->lun_lock);
5339 	if ((cdb->how & PR_PREVENT) &&
5340 	    ctl_is_set(lun->prevent, initidx) == 0) {
5341 		ctl_set_mask(lun->prevent, initidx);
5342 		lun->prevent_count++;
5343 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5344 	    ctl_is_set(lun->prevent, initidx)) {
5345 		ctl_clear_mask(lun->prevent, initidx);
5346 		lun->prevent_count--;
5347 	}
5348 	mtx_unlock(&lun->lun_lock);
5349 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5350 	return (retval);
5351 }
5352 
5353 /*
5354  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5355  * we don't really do anything with the LBA and length fields if the user
5356  * passes them in.  Instead we'll just flush out the cache for the entire
5357  * LUN.
5358  */
5359 int
5360 ctl_sync_cache(struct ctl_scsiio *ctsio)
5361 {
5362 	struct ctl_lun *lun = CTL_LUN(ctsio);
5363 	struct ctl_lba_len_flags *lbalen;
5364 	uint64_t starting_lba;
5365 	uint32_t block_count;
5366 	int retval;
5367 	uint8_t byte2;
5368 
5369 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5370 
5371 	retval = 0;
5372 
5373 	switch (ctsio->cdb[0]) {
5374 	case SYNCHRONIZE_CACHE: {
5375 		struct scsi_sync_cache *cdb;
5376 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5377 
5378 		starting_lba = scsi_4btoul(cdb->begin_lba);
5379 		block_count = scsi_2btoul(cdb->lb_count);
5380 		byte2 = cdb->byte2;
5381 		break;
5382 	}
5383 	case SYNCHRONIZE_CACHE_16: {
5384 		struct scsi_sync_cache_16 *cdb;
5385 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5386 
5387 		starting_lba = scsi_8btou64(cdb->begin_lba);
5388 		block_count = scsi_4btoul(cdb->lb_count);
5389 		byte2 = cdb->byte2;
5390 		break;
5391 	}
5392 	default:
5393 		ctl_set_invalid_opcode(ctsio);
5394 		ctl_done((union ctl_io *)ctsio);
5395 		goto bailout;
5396 		break; /* NOTREACHED */
5397 	}
5398 
5399 	/*
5400 	 * We check the LBA and length, but don't do anything with them.
5401 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5402 	 * get flushed.  This check will just help satisfy anyone who wants
5403 	 * to see an error for an out of range LBA.
5404 	 */
5405 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5406 		ctl_set_lba_out_of_range(ctsio,
5407 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5408 		ctl_done((union ctl_io *)ctsio);
5409 		goto bailout;
5410 	}
5411 
5412 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5413 	lbalen->lba = starting_lba;
5414 	lbalen->len = block_count;
5415 	lbalen->flags = byte2;
5416 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5417 
5418 bailout:
5419 	return (retval);
5420 }
5421 
5422 int
5423 ctl_format(struct ctl_scsiio *ctsio)
5424 {
5425 	struct scsi_format *cdb;
5426 	int length, defect_list_len;
5427 
5428 	CTL_DEBUG_PRINT(("ctl_format\n"));
5429 
5430 	cdb = (struct scsi_format *)ctsio->cdb;
5431 
5432 	length = 0;
5433 	if (cdb->byte2 & SF_FMTDATA) {
5434 		if (cdb->byte2 & SF_LONGLIST)
5435 			length = sizeof(struct scsi_format_header_long);
5436 		else
5437 			length = sizeof(struct scsi_format_header_short);
5438 	}
5439 
5440 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5441 	 && (length > 0)) {
5442 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5443 		ctsio->kern_data_len = length;
5444 		ctsio->kern_total_len = length;
5445 		ctsio->kern_rel_offset = 0;
5446 		ctsio->kern_sg_entries = 0;
5447 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5448 		ctsio->be_move_done = ctl_config_move_done;
5449 		ctl_datamove((union ctl_io *)ctsio);
5450 
5451 		return (CTL_RETVAL_COMPLETE);
5452 	}
5453 
5454 	defect_list_len = 0;
5455 
5456 	if (cdb->byte2 & SF_FMTDATA) {
5457 		if (cdb->byte2 & SF_LONGLIST) {
5458 			struct scsi_format_header_long *header;
5459 
5460 			header = (struct scsi_format_header_long *)
5461 				ctsio->kern_data_ptr;
5462 
5463 			defect_list_len = scsi_4btoul(header->defect_list_len);
5464 			if (defect_list_len != 0) {
5465 				ctl_set_invalid_field(ctsio,
5466 						      /*sks_valid*/ 1,
5467 						      /*command*/ 0,
5468 						      /*field*/ 2,
5469 						      /*bit_valid*/ 0,
5470 						      /*bit*/ 0);
5471 				goto bailout;
5472 			}
5473 		} else {
5474 			struct scsi_format_header_short *header;
5475 
5476 			header = (struct scsi_format_header_short *)
5477 				ctsio->kern_data_ptr;
5478 
5479 			defect_list_len = scsi_2btoul(header->defect_list_len);
5480 			if (defect_list_len != 0) {
5481 				ctl_set_invalid_field(ctsio,
5482 						      /*sks_valid*/ 1,
5483 						      /*command*/ 0,
5484 						      /*field*/ 2,
5485 						      /*bit_valid*/ 0,
5486 						      /*bit*/ 0);
5487 				goto bailout;
5488 			}
5489 		}
5490 	}
5491 
5492 	ctl_set_success(ctsio);
5493 bailout:
5494 
5495 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5496 		free(ctsio->kern_data_ptr, M_CTL);
5497 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5498 	}
5499 
5500 	ctl_done((union ctl_io *)ctsio);
5501 	return (CTL_RETVAL_COMPLETE);
5502 }
5503 
5504 int
5505 ctl_read_buffer(struct ctl_scsiio *ctsio)
5506 {
5507 	struct ctl_lun *lun = CTL_LUN(ctsio);
5508 	uint64_t buffer_offset;
5509 	uint32_t len;
5510 	uint8_t byte2;
5511 	static uint8_t descr[4];
5512 	static uint8_t echo_descr[4] = { 0 };
5513 
5514 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5515 
5516 	switch (ctsio->cdb[0]) {
5517 	case READ_BUFFER: {
5518 		struct scsi_read_buffer *cdb;
5519 
5520 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5521 		buffer_offset = scsi_3btoul(cdb->offset);
5522 		len = scsi_3btoul(cdb->length);
5523 		byte2 = cdb->byte2;
5524 		break;
5525 	}
5526 	case READ_BUFFER_16: {
5527 		struct scsi_read_buffer_16 *cdb;
5528 
5529 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5530 		buffer_offset = scsi_8btou64(cdb->offset);
5531 		len = scsi_4btoul(cdb->length);
5532 		byte2 = cdb->byte2;
5533 		break;
5534 	}
5535 	default: /* This shouldn't happen. */
5536 		ctl_set_invalid_opcode(ctsio);
5537 		ctl_done((union ctl_io *)ctsio);
5538 		return (CTL_RETVAL_COMPLETE);
5539 	}
5540 
5541 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5542 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5543 		ctl_set_invalid_field(ctsio,
5544 				      /*sks_valid*/ 1,
5545 				      /*command*/ 1,
5546 				      /*field*/ 6,
5547 				      /*bit_valid*/ 0,
5548 				      /*bit*/ 0);
5549 		ctl_done((union ctl_io *)ctsio);
5550 		return (CTL_RETVAL_COMPLETE);
5551 	}
5552 
5553 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5554 		descr[0] = 0;
5555 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5556 		ctsio->kern_data_ptr = descr;
5557 		len = min(len, sizeof(descr));
5558 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5559 		ctsio->kern_data_ptr = echo_descr;
5560 		len = min(len, sizeof(echo_descr));
5561 	} else {
5562 		if (lun->write_buffer == NULL) {
5563 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5564 			    M_CTL, M_WAITOK);
5565 		}
5566 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5567 	}
5568 	ctsio->kern_data_len = len;
5569 	ctsio->kern_total_len = len;
5570 	ctsio->kern_rel_offset = 0;
5571 	ctsio->kern_sg_entries = 0;
5572 	ctl_set_success(ctsio);
5573 	ctsio->be_move_done = ctl_config_move_done;
5574 	ctl_datamove((union ctl_io *)ctsio);
5575 	return (CTL_RETVAL_COMPLETE);
5576 }
5577 
5578 int
5579 ctl_write_buffer(struct ctl_scsiio *ctsio)
5580 {
5581 	struct ctl_lun *lun = CTL_LUN(ctsio);
5582 	struct scsi_write_buffer *cdb;
5583 	int buffer_offset, len;
5584 
5585 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5586 
5587 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5588 
5589 	len = scsi_3btoul(cdb->length);
5590 	buffer_offset = scsi_3btoul(cdb->offset);
5591 
5592 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5593 		ctl_set_invalid_field(ctsio,
5594 				      /*sks_valid*/ 1,
5595 				      /*command*/ 1,
5596 				      /*field*/ 6,
5597 				      /*bit_valid*/ 0,
5598 				      /*bit*/ 0);
5599 		ctl_done((union ctl_io *)ctsio);
5600 		return (CTL_RETVAL_COMPLETE);
5601 	}
5602 
5603 	/*
5604 	 * If we've got a kernel request that hasn't been malloced yet,
5605 	 * malloc it and tell the caller the data buffer is here.
5606 	 */
5607 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5608 		if (lun->write_buffer == NULL) {
5609 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5610 			    M_CTL, M_WAITOK);
5611 		}
5612 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5613 		ctsio->kern_data_len = len;
5614 		ctsio->kern_total_len = len;
5615 		ctsio->kern_rel_offset = 0;
5616 		ctsio->kern_sg_entries = 0;
5617 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5618 		ctsio->be_move_done = ctl_config_move_done;
5619 		ctl_datamove((union ctl_io *)ctsio);
5620 
5621 		return (CTL_RETVAL_COMPLETE);
5622 	}
5623 
5624 	ctl_set_success(ctsio);
5625 	ctl_done((union ctl_io *)ctsio);
5626 	return (CTL_RETVAL_COMPLETE);
5627 }
5628 
5629 static int
5630 ctl_write_same_cont(union ctl_io *io)
5631 {
5632 	struct ctl_lun *lun = CTL_LUN(io);
5633 	struct ctl_scsiio *ctsio;
5634 	struct ctl_lba_len_flags *lbalen;
5635 	int retval;
5636 
5637 	ctsio = &io->scsiio;
5638 	ctsio->io_hdr.status = CTL_STATUS_NONE;
5639 	lbalen = (struct ctl_lba_len_flags *)
5640 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5641 	lbalen->lba += lbalen->len;
5642 	if ((lun->be_lun->maxlba + 1) - lbalen->lba <= UINT32_MAX) {
5643 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
5644 		lbalen->len = (lun->be_lun->maxlba + 1) - lbalen->lba;
5645 	}
5646 
5647 	CTL_DEBUG_PRINT(("ctl_write_same_cont: calling config_write()\n"));
5648 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5649 	return (retval);
5650 }
5651 
5652 int
5653 ctl_write_same(struct ctl_scsiio *ctsio)
5654 {
5655 	struct ctl_lun *lun = CTL_LUN(ctsio);
5656 	struct ctl_lba_len_flags *lbalen;
5657 	const char *val;
5658 	uint64_t lba, ival;
5659 	uint32_t num_blocks;
5660 	int len, retval;
5661 	uint8_t byte2;
5662 
5663 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5664 
5665 	switch (ctsio->cdb[0]) {
5666 	case WRITE_SAME_10: {
5667 		struct scsi_write_same_10 *cdb;
5668 
5669 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5670 
5671 		lba = scsi_4btoul(cdb->addr);
5672 		num_blocks = scsi_2btoul(cdb->length);
5673 		byte2 = cdb->byte2;
5674 		break;
5675 	}
5676 	case WRITE_SAME_16: {
5677 		struct scsi_write_same_16 *cdb;
5678 
5679 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5680 
5681 		lba = scsi_8btou64(cdb->addr);
5682 		num_blocks = scsi_4btoul(cdb->length);
5683 		byte2 = cdb->byte2;
5684 		break;
5685 	}
5686 	default:
5687 		/*
5688 		 * We got a command we don't support.  This shouldn't
5689 		 * happen, commands should be filtered out above us.
5690 		 */
5691 		ctl_set_invalid_opcode(ctsio);
5692 		ctl_done((union ctl_io *)ctsio);
5693 
5694 		return (CTL_RETVAL_COMPLETE);
5695 		break; /* NOTREACHED */
5696 	}
5697 
5698 	/* ANCHOR flag can be used only together with UNMAP */
5699 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5700 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5701 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5702 		ctl_done((union ctl_io *)ctsio);
5703 		return (CTL_RETVAL_COMPLETE);
5704 	}
5705 
5706 	/*
5707 	 * The first check is to make sure we're in bounds, the second
5708 	 * check is to catch wrap-around problems.  If the lba + num blocks
5709 	 * is less than the lba, then we've wrapped around and the block
5710 	 * range is invalid anyway.
5711 	 */
5712 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5713 	 || ((lba + num_blocks) < lba)) {
5714 		ctl_set_lba_out_of_range(ctsio,
5715 		    MAX(lba, lun->be_lun->maxlba + 1));
5716 		ctl_done((union ctl_io *)ctsio);
5717 		return (CTL_RETVAL_COMPLETE);
5718 	}
5719 
5720 	/* Zero number of blocks means "to the last logical block" */
5721 	if (num_blocks == 0) {
5722 		ival = UINT64_MAX;
5723 		val = dnvlist_get_string(lun->be_lun->options,
5724 		    "write_same_max_lba", NULL);
5725 		if (val != NULL)
5726 			ctl_expand_number(val, &ival);
5727 		if ((lun->be_lun->maxlba + 1) - lba > ival) {
5728 			ctl_set_invalid_field(ctsio,
5729 			    /*sks_valid*/ 1, /*command*/ 1,
5730 			    /*field*/ ctsio->cdb[0] == WRITE_SAME_10 ? 7 : 10,
5731 			    /*bit_valid*/ 0, /*bit*/ 0);
5732 			ctl_done((union ctl_io *)ctsio);
5733 			return (CTL_RETVAL_COMPLETE);
5734 		}
5735 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5736 			ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
5737 			ctsio->io_cont = ctl_write_same_cont;
5738 			num_blocks = 1 << 31;
5739 		} else
5740 			num_blocks = (lun->be_lun->maxlba + 1) - lba;
5741 	}
5742 
5743 	len = lun->be_lun->blocksize;
5744 
5745 	/*
5746 	 * If we've got a kernel request that hasn't been malloced yet,
5747 	 * malloc it and tell the caller the data buffer is here.
5748 	 */
5749 	if ((byte2 & SWS_NDOB) == 0 &&
5750 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5751 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5752 		ctsio->kern_data_len = len;
5753 		ctsio->kern_total_len = len;
5754 		ctsio->kern_rel_offset = 0;
5755 		ctsio->kern_sg_entries = 0;
5756 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5757 		ctsio->be_move_done = ctl_config_move_done;
5758 		ctl_datamove((union ctl_io *)ctsio);
5759 
5760 		return (CTL_RETVAL_COMPLETE);
5761 	}
5762 
5763 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5764 	lbalen->lba = lba;
5765 	lbalen->len = num_blocks;
5766 	lbalen->flags = byte2;
5767 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5768 
5769 	return (retval);
5770 }
5771 
5772 int
5773 ctl_unmap(struct ctl_scsiio *ctsio)
5774 {
5775 	struct ctl_lun *lun = CTL_LUN(ctsio);
5776 	struct scsi_unmap *cdb;
5777 	struct ctl_ptr_len_flags *ptrlen;
5778 	struct scsi_unmap_header *hdr;
5779 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5780 	uint64_t lba;
5781 	uint32_t num_blocks;
5782 	int len, retval;
5783 	uint8_t byte2;
5784 
5785 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5786 
5787 	cdb = (struct scsi_unmap *)ctsio->cdb;
5788 	len = scsi_2btoul(cdb->length);
5789 	byte2 = cdb->byte2;
5790 
5791 	/*
5792 	 * If we've got a kernel request that hasn't been malloced yet,
5793 	 * malloc it and tell the caller the data buffer is here.
5794 	 */
5795 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5796 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5797 		ctsio->kern_data_len = len;
5798 		ctsio->kern_total_len = len;
5799 		ctsio->kern_rel_offset = 0;
5800 		ctsio->kern_sg_entries = 0;
5801 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5802 		ctsio->be_move_done = ctl_config_move_done;
5803 		ctl_datamove((union ctl_io *)ctsio);
5804 
5805 		return (CTL_RETVAL_COMPLETE);
5806 	}
5807 
5808 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5809 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5810 	if (len < sizeof (*hdr) ||
5811 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5812 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5813 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5814 		ctl_set_invalid_field(ctsio,
5815 				      /*sks_valid*/ 0,
5816 				      /*command*/ 0,
5817 				      /*field*/ 0,
5818 				      /*bit_valid*/ 0,
5819 				      /*bit*/ 0);
5820 		goto done;
5821 	}
5822 	len = scsi_2btoul(hdr->desc_length);
5823 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5824 	end = buf + len / sizeof(*buf);
5825 
5826 	endnz = buf;
5827 	for (range = buf; range < end; range++) {
5828 		lba = scsi_8btou64(range->lba);
5829 		num_blocks = scsi_4btoul(range->length);
5830 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5831 		 || ((lba + num_blocks) < lba)) {
5832 			ctl_set_lba_out_of_range(ctsio,
5833 			    MAX(lba, lun->be_lun->maxlba + 1));
5834 			ctl_done((union ctl_io *)ctsio);
5835 			return (CTL_RETVAL_COMPLETE);
5836 		}
5837 		if (num_blocks != 0)
5838 			endnz = range + 1;
5839 	}
5840 
5841 	/*
5842 	 * Block backend can not handle zero last range.
5843 	 * Filter it out and return if there is nothing left.
5844 	 */
5845 	len = (uint8_t *)endnz - (uint8_t *)buf;
5846 	if (len == 0) {
5847 		ctl_set_success(ctsio);
5848 		goto done;
5849 	}
5850 
5851 	mtx_lock(&lun->lun_lock);
5852 	ptrlen = (struct ctl_ptr_len_flags *)
5853 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5854 	ptrlen->ptr = (void *)buf;
5855 	ptrlen->len = len;
5856 	ptrlen->flags = byte2;
5857 	ctl_try_unblock_others(lun, (union ctl_io *)ctsio, FALSE);
5858 	mtx_unlock(&lun->lun_lock);
5859 
5860 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5861 	return (retval);
5862 
5863 done:
5864 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5865 		free(ctsio->kern_data_ptr, M_CTL);
5866 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5867 	}
5868 	ctl_done((union ctl_io *)ctsio);
5869 	return (CTL_RETVAL_COMPLETE);
5870 }
5871 
5872 int
5873 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5874 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5875 {
5876 	struct ctl_lun *lun = CTL_LUN(ctsio);
5877 	uint8_t *current_cp;
5878 	int set_ua;
5879 	uint32_t initidx;
5880 
5881 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5882 	set_ua = 0;
5883 
5884 	current_cp = (page_index->page_data + (page_index->page_len *
5885 	    CTL_PAGE_CURRENT));
5886 
5887 	mtx_lock(&lun->lun_lock);
5888 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5889 		memcpy(current_cp, page_ptr, page_index->page_len);
5890 		set_ua = 1;
5891 	}
5892 	if (set_ua != 0)
5893 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5894 	mtx_unlock(&lun->lun_lock);
5895 	if (set_ua) {
5896 		ctl_isc_announce_mode(lun,
5897 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5898 		    page_index->page_code, page_index->subpage);
5899 	}
5900 	return (CTL_RETVAL_COMPLETE);
5901 }
5902 
5903 static void
5904 ctl_ie_timer(void *arg)
5905 {
5906 	struct ctl_lun *lun = arg;
5907 	uint64_t t;
5908 
5909 	if (lun->ie_asc == 0)
5910 		return;
5911 
5912 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5913 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5914 	else
5915 		lun->ie_reported = 0;
5916 
5917 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5918 		lun->ie_reportcnt++;
5919 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5920 		if (t == 0 || t == UINT32_MAX)
5921 			t = 3000;  /* 5 min */
5922 		callout_schedule(&lun->ie_callout, t * hz / 10);
5923 	}
5924 }
5925 
5926 int
5927 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5928 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5929 {
5930 	struct ctl_lun *lun = CTL_LUN(ctsio);
5931 	struct scsi_info_exceptions_page *pg;
5932 	uint64_t t;
5933 
5934 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5935 
5936 	pg = (struct scsi_info_exceptions_page *)page_ptr;
5937 	mtx_lock(&lun->lun_lock);
5938 	if (pg->info_flags & SIEP_FLAGS_TEST) {
5939 		lun->ie_asc = 0x5d;
5940 		lun->ie_ascq = 0xff;
5941 		if (pg->mrie == SIEP_MRIE_UA) {
5942 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5943 			lun->ie_reported = 1;
5944 		} else {
5945 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5946 			lun->ie_reported = -1;
5947 		}
5948 		lun->ie_reportcnt = 1;
5949 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5950 			lun->ie_reportcnt++;
5951 			t = scsi_4btoul(pg->interval_timer);
5952 			if (t == 0 || t == UINT32_MAX)
5953 				t = 3000;  /* 5 min */
5954 			callout_reset(&lun->ie_callout, t * hz / 10,
5955 			    ctl_ie_timer, lun);
5956 		}
5957 	} else {
5958 		lun->ie_asc = 0;
5959 		lun->ie_ascq = 0;
5960 		lun->ie_reported = 1;
5961 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5962 		lun->ie_reportcnt = UINT32_MAX;
5963 		callout_stop(&lun->ie_callout);
5964 	}
5965 	mtx_unlock(&lun->lun_lock);
5966 	return (CTL_RETVAL_COMPLETE);
5967 }
5968 
5969 static int
5970 ctl_do_mode_select(union ctl_io *io)
5971 {
5972 	struct ctl_lun *lun = CTL_LUN(io);
5973 	struct scsi_mode_page_header *page_header;
5974 	struct ctl_page_index *page_index;
5975 	struct ctl_scsiio *ctsio;
5976 	int page_len, page_len_offset, page_len_size;
5977 	union ctl_modepage_info *modepage_info;
5978 	uint16_t *len_left, *len_used;
5979 	int retval, i;
5980 
5981 	ctsio = &io->scsiio;
5982 	page_index = NULL;
5983 	page_len = 0;
5984 
5985 	modepage_info = (union ctl_modepage_info *)
5986 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5987 	len_left = &modepage_info->header.len_left;
5988 	len_used = &modepage_info->header.len_used;
5989 
5990 do_next_page:
5991 
5992 	page_header = (struct scsi_mode_page_header *)
5993 		(ctsio->kern_data_ptr + *len_used);
5994 
5995 	if (*len_left == 0) {
5996 		free(ctsio->kern_data_ptr, M_CTL);
5997 		ctl_set_success(ctsio);
5998 		ctl_done((union ctl_io *)ctsio);
5999 		return (CTL_RETVAL_COMPLETE);
6000 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6001 		free(ctsio->kern_data_ptr, M_CTL);
6002 		ctl_set_param_len_error(ctsio);
6003 		ctl_done((union ctl_io *)ctsio);
6004 		return (CTL_RETVAL_COMPLETE);
6005 
6006 	} else if ((page_header->page_code & SMPH_SPF)
6007 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6008 		free(ctsio->kern_data_ptr, M_CTL);
6009 		ctl_set_param_len_error(ctsio);
6010 		ctl_done((union ctl_io *)ctsio);
6011 		return (CTL_RETVAL_COMPLETE);
6012 	}
6013 
6014 	/*
6015 	 * XXX KDM should we do something with the block descriptor?
6016 	 */
6017 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6018 		page_index = &lun->mode_pages.index[i];
6019 		if (lun->be_lun->lun_type == T_DIRECT &&
6020 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6021 			continue;
6022 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6023 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6024 			continue;
6025 		if (lun->be_lun->lun_type == T_CDROM &&
6026 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6027 			continue;
6028 
6029 		if ((page_index->page_code & SMPH_PC_MASK) !=
6030 		    (page_header->page_code & SMPH_PC_MASK))
6031 			continue;
6032 
6033 		/*
6034 		 * If neither page has a subpage code, then we've got a
6035 		 * match.
6036 		 */
6037 		if (((page_index->page_code & SMPH_SPF) == 0)
6038 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6039 			page_len = page_header->page_length;
6040 			break;
6041 		}
6042 
6043 		/*
6044 		 * If both pages have subpages, then the subpage numbers
6045 		 * have to match.
6046 		 */
6047 		if ((page_index->page_code & SMPH_SPF)
6048 		  && (page_header->page_code & SMPH_SPF)) {
6049 			struct scsi_mode_page_header_sp *sph;
6050 
6051 			sph = (struct scsi_mode_page_header_sp *)page_header;
6052 			if (page_index->subpage == sph->subpage) {
6053 				page_len = scsi_2btoul(sph->page_length);
6054 				break;
6055 			}
6056 		}
6057 	}
6058 
6059 	/*
6060 	 * If we couldn't find the page, or if we don't have a mode select
6061 	 * handler for it, send back an error to the user.
6062 	 */
6063 	if ((i >= CTL_NUM_MODE_PAGES)
6064 	 || (page_index->select_handler == NULL)) {
6065 		ctl_set_invalid_field(ctsio,
6066 				      /*sks_valid*/ 1,
6067 				      /*command*/ 0,
6068 				      /*field*/ *len_used,
6069 				      /*bit_valid*/ 0,
6070 				      /*bit*/ 0);
6071 		free(ctsio->kern_data_ptr, M_CTL);
6072 		ctl_done((union ctl_io *)ctsio);
6073 		return (CTL_RETVAL_COMPLETE);
6074 	}
6075 
6076 	if (page_index->page_code & SMPH_SPF) {
6077 		page_len_offset = 2;
6078 		page_len_size = 2;
6079 	} else {
6080 		page_len_size = 1;
6081 		page_len_offset = 1;
6082 	}
6083 
6084 	/*
6085 	 * If the length the initiator gives us isn't the one we specify in
6086 	 * the mode page header, or if they didn't specify enough data in
6087 	 * the CDB to avoid truncating this page, kick out the request.
6088 	 */
6089 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6090 		ctl_set_invalid_field(ctsio,
6091 				      /*sks_valid*/ 1,
6092 				      /*command*/ 0,
6093 				      /*field*/ *len_used + page_len_offset,
6094 				      /*bit_valid*/ 0,
6095 				      /*bit*/ 0);
6096 		free(ctsio->kern_data_ptr, M_CTL);
6097 		ctl_done((union ctl_io *)ctsio);
6098 		return (CTL_RETVAL_COMPLETE);
6099 	}
6100 	if (*len_left < page_index->page_len) {
6101 		free(ctsio->kern_data_ptr, M_CTL);
6102 		ctl_set_param_len_error(ctsio);
6103 		ctl_done((union ctl_io *)ctsio);
6104 		return (CTL_RETVAL_COMPLETE);
6105 	}
6106 
6107 	/*
6108 	 * Run through the mode page, checking to make sure that the bits
6109 	 * the user changed are actually legal for him to change.
6110 	 */
6111 	for (i = 0; i < page_index->page_len; i++) {
6112 		uint8_t *user_byte, *change_mask, *current_byte;
6113 		int bad_bit;
6114 		int j;
6115 
6116 		user_byte = (uint8_t *)page_header + i;
6117 		change_mask = page_index->page_data +
6118 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6119 		current_byte = page_index->page_data +
6120 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6121 
6122 		/*
6123 		 * Check to see whether the user set any bits in this byte
6124 		 * that he is not allowed to set.
6125 		 */
6126 		if ((*user_byte & ~(*change_mask)) ==
6127 		    (*current_byte & ~(*change_mask)))
6128 			continue;
6129 
6130 		/*
6131 		 * Go through bit by bit to determine which one is illegal.
6132 		 */
6133 		bad_bit = 0;
6134 		for (j = 7; j >= 0; j--) {
6135 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6136 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6137 				bad_bit = i;
6138 				break;
6139 			}
6140 		}
6141 		ctl_set_invalid_field(ctsio,
6142 				      /*sks_valid*/ 1,
6143 				      /*command*/ 0,
6144 				      /*field*/ *len_used + i,
6145 				      /*bit_valid*/ 1,
6146 				      /*bit*/ bad_bit);
6147 		free(ctsio->kern_data_ptr, M_CTL);
6148 		ctl_done((union ctl_io *)ctsio);
6149 		return (CTL_RETVAL_COMPLETE);
6150 	}
6151 
6152 	/*
6153 	 * Decrement these before we call the page handler, since we may
6154 	 * end up getting called back one way or another before the handler
6155 	 * returns to this context.
6156 	 */
6157 	*len_left -= page_index->page_len;
6158 	*len_used += page_index->page_len;
6159 
6160 	retval = page_index->select_handler(ctsio, page_index,
6161 					    (uint8_t *)page_header);
6162 
6163 	/*
6164 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6165 	 * wait until this queued command completes to finish processing
6166 	 * the mode page.  If it returns anything other than
6167 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6168 	 * already set the sense information, freed the data pointer, and
6169 	 * completed the io for us.
6170 	 */
6171 	if (retval != CTL_RETVAL_COMPLETE)
6172 		goto bailout_no_done;
6173 
6174 	/*
6175 	 * If the initiator sent us more than one page, parse the next one.
6176 	 */
6177 	if (*len_left > 0)
6178 		goto do_next_page;
6179 
6180 	ctl_set_success(ctsio);
6181 	free(ctsio->kern_data_ptr, M_CTL);
6182 	ctl_done((union ctl_io *)ctsio);
6183 
6184 bailout_no_done:
6185 
6186 	return (CTL_RETVAL_COMPLETE);
6187 
6188 }
6189 
6190 int
6191 ctl_mode_select(struct ctl_scsiio *ctsio)
6192 {
6193 	struct ctl_lun *lun = CTL_LUN(ctsio);
6194 	union ctl_modepage_info *modepage_info;
6195 	int bd_len, i, header_size, param_len, rtd;
6196 	uint32_t initidx;
6197 
6198 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6199 	switch (ctsio->cdb[0]) {
6200 	case MODE_SELECT_6: {
6201 		struct scsi_mode_select_6 *cdb;
6202 
6203 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6204 
6205 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6206 		param_len = cdb->length;
6207 		header_size = sizeof(struct scsi_mode_header_6);
6208 		break;
6209 	}
6210 	case MODE_SELECT_10: {
6211 		struct scsi_mode_select_10 *cdb;
6212 
6213 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6214 
6215 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6216 		param_len = scsi_2btoul(cdb->length);
6217 		header_size = sizeof(struct scsi_mode_header_10);
6218 		break;
6219 	}
6220 	default:
6221 		ctl_set_invalid_opcode(ctsio);
6222 		ctl_done((union ctl_io *)ctsio);
6223 		return (CTL_RETVAL_COMPLETE);
6224 	}
6225 
6226 	if (rtd) {
6227 		if (param_len != 0) {
6228 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6229 			    /*command*/ 1, /*field*/ 0,
6230 			    /*bit_valid*/ 0, /*bit*/ 0);
6231 			ctl_done((union ctl_io *)ctsio);
6232 			return (CTL_RETVAL_COMPLETE);
6233 		}
6234 
6235 		/* Revert to defaults. */
6236 		ctl_init_page_index(lun);
6237 		mtx_lock(&lun->lun_lock);
6238 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6239 		mtx_unlock(&lun->lun_lock);
6240 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6241 			ctl_isc_announce_mode(lun, -1,
6242 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6243 			    lun->mode_pages.index[i].subpage);
6244 		}
6245 		ctl_set_success(ctsio);
6246 		ctl_done((union ctl_io *)ctsio);
6247 		return (CTL_RETVAL_COMPLETE);
6248 	}
6249 
6250 	/*
6251 	 * From SPC-3:
6252 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6253 	 * shall be empty. This condition shall not be considered as an error."
6254 	 */
6255 	if (param_len == 0) {
6256 		ctl_set_success(ctsio);
6257 		ctl_done((union ctl_io *)ctsio);
6258 		return (CTL_RETVAL_COMPLETE);
6259 	}
6260 
6261 	/*
6262 	 * Since we'll hit this the first time through, prior to
6263 	 * allocation, we don't need to free a data buffer here.
6264 	 */
6265 	if (param_len < header_size) {
6266 		ctl_set_param_len_error(ctsio);
6267 		ctl_done((union ctl_io *)ctsio);
6268 		return (CTL_RETVAL_COMPLETE);
6269 	}
6270 
6271 	/*
6272 	 * Allocate the data buffer and grab the user's data.  In theory,
6273 	 * we shouldn't have to sanity check the parameter list length here
6274 	 * because the maximum size is 64K.  We should be able to malloc
6275 	 * that much without too many problems.
6276 	 */
6277 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6278 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6279 		ctsio->kern_data_len = param_len;
6280 		ctsio->kern_total_len = param_len;
6281 		ctsio->kern_rel_offset = 0;
6282 		ctsio->kern_sg_entries = 0;
6283 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6284 		ctsio->be_move_done = ctl_config_move_done;
6285 		ctl_datamove((union ctl_io *)ctsio);
6286 
6287 		return (CTL_RETVAL_COMPLETE);
6288 	}
6289 
6290 	switch (ctsio->cdb[0]) {
6291 	case MODE_SELECT_6: {
6292 		struct scsi_mode_header_6 *mh6;
6293 
6294 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6295 		bd_len = mh6->blk_desc_len;
6296 		break;
6297 	}
6298 	case MODE_SELECT_10: {
6299 		struct scsi_mode_header_10 *mh10;
6300 
6301 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6302 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6303 		break;
6304 	}
6305 	default:
6306 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6307 	}
6308 
6309 	if (param_len < (header_size + bd_len)) {
6310 		free(ctsio->kern_data_ptr, M_CTL);
6311 		ctl_set_param_len_error(ctsio);
6312 		ctl_done((union ctl_io *)ctsio);
6313 		return (CTL_RETVAL_COMPLETE);
6314 	}
6315 
6316 	/*
6317 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6318 	 * ctl_config_write_done(), it'll get passed back to
6319 	 * ctl_do_mode_select() for further processing, or completion if
6320 	 * we're all done.
6321 	 */
6322 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6323 	ctsio->io_cont = ctl_do_mode_select;
6324 
6325 	modepage_info = (union ctl_modepage_info *)
6326 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6327 	memset(modepage_info, 0, sizeof(*modepage_info));
6328 	modepage_info->header.len_left = param_len - header_size - bd_len;
6329 	modepage_info->header.len_used = header_size + bd_len;
6330 
6331 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6332 }
6333 
6334 int
6335 ctl_mode_sense(struct ctl_scsiio *ctsio)
6336 {
6337 	struct ctl_lun *lun = CTL_LUN(ctsio);
6338 	int pc, page_code, llba, subpage;
6339 	int alloc_len, page_len, header_len, bd_len, total_len;
6340 	void *block_desc;
6341 	struct ctl_page_index *page_index;
6342 
6343 	llba = 0;
6344 
6345 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6346 
6347 	switch (ctsio->cdb[0]) {
6348 	case MODE_SENSE_6: {
6349 		struct scsi_mode_sense_6 *cdb;
6350 
6351 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6352 
6353 		header_len = sizeof(struct scsi_mode_hdr_6);
6354 		if (cdb->byte2 & SMS_DBD)
6355 			bd_len = 0;
6356 		else
6357 			bd_len = sizeof(struct scsi_mode_block_descr);
6358 		header_len += bd_len;
6359 
6360 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6361 		page_code = cdb->page & SMS_PAGE_CODE;
6362 		subpage = cdb->subpage;
6363 		alloc_len = cdb->length;
6364 		break;
6365 	}
6366 	case MODE_SENSE_10: {
6367 		struct scsi_mode_sense_10 *cdb;
6368 
6369 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6370 
6371 		header_len = sizeof(struct scsi_mode_hdr_10);
6372 		if (cdb->byte2 & SMS_DBD) {
6373 			bd_len = 0;
6374 		} else if (lun->be_lun->lun_type == T_DIRECT) {
6375 			if (cdb->byte2 & SMS10_LLBAA) {
6376 				llba = 1;
6377 				bd_len = sizeof(struct scsi_mode_block_descr_dlong);
6378 			} else
6379 				bd_len = sizeof(struct scsi_mode_block_descr_dshort);
6380 		} else
6381 			bd_len = sizeof(struct scsi_mode_block_descr);
6382 		header_len += bd_len;
6383 
6384 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6385 		page_code = cdb->page & SMS_PAGE_CODE;
6386 		subpage = cdb->subpage;
6387 		alloc_len = scsi_2btoul(cdb->length);
6388 		break;
6389 	}
6390 	default:
6391 		ctl_set_invalid_opcode(ctsio);
6392 		ctl_done((union ctl_io *)ctsio);
6393 		return (CTL_RETVAL_COMPLETE);
6394 		break; /* NOTREACHED */
6395 	}
6396 
6397 	/*
6398 	 * We have to make a first pass through to calculate the size of
6399 	 * the pages that match the user's query.  Then we allocate enough
6400 	 * memory to hold it, and actually copy the data into the buffer.
6401 	 */
6402 	switch (page_code) {
6403 	case SMS_ALL_PAGES_PAGE: {
6404 		u_int i;
6405 
6406 		page_len = 0;
6407 
6408 		/*
6409 		 * At the moment, values other than 0 and 0xff here are
6410 		 * reserved according to SPC-3.
6411 		 */
6412 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6413 		 && (subpage != SMS_SUBPAGE_ALL)) {
6414 			ctl_set_invalid_field(ctsio,
6415 					      /*sks_valid*/ 1,
6416 					      /*command*/ 1,
6417 					      /*field*/ 3,
6418 					      /*bit_valid*/ 0,
6419 					      /*bit*/ 0);
6420 			ctl_done((union ctl_io *)ctsio);
6421 			return (CTL_RETVAL_COMPLETE);
6422 		}
6423 
6424 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6425 			page_index = &lun->mode_pages.index[i];
6426 
6427 			/* Make sure the page is supported for this dev type */
6428 			if (lun->be_lun->lun_type == T_DIRECT &&
6429 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6430 				continue;
6431 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6432 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6433 				continue;
6434 			if (lun->be_lun->lun_type == T_CDROM &&
6435 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6436 				continue;
6437 
6438 			/*
6439 			 * We don't use this subpage if the user didn't
6440 			 * request all subpages.
6441 			 */
6442 			if ((page_index->subpage != 0)
6443 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6444 				continue;
6445 
6446 			page_len += page_index->page_len;
6447 		}
6448 		break;
6449 	}
6450 	default: {
6451 		u_int i;
6452 
6453 		page_len = 0;
6454 
6455 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6456 			page_index = &lun->mode_pages.index[i];
6457 
6458 			/* Make sure the page is supported for this dev type */
6459 			if (lun->be_lun->lun_type == T_DIRECT &&
6460 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6461 				continue;
6462 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6463 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6464 				continue;
6465 			if (lun->be_lun->lun_type == T_CDROM &&
6466 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6467 				continue;
6468 
6469 			/* Look for the right page code */
6470 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6471 				continue;
6472 
6473 			/* Look for the right subpage or the subpage wildcard*/
6474 			if ((page_index->subpage != subpage)
6475 			 && (subpage != SMS_SUBPAGE_ALL))
6476 				continue;
6477 
6478 			page_len += page_index->page_len;
6479 		}
6480 
6481 		if (page_len == 0) {
6482 			ctl_set_invalid_field(ctsio,
6483 					      /*sks_valid*/ 1,
6484 					      /*command*/ 1,
6485 					      /*field*/ 2,
6486 					      /*bit_valid*/ 1,
6487 					      /*bit*/ 5);
6488 			ctl_done((union ctl_io *)ctsio);
6489 			return (CTL_RETVAL_COMPLETE);
6490 		}
6491 		break;
6492 	}
6493 	}
6494 
6495 	total_len = header_len + page_len;
6496 
6497 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6498 	ctsio->kern_sg_entries = 0;
6499 	ctsio->kern_rel_offset = 0;
6500 	ctsio->kern_data_len = min(total_len, alloc_len);
6501 	ctsio->kern_total_len = ctsio->kern_data_len;
6502 
6503 	switch (ctsio->cdb[0]) {
6504 	case MODE_SENSE_6: {
6505 		struct scsi_mode_hdr_6 *header;
6506 
6507 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6508 
6509 		header->datalen = MIN(total_len - 1, 254);
6510 		if (lun->be_lun->lun_type == T_DIRECT) {
6511 			header->dev_specific = 0x10; /* DPOFUA */
6512 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6513 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6514 				header->dev_specific |= 0x80; /* WP */
6515 		}
6516 		header->block_descr_len = bd_len;
6517 		block_desc = &header[1];
6518 		break;
6519 	}
6520 	case MODE_SENSE_10: {
6521 		struct scsi_mode_hdr_10 *header;
6522 		int datalen;
6523 
6524 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6525 
6526 		datalen = MIN(total_len - 2, 65533);
6527 		scsi_ulto2b(datalen, header->datalen);
6528 		if (lun->be_lun->lun_type == T_DIRECT) {
6529 			header->dev_specific = 0x10; /* DPOFUA */
6530 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6531 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6532 				header->dev_specific |= 0x80; /* WP */
6533 		}
6534 		if (llba)
6535 			header->flags |= SMH_LONGLBA;
6536 		scsi_ulto2b(bd_len, header->block_descr_len);
6537 		block_desc = &header[1];
6538 		break;
6539 	}
6540 	default:
6541 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6542 	}
6543 
6544 	/*
6545 	 * If we've got a disk, use its blocksize in the block
6546 	 * descriptor.  Otherwise, just set it to 0.
6547 	 */
6548 	if (bd_len > 0) {
6549 		if (lun->be_lun->lun_type == T_DIRECT) {
6550 			if (llba) {
6551 				struct scsi_mode_block_descr_dlong *bd = block_desc;
6552 				if (lun->be_lun->maxlba != 0)
6553 					scsi_u64to8b(lun->be_lun->maxlba + 1,
6554 					    bd->num_blocks);
6555 				scsi_ulto4b(lun->be_lun->blocksize,
6556 				    bd->block_len);
6557 			} else {
6558 				struct scsi_mode_block_descr_dshort *bd = block_desc;
6559 				if (lun->be_lun->maxlba != 0)
6560 					scsi_ulto4b(MIN(lun->be_lun->maxlba+1,
6561 					    UINT32_MAX), bd->num_blocks);
6562 				scsi_ulto3b(lun->be_lun->blocksize,
6563 				    bd->block_len);
6564 			}
6565 		} else {
6566 			struct scsi_mode_block_descr *bd = block_desc;
6567 			scsi_ulto3b(0, bd->block_len);
6568 		}
6569 	}
6570 
6571 	switch (page_code) {
6572 	case SMS_ALL_PAGES_PAGE: {
6573 		int i, data_used;
6574 
6575 		data_used = header_len;
6576 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6577 			struct ctl_page_index *page_index;
6578 
6579 			page_index = &lun->mode_pages.index[i];
6580 			if (lun->be_lun->lun_type == T_DIRECT &&
6581 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6582 				continue;
6583 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6584 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6585 				continue;
6586 			if (lun->be_lun->lun_type == T_CDROM &&
6587 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6588 				continue;
6589 
6590 			/*
6591 			 * We don't use this subpage if the user didn't
6592 			 * request all subpages.  We already checked (above)
6593 			 * to make sure the user only specified a subpage
6594 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6595 			 */
6596 			if ((page_index->subpage != 0)
6597 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6598 				continue;
6599 
6600 			/*
6601 			 * Call the handler, if it exists, to update the
6602 			 * page to the latest values.
6603 			 */
6604 			if (page_index->sense_handler != NULL)
6605 				page_index->sense_handler(ctsio, page_index,pc);
6606 
6607 			memcpy(ctsio->kern_data_ptr + data_used,
6608 			       page_index->page_data +
6609 			       (page_index->page_len * pc),
6610 			       page_index->page_len);
6611 			data_used += page_index->page_len;
6612 		}
6613 		break;
6614 	}
6615 	default: {
6616 		int i, data_used;
6617 
6618 		data_used = header_len;
6619 
6620 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6621 			struct ctl_page_index *page_index;
6622 
6623 			page_index = &lun->mode_pages.index[i];
6624 
6625 			/* Look for the right page code */
6626 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6627 				continue;
6628 
6629 			/* Look for the right subpage or the subpage wildcard*/
6630 			if ((page_index->subpage != subpage)
6631 			 && (subpage != SMS_SUBPAGE_ALL))
6632 				continue;
6633 
6634 			/* Make sure the page is supported for this dev type */
6635 			if (lun->be_lun->lun_type == T_DIRECT &&
6636 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6637 				continue;
6638 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6639 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6640 				continue;
6641 			if (lun->be_lun->lun_type == T_CDROM &&
6642 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6643 				continue;
6644 
6645 			/*
6646 			 * Call the handler, if it exists, to update the
6647 			 * page to the latest values.
6648 			 */
6649 			if (page_index->sense_handler != NULL)
6650 				page_index->sense_handler(ctsio, page_index,pc);
6651 
6652 			memcpy(ctsio->kern_data_ptr + data_used,
6653 			       page_index->page_data +
6654 			       (page_index->page_len * pc),
6655 			       page_index->page_len);
6656 			data_used += page_index->page_len;
6657 		}
6658 		break;
6659 	}
6660 	}
6661 
6662 	ctl_set_success(ctsio);
6663 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6664 	ctsio->be_move_done = ctl_config_move_done;
6665 	ctl_datamove((union ctl_io *)ctsio);
6666 	return (CTL_RETVAL_COMPLETE);
6667 }
6668 
6669 int
6670 ctl_temp_log_sense_handler(struct ctl_scsiio *ctsio,
6671 			       struct ctl_page_index *page_index,
6672 			       int pc)
6673 {
6674 	struct ctl_lun *lun = CTL_LUN(ctsio);
6675 	struct scsi_log_temperature *data;
6676 	const char *value;
6677 
6678 	data = (struct scsi_log_temperature *)page_index->page_data;
6679 
6680 	scsi_ulto2b(SLP_TEMPERATURE, data->hdr.param_code);
6681 	data->hdr.param_control = SLP_LBIN;
6682 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6683 	    sizeof(struct scsi_log_param_header);
6684 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6685 	    NULL)) != NULL)
6686 		data->temperature = strtol(value, NULL, 0);
6687 	else
6688 		data->temperature = 0xff;
6689 	data++;
6690 
6691 	scsi_ulto2b(SLP_REFTEMPERATURE, data->hdr.param_code);
6692 	data->hdr.param_control = SLP_LBIN;
6693 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6694 	    sizeof(struct scsi_log_param_header);
6695 	if ((value = dnvlist_get_string(lun->be_lun->options, "reftemperature",
6696 	    NULL)) != NULL)
6697 		data->temperature = strtol(value, NULL, 0);
6698 	else
6699 		data->temperature = 0xff;
6700 	return (0);
6701 }
6702 
6703 int
6704 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6705 			       struct ctl_page_index *page_index,
6706 			       int pc)
6707 {
6708 	struct ctl_lun *lun = CTL_LUN(ctsio);
6709 	struct scsi_log_param_header *phdr;
6710 	uint8_t *data;
6711 	uint64_t val;
6712 
6713 	data = page_index->page_data;
6714 
6715 	if (lun->backend->lun_attr != NULL &&
6716 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksavail"))
6717 	     != UINT64_MAX) {
6718 		phdr = (struct scsi_log_param_header *)data;
6719 		scsi_ulto2b(0x0001, phdr->param_code);
6720 		phdr->param_control = SLP_LBIN | SLP_LP;
6721 		phdr->param_len = 8;
6722 		data = (uint8_t *)(phdr + 1);
6723 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6724 		data[4] = 0x02; /* per-pool */
6725 		data += phdr->param_len;
6726 	}
6727 
6728 	if (lun->backend->lun_attr != NULL &&
6729 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksused"))
6730 	     != UINT64_MAX) {
6731 		phdr = (struct scsi_log_param_header *)data;
6732 		scsi_ulto2b(0x0002, phdr->param_code);
6733 		phdr->param_control = SLP_LBIN | SLP_LP;
6734 		phdr->param_len = 8;
6735 		data = (uint8_t *)(phdr + 1);
6736 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6737 		data[4] = 0x01; /* per-LUN */
6738 		data += phdr->param_len;
6739 	}
6740 
6741 	if (lun->backend->lun_attr != NULL &&
6742 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksavail"))
6743 	     != UINT64_MAX) {
6744 		phdr = (struct scsi_log_param_header *)data;
6745 		scsi_ulto2b(0x00f1, phdr->param_code);
6746 		phdr->param_control = SLP_LBIN | SLP_LP;
6747 		phdr->param_len = 8;
6748 		data = (uint8_t *)(phdr + 1);
6749 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6750 		data[4] = 0x02; /* per-pool */
6751 		data += phdr->param_len;
6752 	}
6753 
6754 	if (lun->backend->lun_attr != NULL &&
6755 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksused"))
6756 	     != UINT64_MAX) {
6757 		phdr = (struct scsi_log_param_header *)data;
6758 		scsi_ulto2b(0x00f2, phdr->param_code);
6759 		phdr->param_control = SLP_LBIN | SLP_LP;
6760 		phdr->param_len = 8;
6761 		data = (uint8_t *)(phdr + 1);
6762 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6763 		data[4] = 0x02; /* per-pool */
6764 		data += phdr->param_len;
6765 	}
6766 
6767 	page_index->page_len = data - page_index->page_data;
6768 	return (0);
6769 }
6770 
6771 int
6772 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6773 			       struct ctl_page_index *page_index,
6774 			       int pc)
6775 {
6776 	struct ctl_lun *lun = CTL_LUN(ctsio);
6777 	struct stat_page *data;
6778 	struct bintime *t;
6779 
6780 	data = (struct stat_page *)page_index->page_data;
6781 
6782 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6783 	data->sap.hdr.param_control = SLP_LBIN;
6784 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6785 	    sizeof(struct scsi_log_param_header);
6786 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6787 	    data->sap.read_num);
6788 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6789 	    data->sap.write_num);
6790 	if (lun->be_lun->blocksize > 0) {
6791 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6792 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6793 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6794 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6795 	}
6796 	t = &lun->stats.time[CTL_STATS_READ];
6797 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6798 	    data->sap.read_int);
6799 	t = &lun->stats.time[CTL_STATS_WRITE];
6800 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6801 	    data->sap.write_int);
6802 	scsi_u64to8b(0, data->sap.weighted_num);
6803 	scsi_u64to8b(0, data->sap.weighted_int);
6804 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6805 	data->it.hdr.param_control = SLP_LBIN;
6806 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6807 	    sizeof(struct scsi_log_param_header);
6808 #ifdef CTL_TIME_IO
6809 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6810 #endif
6811 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6812 	data->it.hdr.param_control = SLP_LBIN;
6813 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6814 	    sizeof(struct scsi_log_param_header);
6815 	scsi_ulto4b(3, data->ti.exponent);
6816 	scsi_ulto4b(1, data->ti.integer);
6817 	return (0);
6818 }
6819 
6820 int
6821 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6822 			       struct ctl_page_index *page_index,
6823 			       int pc)
6824 {
6825 	struct ctl_lun *lun = CTL_LUN(ctsio);
6826 	struct scsi_log_informational_exceptions *data;
6827 	const char *value;
6828 
6829 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6830 
6831 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6832 	data->hdr.param_control = SLP_LBIN;
6833 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6834 	    sizeof(struct scsi_log_param_header);
6835 	data->ie_asc = lun->ie_asc;
6836 	data->ie_ascq = lun->ie_ascq;
6837 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6838 	    NULL)) != NULL)
6839 		data->temperature = strtol(value, NULL, 0);
6840 	else
6841 		data->temperature = 0xff;
6842 	return (0);
6843 }
6844 
6845 int
6846 ctl_log_sense(struct ctl_scsiio *ctsio)
6847 {
6848 	struct ctl_lun *lun = CTL_LUN(ctsio);
6849 	int i, pc, page_code, subpage;
6850 	int alloc_len, total_len;
6851 	struct ctl_page_index *page_index;
6852 	struct scsi_log_sense *cdb;
6853 	struct scsi_log_header *header;
6854 
6855 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6856 
6857 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6858 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6859 	page_code = cdb->page & SLS_PAGE_CODE;
6860 	subpage = cdb->subpage;
6861 	alloc_len = scsi_2btoul(cdb->length);
6862 
6863 	page_index = NULL;
6864 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6865 		page_index = &lun->log_pages.index[i];
6866 
6867 		/* Look for the right page code */
6868 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6869 			continue;
6870 
6871 		/* Look for the right subpage or the subpage wildcard*/
6872 		if (page_index->subpage != subpage)
6873 			continue;
6874 
6875 		break;
6876 	}
6877 	if (i >= CTL_NUM_LOG_PAGES) {
6878 		ctl_set_invalid_field(ctsio,
6879 				      /*sks_valid*/ 1,
6880 				      /*command*/ 1,
6881 				      /*field*/ 2,
6882 				      /*bit_valid*/ 0,
6883 				      /*bit*/ 0);
6884 		ctl_done((union ctl_io *)ctsio);
6885 		return (CTL_RETVAL_COMPLETE);
6886 	}
6887 
6888 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6889 
6890 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6891 	ctsio->kern_sg_entries = 0;
6892 	ctsio->kern_rel_offset = 0;
6893 	ctsio->kern_data_len = min(total_len, alloc_len);
6894 	ctsio->kern_total_len = ctsio->kern_data_len;
6895 
6896 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6897 	header->page = page_index->page_code;
6898 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6899 		header->page |= SL_DS;
6900 	if (page_index->subpage) {
6901 		header->page |= SL_SPF;
6902 		header->subpage = page_index->subpage;
6903 	}
6904 	scsi_ulto2b(page_index->page_len, header->datalen);
6905 
6906 	/*
6907 	 * Call the handler, if it exists, to update the
6908 	 * page to the latest values.
6909 	 */
6910 	if (page_index->sense_handler != NULL)
6911 		page_index->sense_handler(ctsio, page_index, pc);
6912 
6913 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6914 
6915 	ctl_set_success(ctsio);
6916 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6917 	ctsio->be_move_done = ctl_config_move_done;
6918 	ctl_datamove((union ctl_io *)ctsio);
6919 	return (CTL_RETVAL_COMPLETE);
6920 }
6921 
6922 int
6923 ctl_read_capacity(struct ctl_scsiio *ctsio)
6924 {
6925 	struct ctl_lun *lun = CTL_LUN(ctsio);
6926 	struct scsi_read_capacity *cdb;
6927 	struct scsi_read_capacity_data *data;
6928 	uint32_t lba;
6929 
6930 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6931 
6932 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6933 
6934 	lba = scsi_4btoul(cdb->addr);
6935 	if (((cdb->pmi & SRC_PMI) == 0)
6936 	 && (lba != 0)) {
6937 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6938 				      /*sks_valid*/ 1,
6939 				      /*command*/ 1,
6940 				      /*field*/ 2,
6941 				      /*bit_valid*/ 0,
6942 				      /*bit*/ 0);
6943 		ctl_done((union ctl_io *)ctsio);
6944 		return (CTL_RETVAL_COMPLETE);
6945 	}
6946 
6947 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6948 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6949 	ctsio->kern_data_len = sizeof(*data);
6950 	ctsio->kern_total_len = sizeof(*data);
6951 	ctsio->kern_rel_offset = 0;
6952 	ctsio->kern_sg_entries = 0;
6953 
6954 	/*
6955 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6956 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6957 	 * serivce action set.
6958 	 */
6959 	if (lun->be_lun->maxlba > 0xfffffffe)
6960 		scsi_ulto4b(0xffffffff, data->addr);
6961 	else
6962 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6963 
6964 	/*
6965 	 * XXX KDM this may not be 512 bytes...
6966 	 */
6967 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6968 
6969 	ctl_set_success(ctsio);
6970 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6971 	ctsio->be_move_done = ctl_config_move_done;
6972 	ctl_datamove((union ctl_io *)ctsio);
6973 	return (CTL_RETVAL_COMPLETE);
6974 }
6975 
6976 int
6977 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6978 {
6979 	struct ctl_lun *lun = CTL_LUN(ctsio);
6980 	struct scsi_read_capacity_16 *cdb;
6981 	struct scsi_read_capacity_data_long *data;
6982 	uint64_t lba;
6983 	uint32_t alloc_len;
6984 
6985 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6986 
6987 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6988 
6989 	alloc_len = scsi_4btoul(cdb->alloc_len);
6990 	lba = scsi_8btou64(cdb->addr);
6991 
6992 	if ((cdb->reladr & SRC16_PMI)
6993 	 && (lba != 0)) {
6994 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6995 				      /*sks_valid*/ 1,
6996 				      /*command*/ 1,
6997 				      /*field*/ 2,
6998 				      /*bit_valid*/ 0,
6999 				      /*bit*/ 0);
7000 		ctl_done((union ctl_io *)ctsio);
7001 		return (CTL_RETVAL_COMPLETE);
7002 	}
7003 
7004 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7005 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7006 	ctsio->kern_rel_offset = 0;
7007 	ctsio->kern_sg_entries = 0;
7008 	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
7009 	ctsio->kern_total_len = ctsio->kern_data_len;
7010 
7011 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7012 	/* XXX KDM this may not be 512 bytes... */
7013 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7014 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7015 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7016 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7017 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7018 
7019 	ctl_set_success(ctsio);
7020 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7021 	ctsio->be_move_done = ctl_config_move_done;
7022 	ctl_datamove((union ctl_io *)ctsio);
7023 	return (CTL_RETVAL_COMPLETE);
7024 }
7025 
7026 int
7027 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7028 {
7029 	struct ctl_lun *lun = CTL_LUN(ctsio);
7030 	struct scsi_get_lba_status *cdb;
7031 	struct scsi_get_lba_status_data *data;
7032 	struct ctl_lba_len_flags *lbalen;
7033 	uint64_t lba;
7034 	uint32_t alloc_len, total_len;
7035 	int retval;
7036 
7037 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7038 
7039 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7040 	lba = scsi_8btou64(cdb->addr);
7041 	alloc_len = scsi_4btoul(cdb->alloc_len);
7042 
7043 	if (lba > lun->be_lun->maxlba) {
7044 		ctl_set_lba_out_of_range(ctsio, lba);
7045 		ctl_done((union ctl_io *)ctsio);
7046 		return (CTL_RETVAL_COMPLETE);
7047 	}
7048 
7049 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7050 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7051 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7052 	ctsio->kern_rel_offset = 0;
7053 	ctsio->kern_sg_entries = 0;
7054 	ctsio->kern_data_len = min(total_len, alloc_len);
7055 	ctsio->kern_total_len = ctsio->kern_data_len;
7056 
7057 	/* Fill dummy data in case backend can't tell anything. */
7058 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7059 	scsi_u64to8b(lba, data->descr[0].addr);
7060 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7061 	    data->descr[0].length);
7062 	data->descr[0].status = 0; /* Mapped or unknown. */
7063 
7064 	ctl_set_success(ctsio);
7065 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7066 	ctsio->be_move_done = ctl_config_move_done;
7067 
7068 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7069 	lbalen->lba = lba;
7070 	lbalen->len = total_len;
7071 	lbalen->flags = 0;
7072 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7073 	return (retval);
7074 }
7075 
7076 int
7077 ctl_read_defect(struct ctl_scsiio *ctsio)
7078 {
7079 	struct scsi_read_defect_data_10 *ccb10;
7080 	struct scsi_read_defect_data_12 *ccb12;
7081 	struct scsi_read_defect_data_hdr_10 *data10;
7082 	struct scsi_read_defect_data_hdr_12 *data12;
7083 	uint32_t alloc_len, data_len;
7084 	uint8_t format;
7085 
7086 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7087 
7088 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7089 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7090 		format = ccb10->format;
7091 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7092 		data_len = sizeof(*data10);
7093 	} else {
7094 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7095 		format = ccb12->format;
7096 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7097 		data_len = sizeof(*data12);
7098 	}
7099 	if (alloc_len == 0) {
7100 		ctl_set_success(ctsio);
7101 		ctl_done((union ctl_io *)ctsio);
7102 		return (CTL_RETVAL_COMPLETE);
7103 	}
7104 
7105 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7106 	ctsio->kern_rel_offset = 0;
7107 	ctsio->kern_sg_entries = 0;
7108 	ctsio->kern_data_len = min(data_len, alloc_len);
7109 	ctsio->kern_total_len = ctsio->kern_data_len;
7110 
7111 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7112 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7113 		    ctsio->kern_data_ptr;
7114 		data10->format = format;
7115 		scsi_ulto2b(0, data10->length);
7116 	} else {
7117 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7118 		    ctsio->kern_data_ptr;
7119 		data12->format = format;
7120 		scsi_ulto2b(0, data12->generation);
7121 		scsi_ulto4b(0, data12->length);
7122 	}
7123 
7124 	ctl_set_success(ctsio);
7125 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7126 	ctsio->be_move_done = ctl_config_move_done;
7127 	ctl_datamove((union ctl_io *)ctsio);
7128 	return (CTL_RETVAL_COMPLETE);
7129 }
7130 
7131 int
7132 ctl_report_ident_info(struct ctl_scsiio *ctsio)
7133 {
7134 	struct ctl_lun *lun = CTL_LUN(ctsio);
7135 	struct scsi_report_ident_info *cdb;
7136 	struct scsi_report_ident_info_data *rii_ptr;
7137 	struct scsi_report_ident_info_descr *riid_ptr;
7138 	const char *oii, *otii;
7139 	int retval, alloc_len, total_len = 0, len = 0;
7140 
7141 	CTL_DEBUG_PRINT(("ctl_report_ident_info\n"));
7142 
7143 	cdb = (struct scsi_report_ident_info *)ctsio->cdb;
7144 	retval = CTL_RETVAL_COMPLETE;
7145 
7146 	total_len = sizeof(struct scsi_report_ident_info_data);
7147 	switch (cdb->type) {
7148 	case RII_LUII:
7149 		oii = dnvlist_get_string(lun->be_lun->options,
7150 		    "ident_info", NULL);
7151 		if (oii)
7152 			len = strlen(oii);	/* Approximately */
7153 		break;
7154 	case RII_LUTII:
7155 		otii = dnvlist_get_string(lun->be_lun->options,
7156 		    "text_ident_info", NULL);
7157 		if (otii)
7158 			len = strlen(otii) + 1;	/* NULL-terminated */
7159 		break;
7160 	case RII_IIS:
7161 		len = 2 * sizeof(struct scsi_report_ident_info_descr);
7162 		break;
7163 	default:
7164 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7165 				      /*sks_valid*/ 1,
7166 				      /*command*/ 1,
7167 				      /*field*/ 11,
7168 				      /*bit_valid*/ 1,
7169 				      /*bit*/ 2);
7170 		ctl_done((union ctl_io *)ctsio);
7171 		return(retval);
7172 	}
7173 	total_len += len;
7174 	alloc_len = scsi_4btoul(cdb->length);
7175 
7176 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7177 	ctsio->kern_sg_entries = 0;
7178 	ctsio->kern_rel_offset = 0;
7179 	ctsio->kern_data_len = min(total_len, alloc_len);
7180 	ctsio->kern_total_len = ctsio->kern_data_len;
7181 
7182 	rii_ptr = (struct scsi_report_ident_info_data *)ctsio->kern_data_ptr;
7183 	switch (cdb->type) {
7184 	case RII_LUII:
7185 		if (oii) {
7186 			if (oii[0] == '0' && oii[1] == 'x')
7187 				len = hex2bin(oii, (uint8_t *)(rii_ptr + 1), len);
7188 			else
7189 				strncpy((uint8_t *)(rii_ptr + 1), oii, len);
7190 		}
7191 		break;
7192 	case RII_LUTII:
7193 		if (otii)
7194 			strlcpy((uint8_t *)(rii_ptr + 1), otii, len);
7195 		break;
7196 	case RII_IIS:
7197 		riid_ptr = (struct scsi_report_ident_info_descr *)(rii_ptr + 1);
7198 		riid_ptr->type = RII_LUII;
7199 		scsi_ulto2b(0xffff, riid_ptr->length);
7200 		riid_ptr++;
7201 		riid_ptr->type = RII_LUTII;
7202 		scsi_ulto2b(0xffff, riid_ptr->length);
7203 	}
7204 	scsi_ulto2b(len, rii_ptr->length);
7205 
7206 	ctl_set_success(ctsio);
7207 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7208 	ctsio->be_move_done = ctl_config_move_done;
7209 	ctl_datamove((union ctl_io *)ctsio);
7210 	return(retval);
7211 }
7212 
7213 int
7214 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7215 {
7216 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7217 	struct ctl_lun *lun = CTL_LUN(ctsio);
7218 	struct scsi_maintenance_in *cdb;
7219 	int retval;
7220 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7221 	int num_ha_groups, num_target_ports, shared_group;
7222 	struct ctl_port *port;
7223 	struct scsi_target_group_data *rtg_ptr;
7224 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7225 	struct scsi_target_port_group_descriptor *tpg_desc;
7226 
7227 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7228 
7229 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7230 	retval = CTL_RETVAL_COMPLETE;
7231 
7232 	switch (cdb->byte2 & STG_PDF_MASK) {
7233 	case STG_PDF_LENGTH:
7234 		ext = 0;
7235 		break;
7236 	case STG_PDF_EXTENDED:
7237 		ext = 1;
7238 		break;
7239 	default:
7240 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7241 				      /*sks_valid*/ 1,
7242 				      /*command*/ 1,
7243 				      /*field*/ 2,
7244 				      /*bit_valid*/ 1,
7245 				      /*bit*/ 5);
7246 		ctl_done((union ctl_io *)ctsio);
7247 		return(retval);
7248 	}
7249 
7250 	num_target_ports = 0;
7251 	shared_group = (softc->is_single != 0);
7252 	mtx_lock(&softc->ctl_lock);
7253 	STAILQ_FOREACH(port, &softc->port_list, links) {
7254 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7255 			continue;
7256 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7257 			continue;
7258 		num_target_ports++;
7259 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7260 			shared_group = 1;
7261 	}
7262 	mtx_unlock(&softc->ctl_lock);
7263 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7264 
7265 	if (ext)
7266 		total_len = sizeof(struct scsi_target_group_data_extended);
7267 	else
7268 		total_len = sizeof(struct scsi_target_group_data);
7269 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7270 		(shared_group + num_ha_groups) +
7271 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7272 
7273 	alloc_len = scsi_4btoul(cdb->length);
7274 
7275 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7276 	ctsio->kern_sg_entries = 0;
7277 	ctsio->kern_rel_offset = 0;
7278 	ctsio->kern_data_len = min(total_len, alloc_len);
7279 	ctsio->kern_total_len = ctsio->kern_data_len;
7280 
7281 	if (ext) {
7282 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7283 		    ctsio->kern_data_ptr;
7284 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7285 		rtg_ext_ptr->format_type = 0x10;
7286 		rtg_ext_ptr->implicit_transition_time = 0;
7287 		tpg_desc = &rtg_ext_ptr->groups[0];
7288 	} else {
7289 		rtg_ptr = (struct scsi_target_group_data *)
7290 		    ctsio->kern_data_ptr;
7291 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7292 		tpg_desc = &rtg_ptr->groups[0];
7293 	}
7294 
7295 	mtx_lock(&softc->ctl_lock);
7296 	pg = softc->port_min / softc->port_cnt;
7297 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7298 		/* Some shelf is known to be primary. */
7299 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7300 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7301 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7302 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7303 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7304 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7305 		else
7306 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7307 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7308 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7309 		} else {
7310 			ts = os;
7311 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7312 		}
7313 	} else {
7314 		/* No known primary shelf. */
7315 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7316 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7317 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7318 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7319 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7320 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7321 		} else {
7322 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7323 		}
7324 	}
7325 	if (shared_group) {
7326 		tpg_desc->pref_state = ts;
7327 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7328 		    TPG_U_SUP | TPG_T_SUP;
7329 		scsi_ulto2b(1, tpg_desc->target_port_group);
7330 		tpg_desc->status = TPG_IMPLICIT;
7331 		pc = 0;
7332 		STAILQ_FOREACH(port, &softc->port_list, links) {
7333 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7334 				continue;
7335 			if (!softc->is_single &&
7336 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7337 				continue;
7338 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7339 				continue;
7340 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7341 			    relative_target_port_identifier);
7342 			pc++;
7343 		}
7344 		tpg_desc->target_port_count = pc;
7345 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7346 		    &tpg_desc->descriptors[pc];
7347 	}
7348 	for (g = 0; g < num_ha_groups; g++) {
7349 		tpg_desc->pref_state = (g == pg) ? ts : os;
7350 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7351 		    TPG_U_SUP | TPG_T_SUP;
7352 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7353 		tpg_desc->status = TPG_IMPLICIT;
7354 		pc = 0;
7355 		STAILQ_FOREACH(port, &softc->port_list, links) {
7356 			if (port->targ_port < g * softc->port_cnt ||
7357 			    port->targ_port >= (g + 1) * softc->port_cnt)
7358 				continue;
7359 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7360 				continue;
7361 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7362 				continue;
7363 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7364 				continue;
7365 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7366 			    relative_target_port_identifier);
7367 			pc++;
7368 		}
7369 		tpg_desc->target_port_count = pc;
7370 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7371 		    &tpg_desc->descriptors[pc];
7372 	}
7373 	mtx_unlock(&softc->ctl_lock);
7374 
7375 	ctl_set_success(ctsio);
7376 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7377 	ctsio->be_move_done = ctl_config_move_done;
7378 	ctl_datamove((union ctl_io *)ctsio);
7379 	return(retval);
7380 }
7381 
7382 int
7383 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7384 {
7385 	struct ctl_lun *lun = CTL_LUN(ctsio);
7386 	struct scsi_report_supported_opcodes *cdb;
7387 	const struct ctl_cmd_entry *entry, *sentry;
7388 	struct scsi_report_supported_opcodes_all *all;
7389 	struct scsi_report_supported_opcodes_descr *descr;
7390 	struct scsi_report_supported_opcodes_one *one;
7391 	int retval;
7392 	int alloc_len, total_len;
7393 	int opcode, service_action, i, j, num;
7394 
7395 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7396 
7397 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7398 	retval = CTL_RETVAL_COMPLETE;
7399 
7400 	opcode = cdb->requested_opcode;
7401 	service_action = scsi_2btoul(cdb->requested_service_action);
7402 	switch (cdb->options & RSO_OPTIONS_MASK) {
7403 	case RSO_OPTIONS_ALL:
7404 		num = 0;
7405 		for (i = 0; i < 256; i++) {
7406 			entry = &ctl_cmd_table[i];
7407 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7408 				for (j = 0; j < 32; j++) {
7409 					sentry = &((const struct ctl_cmd_entry *)
7410 					    entry->execute)[j];
7411 					if (ctl_cmd_applicable(
7412 					    lun->be_lun->lun_type, sentry))
7413 						num++;
7414 				}
7415 			} else {
7416 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7417 				    entry))
7418 					num++;
7419 			}
7420 		}
7421 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7422 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7423 		break;
7424 	case RSO_OPTIONS_OC:
7425 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7426 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7427 					      /*sks_valid*/ 1,
7428 					      /*command*/ 1,
7429 					      /*field*/ 2,
7430 					      /*bit_valid*/ 1,
7431 					      /*bit*/ 2);
7432 			ctl_done((union ctl_io *)ctsio);
7433 			return (CTL_RETVAL_COMPLETE);
7434 		}
7435 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7436 		break;
7437 	case RSO_OPTIONS_OC_SA:
7438 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7439 		    service_action >= 32) {
7440 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7441 					      /*sks_valid*/ 1,
7442 					      /*command*/ 1,
7443 					      /*field*/ 2,
7444 					      /*bit_valid*/ 1,
7445 					      /*bit*/ 2);
7446 			ctl_done((union ctl_io *)ctsio);
7447 			return (CTL_RETVAL_COMPLETE);
7448 		}
7449 		/* FALLTHROUGH */
7450 	case RSO_OPTIONS_OC_ASA:
7451 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7452 		break;
7453 	default:
7454 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7455 				      /*sks_valid*/ 1,
7456 				      /*command*/ 1,
7457 				      /*field*/ 2,
7458 				      /*bit_valid*/ 1,
7459 				      /*bit*/ 2);
7460 		ctl_done((union ctl_io *)ctsio);
7461 		return (CTL_RETVAL_COMPLETE);
7462 	}
7463 
7464 	alloc_len = scsi_4btoul(cdb->length);
7465 
7466 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7467 	ctsio->kern_sg_entries = 0;
7468 	ctsio->kern_rel_offset = 0;
7469 	ctsio->kern_data_len = min(total_len, alloc_len);
7470 	ctsio->kern_total_len = ctsio->kern_data_len;
7471 
7472 	switch (cdb->options & RSO_OPTIONS_MASK) {
7473 	case RSO_OPTIONS_ALL:
7474 		all = (struct scsi_report_supported_opcodes_all *)
7475 		    ctsio->kern_data_ptr;
7476 		num = 0;
7477 		for (i = 0; i < 256; i++) {
7478 			entry = &ctl_cmd_table[i];
7479 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7480 				for (j = 0; j < 32; j++) {
7481 					sentry = &((const struct ctl_cmd_entry *)
7482 					    entry->execute)[j];
7483 					if (!ctl_cmd_applicable(
7484 					    lun->be_lun->lun_type, sentry))
7485 						continue;
7486 					descr = &all->descr[num++];
7487 					descr->opcode = i;
7488 					scsi_ulto2b(j, descr->service_action);
7489 					descr->flags = RSO_SERVACTV;
7490 					scsi_ulto2b(sentry->length,
7491 					    descr->cdb_length);
7492 				}
7493 			} else {
7494 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7495 				    entry))
7496 					continue;
7497 				descr = &all->descr[num++];
7498 				descr->opcode = i;
7499 				scsi_ulto2b(0, descr->service_action);
7500 				descr->flags = 0;
7501 				scsi_ulto2b(entry->length, descr->cdb_length);
7502 			}
7503 		}
7504 		scsi_ulto4b(
7505 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7506 		    all->length);
7507 		break;
7508 	case RSO_OPTIONS_OC:
7509 		one = (struct scsi_report_supported_opcodes_one *)
7510 		    ctsio->kern_data_ptr;
7511 		entry = &ctl_cmd_table[opcode];
7512 		goto fill_one;
7513 	case RSO_OPTIONS_OC_SA:
7514 		one = (struct scsi_report_supported_opcodes_one *)
7515 		    ctsio->kern_data_ptr;
7516 		entry = &ctl_cmd_table[opcode];
7517 		entry = &((const struct ctl_cmd_entry *)
7518 		    entry->execute)[service_action];
7519 fill_one:
7520 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7521 			one->support = 3;
7522 			scsi_ulto2b(entry->length, one->cdb_length);
7523 			one->cdb_usage[0] = opcode;
7524 			memcpy(&one->cdb_usage[1], entry->usage,
7525 			    entry->length - 1);
7526 		} else
7527 			one->support = 1;
7528 		break;
7529 	case RSO_OPTIONS_OC_ASA:
7530 		one = (struct scsi_report_supported_opcodes_one *)
7531 		    ctsio->kern_data_ptr;
7532 		entry = &ctl_cmd_table[opcode];
7533 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7534 			entry = &((const struct ctl_cmd_entry *)
7535 			    entry->execute)[service_action];
7536 		} else if (service_action != 0) {
7537 			one->support = 1;
7538 			break;
7539 		}
7540 		goto fill_one;
7541 	}
7542 
7543 	ctl_set_success(ctsio);
7544 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7545 	ctsio->be_move_done = ctl_config_move_done;
7546 	ctl_datamove((union ctl_io *)ctsio);
7547 	return(retval);
7548 }
7549 
7550 int
7551 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7552 {
7553 	struct scsi_report_supported_tmf *cdb;
7554 	struct scsi_report_supported_tmf_ext_data *data;
7555 	int retval;
7556 	int alloc_len, total_len;
7557 
7558 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7559 
7560 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7561 
7562 	retval = CTL_RETVAL_COMPLETE;
7563 
7564 	if (cdb->options & RST_REPD)
7565 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7566 	else
7567 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7568 	alloc_len = scsi_4btoul(cdb->length);
7569 
7570 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7571 	ctsio->kern_sg_entries = 0;
7572 	ctsio->kern_rel_offset = 0;
7573 	ctsio->kern_data_len = min(total_len, alloc_len);
7574 	ctsio->kern_total_len = ctsio->kern_data_len;
7575 
7576 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7577 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7578 	    RST_TRS;
7579 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7580 	data->length = total_len - 4;
7581 
7582 	ctl_set_success(ctsio);
7583 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7584 	ctsio->be_move_done = ctl_config_move_done;
7585 	ctl_datamove((union ctl_io *)ctsio);
7586 	return (retval);
7587 }
7588 
7589 int
7590 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7591 {
7592 	struct scsi_report_timestamp *cdb;
7593 	struct scsi_report_timestamp_data *data;
7594 	struct timeval tv;
7595 	int64_t timestamp;
7596 	int retval;
7597 	int alloc_len, total_len;
7598 
7599 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7600 
7601 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7602 
7603 	retval = CTL_RETVAL_COMPLETE;
7604 
7605 	total_len = sizeof(struct scsi_report_timestamp_data);
7606 	alloc_len = scsi_4btoul(cdb->length);
7607 
7608 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7609 	ctsio->kern_sg_entries = 0;
7610 	ctsio->kern_rel_offset = 0;
7611 	ctsio->kern_data_len = min(total_len, alloc_len);
7612 	ctsio->kern_total_len = ctsio->kern_data_len;
7613 
7614 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7615 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7616 	data->origin = RTS_ORIG_OUTSIDE;
7617 	getmicrotime(&tv);
7618 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7619 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7620 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7621 
7622 	ctl_set_success(ctsio);
7623 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7624 	ctsio->be_move_done = ctl_config_move_done;
7625 	ctl_datamove((union ctl_io *)ctsio);
7626 	return (retval);
7627 }
7628 
7629 int
7630 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7631 {
7632 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7633 	struct ctl_lun *lun = CTL_LUN(ctsio);
7634 	struct scsi_per_res_in *cdb;
7635 	int alloc_len, total_len = 0;
7636 	/* struct scsi_per_res_in_rsrv in_data; */
7637 	uint64_t key;
7638 
7639 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7640 
7641 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7642 
7643 	alloc_len = scsi_2btoul(cdb->length);
7644 
7645 retry:
7646 	mtx_lock(&lun->lun_lock);
7647 	switch (cdb->action) {
7648 	case SPRI_RK: /* read keys */
7649 		total_len = sizeof(struct scsi_per_res_in_keys) +
7650 			lun->pr_key_count *
7651 			sizeof(struct scsi_per_res_key);
7652 		break;
7653 	case SPRI_RR: /* read reservation */
7654 		if (lun->flags & CTL_LUN_PR_RESERVED)
7655 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7656 		else
7657 			total_len = sizeof(struct scsi_per_res_in_header);
7658 		break;
7659 	case SPRI_RC: /* report capabilities */
7660 		total_len = sizeof(struct scsi_per_res_cap);
7661 		break;
7662 	case SPRI_RS: /* read full status */
7663 		total_len = sizeof(struct scsi_per_res_in_header) +
7664 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7665 		    lun->pr_key_count;
7666 		break;
7667 	default:
7668 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7669 	}
7670 	mtx_unlock(&lun->lun_lock);
7671 
7672 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7673 	ctsio->kern_rel_offset = 0;
7674 	ctsio->kern_sg_entries = 0;
7675 	ctsio->kern_data_len = min(total_len, alloc_len);
7676 	ctsio->kern_total_len = ctsio->kern_data_len;
7677 
7678 	mtx_lock(&lun->lun_lock);
7679 	switch (cdb->action) {
7680 	case SPRI_RK: { // read keys
7681         struct scsi_per_res_in_keys *res_keys;
7682 		int i, key_count;
7683 
7684 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7685 
7686 		/*
7687 		 * We had to drop the lock to allocate our buffer, which
7688 		 * leaves time for someone to come in with another
7689 		 * persistent reservation.  (That is unlikely, though,
7690 		 * since this should be the only persistent reservation
7691 		 * command active right now.)
7692 		 */
7693 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7694 		    (lun->pr_key_count *
7695 		     sizeof(struct scsi_per_res_key)))){
7696 			mtx_unlock(&lun->lun_lock);
7697 			free(ctsio->kern_data_ptr, M_CTL);
7698 			printf("%s: reservation length changed, retrying\n",
7699 			       __func__);
7700 			goto retry;
7701 		}
7702 
7703 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7704 
7705 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7706 			     lun->pr_key_count, res_keys->header.length);
7707 
7708 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7709 			if ((key = ctl_get_prkey(lun, i)) == 0)
7710 				continue;
7711 
7712 			/*
7713 			 * We used lun->pr_key_count to calculate the
7714 			 * size to allocate.  If it turns out the number of
7715 			 * initiators with the registered flag set is
7716 			 * larger than that (i.e. they haven't been kept in
7717 			 * sync), we've got a problem.
7718 			 */
7719 			if (key_count >= lun->pr_key_count) {
7720 				key_count++;
7721 				continue;
7722 			}
7723 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7724 			key_count++;
7725 		}
7726 		break;
7727 	}
7728 	case SPRI_RR: { // read reservation
7729 		struct scsi_per_res_in_rsrv *res;
7730 		int tmp_len, header_only;
7731 
7732 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7733 
7734 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7735 
7736 		if (lun->flags & CTL_LUN_PR_RESERVED)
7737 		{
7738 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7739 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7740 				    res->header.length);
7741 			header_only = 0;
7742 		} else {
7743 			tmp_len = sizeof(struct scsi_per_res_in_header);
7744 			scsi_ulto4b(0, res->header.length);
7745 			header_only = 1;
7746 		}
7747 
7748 		/*
7749 		 * We had to drop the lock to allocate our buffer, which
7750 		 * leaves time for someone to come in with another
7751 		 * persistent reservation.  (That is unlikely, though,
7752 		 * since this should be the only persistent reservation
7753 		 * command active right now.)
7754 		 */
7755 		if (tmp_len != total_len) {
7756 			mtx_unlock(&lun->lun_lock);
7757 			free(ctsio->kern_data_ptr, M_CTL);
7758 			printf("%s: reservation status changed, retrying\n",
7759 			       __func__);
7760 			goto retry;
7761 		}
7762 
7763 		/*
7764 		 * No reservation held, so we're done.
7765 		 */
7766 		if (header_only != 0)
7767 			break;
7768 
7769 		/*
7770 		 * If the registration is an All Registrants type, the key
7771 		 * is 0, since it doesn't really matter.
7772 		 */
7773 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7774 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7775 			    res->data.reservation);
7776 		}
7777 		res->data.scopetype = lun->pr_res_type;
7778 		break;
7779 	}
7780 	case SPRI_RC:     //report capabilities
7781 	{
7782 		struct scsi_per_res_cap *res_cap;
7783 		uint16_t type_mask;
7784 
7785 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7786 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7787 		res_cap->flags1 = SPRI_CRH;
7788 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7789 		type_mask = SPRI_TM_WR_EX_AR |
7790 			    SPRI_TM_EX_AC_RO |
7791 			    SPRI_TM_WR_EX_RO |
7792 			    SPRI_TM_EX_AC |
7793 			    SPRI_TM_WR_EX |
7794 			    SPRI_TM_EX_AC_AR;
7795 		scsi_ulto2b(type_mask, res_cap->type_mask);
7796 		break;
7797 	}
7798 	case SPRI_RS: { // read full status
7799 		struct scsi_per_res_in_full *res_status;
7800 		struct scsi_per_res_in_full_desc *res_desc;
7801 		struct ctl_port *port;
7802 		int i, len;
7803 
7804 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7805 
7806 		/*
7807 		 * We had to drop the lock to allocate our buffer, which
7808 		 * leaves time for someone to come in with another
7809 		 * persistent reservation.  (That is unlikely, though,
7810 		 * since this should be the only persistent reservation
7811 		 * command active right now.)
7812 		 */
7813 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7814 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7815 		     lun->pr_key_count)){
7816 			mtx_unlock(&lun->lun_lock);
7817 			free(ctsio->kern_data_ptr, M_CTL);
7818 			printf("%s: reservation length changed, retrying\n",
7819 			       __func__);
7820 			goto retry;
7821 		}
7822 
7823 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7824 
7825 		res_desc = &res_status->desc[0];
7826 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7827 			if ((key = ctl_get_prkey(lun, i)) == 0)
7828 				continue;
7829 
7830 			scsi_u64to8b(key, res_desc->res_key.key);
7831 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7832 			    (lun->pr_res_idx == i ||
7833 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7834 				res_desc->flags = SPRI_FULL_R_HOLDER;
7835 				res_desc->scopetype = lun->pr_res_type;
7836 			}
7837 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7838 			    res_desc->rel_trgt_port_id);
7839 			len = 0;
7840 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7841 			if (port != NULL)
7842 				len = ctl_create_iid(port,
7843 				    i % CTL_MAX_INIT_PER_PORT,
7844 				    res_desc->transport_id);
7845 			scsi_ulto4b(len, res_desc->additional_length);
7846 			res_desc = (struct scsi_per_res_in_full_desc *)
7847 			    &res_desc->transport_id[len];
7848 		}
7849 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7850 		    res_status->header.length);
7851 		break;
7852 	}
7853 	default:
7854 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7855 	}
7856 	mtx_unlock(&lun->lun_lock);
7857 
7858 	ctl_set_success(ctsio);
7859 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7860 	ctsio->be_move_done = ctl_config_move_done;
7861 	ctl_datamove((union ctl_io *)ctsio);
7862 	return (CTL_RETVAL_COMPLETE);
7863 }
7864 
7865 /*
7866  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7867  * it should return.
7868  */
7869 static int
7870 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7871 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7872 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7873 		struct scsi_per_res_out_parms* param)
7874 {
7875 	union ctl_ha_msg persis_io;
7876 	int i;
7877 
7878 	mtx_lock(&lun->lun_lock);
7879 	if (sa_res_key == 0) {
7880 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7881 			/* validate scope and type */
7882 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7883 			     SPR_LU_SCOPE) {
7884 				mtx_unlock(&lun->lun_lock);
7885 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7886 						      /*sks_valid*/ 1,
7887 						      /*command*/ 1,
7888 						      /*field*/ 2,
7889 						      /*bit_valid*/ 1,
7890 						      /*bit*/ 4);
7891 				ctl_done((union ctl_io *)ctsio);
7892 				return (1);
7893 			}
7894 
7895 		        if (type>8 || type==2 || type==4 || type==0) {
7896 				mtx_unlock(&lun->lun_lock);
7897 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7898        	           				      /*sks_valid*/ 1,
7899 						      /*command*/ 1,
7900 						      /*field*/ 2,
7901 						      /*bit_valid*/ 1,
7902 						      /*bit*/ 0);
7903 				ctl_done((union ctl_io *)ctsio);
7904 				return (1);
7905 		        }
7906 
7907 			/*
7908 			 * Unregister everybody else and build UA for
7909 			 * them
7910 			 */
7911 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7912 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7913 					continue;
7914 
7915 				ctl_clr_prkey(lun, i);
7916 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7917 			}
7918 			lun->pr_key_count = 1;
7919 			lun->pr_res_type = type;
7920 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7921 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7922 				lun->pr_res_idx = residx;
7923 			lun->pr_generation++;
7924 			mtx_unlock(&lun->lun_lock);
7925 
7926 			/* send msg to other side */
7927 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7928 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7929 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7930 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7931 			persis_io.pr.pr_info.res_type = type;
7932 			memcpy(persis_io.pr.pr_info.sa_res_key,
7933 			       param->serv_act_res_key,
7934 			       sizeof(param->serv_act_res_key));
7935 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7936 			    sizeof(persis_io.pr), M_WAITOK);
7937 		} else {
7938 			/* not all registrants */
7939 			mtx_unlock(&lun->lun_lock);
7940 			free(ctsio->kern_data_ptr, M_CTL);
7941 			ctl_set_invalid_field(ctsio,
7942 					      /*sks_valid*/ 1,
7943 					      /*command*/ 0,
7944 					      /*field*/ 8,
7945 					      /*bit_valid*/ 0,
7946 					      /*bit*/ 0);
7947 			ctl_done((union ctl_io *)ctsio);
7948 			return (1);
7949 		}
7950 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7951 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7952 		int found = 0;
7953 
7954 		if (res_key == sa_res_key) {
7955 			/* special case */
7956 			/*
7957 			 * The spec implies this is not good but doesn't
7958 			 * say what to do. There are two choices either
7959 			 * generate a res conflict or check condition
7960 			 * with illegal field in parameter data. Since
7961 			 * that is what is done when the sa_res_key is
7962 			 * zero I'll take that approach since this has
7963 			 * to do with the sa_res_key.
7964 			 */
7965 			mtx_unlock(&lun->lun_lock);
7966 			free(ctsio->kern_data_ptr, M_CTL);
7967 			ctl_set_invalid_field(ctsio,
7968 					      /*sks_valid*/ 1,
7969 					      /*command*/ 0,
7970 					      /*field*/ 8,
7971 					      /*bit_valid*/ 0,
7972 					      /*bit*/ 0);
7973 			ctl_done((union ctl_io *)ctsio);
7974 			return (1);
7975 		}
7976 
7977 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7978 			if (ctl_get_prkey(lun, i) != sa_res_key)
7979 				continue;
7980 
7981 			found = 1;
7982 			ctl_clr_prkey(lun, i);
7983 			lun->pr_key_count--;
7984 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7985 		}
7986 		if (!found) {
7987 			mtx_unlock(&lun->lun_lock);
7988 			free(ctsio->kern_data_ptr, M_CTL);
7989 			ctl_set_reservation_conflict(ctsio);
7990 			ctl_done((union ctl_io *)ctsio);
7991 			return (CTL_RETVAL_COMPLETE);
7992 		}
7993 		lun->pr_generation++;
7994 		mtx_unlock(&lun->lun_lock);
7995 
7996 		/* send msg to other side */
7997 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7998 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7999 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8000 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8001 		persis_io.pr.pr_info.res_type = type;
8002 		memcpy(persis_io.pr.pr_info.sa_res_key,
8003 		       param->serv_act_res_key,
8004 		       sizeof(param->serv_act_res_key));
8005 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8006 		    sizeof(persis_io.pr), M_WAITOK);
8007 	} else {
8008 		/* Reserved but not all registrants */
8009 		/* sa_res_key is res holder */
8010 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8011 			/* validate scope and type */
8012 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8013 			     SPR_LU_SCOPE) {
8014 				mtx_unlock(&lun->lun_lock);
8015 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8016 						      /*sks_valid*/ 1,
8017 						      /*command*/ 1,
8018 						      /*field*/ 2,
8019 						      /*bit_valid*/ 1,
8020 						      /*bit*/ 4);
8021 				ctl_done((union ctl_io *)ctsio);
8022 				return (1);
8023 			}
8024 
8025 			if (type>8 || type==2 || type==4 || type==0) {
8026 				mtx_unlock(&lun->lun_lock);
8027 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8028 						      /*sks_valid*/ 1,
8029 						      /*command*/ 1,
8030 						      /*field*/ 2,
8031 						      /*bit_valid*/ 1,
8032 						      /*bit*/ 0);
8033 				ctl_done((union ctl_io *)ctsio);
8034 				return (1);
8035 			}
8036 
8037 			/*
8038 			 * Do the following:
8039 			 * if sa_res_key != res_key remove all
8040 			 * registrants w/sa_res_key and generate UA
8041 			 * for these registrants(Registrations
8042 			 * Preempted) if it wasn't an exclusive
8043 			 * reservation generate UA(Reservations
8044 			 * Preempted) for all other registered nexuses
8045 			 * if the type has changed. Establish the new
8046 			 * reservation and holder. If res_key and
8047 			 * sa_res_key are the same do the above
8048 			 * except don't unregister the res holder.
8049 			 */
8050 
8051 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8052 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8053 					continue;
8054 
8055 				if (sa_res_key == ctl_get_prkey(lun, i)) {
8056 					ctl_clr_prkey(lun, i);
8057 					lun->pr_key_count--;
8058 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8059 				} else if (type != lun->pr_res_type &&
8060 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8061 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8062 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8063 				}
8064 			}
8065 			lun->pr_res_type = type;
8066 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8067 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8068 				lun->pr_res_idx = residx;
8069 			else
8070 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8071 			lun->pr_generation++;
8072 			mtx_unlock(&lun->lun_lock);
8073 
8074 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8075 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8076 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8077 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8078 			persis_io.pr.pr_info.res_type = type;
8079 			memcpy(persis_io.pr.pr_info.sa_res_key,
8080 			       param->serv_act_res_key,
8081 			       sizeof(param->serv_act_res_key));
8082 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8083 			    sizeof(persis_io.pr), M_WAITOK);
8084 		} else {
8085 			/*
8086 			 * sa_res_key is not the res holder just
8087 			 * remove registrants
8088 			 */
8089 			int found=0;
8090 
8091 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8092 				if (sa_res_key != ctl_get_prkey(lun, i))
8093 					continue;
8094 
8095 				found = 1;
8096 				ctl_clr_prkey(lun, i);
8097 				lun->pr_key_count--;
8098 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8099 			}
8100 
8101 			if (!found) {
8102 				mtx_unlock(&lun->lun_lock);
8103 				free(ctsio->kern_data_ptr, M_CTL);
8104 				ctl_set_reservation_conflict(ctsio);
8105 				ctl_done((union ctl_io *)ctsio);
8106 		        	return (1);
8107 			}
8108 			lun->pr_generation++;
8109 			mtx_unlock(&lun->lun_lock);
8110 
8111 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8112 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8113 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8114 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8115 			persis_io.pr.pr_info.res_type = type;
8116 			memcpy(persis_io.pr.pr_info.sa_res_key,
8117 			       param->serv_act_res_key,
8118 			       sizeof(param->serv_act_res_key));
8119 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8120 			    sizeof(persis_io.pr), M_WAITOK);
8121 		}
8122 	}
8123 	return (0);
8124 }
8125 
8126 static void
8127 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8128 {
8129 	uint64_t sa_res_key;
8130 	int i;
8131 
8132 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8133 
8134 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8135 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8136 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8137 		if (sa_res_key == 0) {
8138 			/*
8139 			 * Unregister everybody else and build UA for
8140 			 * them
8141 			 */
8142 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8143 				if (i == msg->pr.pr_info.residx ||
8144 				    ctl_get_prkey(lun, i) == 0)
8145 					continue;
8146 
8147 				ctl_clr_prkey(lun, i);
8148 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8149 			}
8150 
8151 			lun->pr_key_count = 1;
8152 			lun->pr_res_type = msg->pr.pr_info.res_type;
8153 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8154 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8155 				lun->pr_res_idx = msg->pr.pr_info.residx;
8156 		} else {
8157 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8158 				if (sa_res_key == ctl_get_prkey(lun, i))
8159 					continue;
8160 
8161 				ctl_clr_prkey(lun, i);
8162 				lun->pr_key_count--;
8163 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8164 			}
8165 		}
8166 	} else {
8167 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8168 			if (i == msg->pr.pr_info.residx ||
8169 			    ctl_get_prkey(lun, i) == 0)
8170 				continue;
8171 
8172 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8173 				ctl_clr_prkey(lun, i);
8174 				lun->pr_key_count--;
8175 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8176 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8177 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8178 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8179 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8180 			}
8181 		}
8182 		lun->pr_res_type = msg->pr.pr_info.res_type;
8183 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8184 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8185 			lun->pr_res_idx = msg->pr.pr_info.residx;
8186 		else
8187 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8188 	}
8189 	lun->pr_generation++;
8190 
8191 }
8192 
8193 int
8194 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8195 {
8196 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8197 	struct ctl_lun *lun = CTL_LUN(ctsio);
8198 	int retval;
8199 	u_int32_t param_len;
8200 	struct scsi_per_res_out *cdb;
8201 	struct scsi_per_res_out_parms* param;
8202 	uint32_t residx;
8203 	uint64_t res_key, sa_res_key, key;
8204 	uint8_t type;
8205 	union ctl_ha_msg persis_io;
8206 	int    i;
8207 
8208 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8209 
8210 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8211 	retval = CTL_RETVAL_COMPLETE;
8212 
8213 	/*
8214 	 * We only support whole-LUN scope.  The scope & type are ignored for
8215 	 * register, register and ignore existing key and clear.
8216 	 * We sometimes ignore scope and type on preempts too!!
8217 	 * Verify reservation type here as well.
8218 	 */
8219 	type = cdb->scope_type & SPR_TYPE_MASK;
8220 	if ((cdb->action == SPRO_RESERVE)
8221 	 || (cdb->action == SPRO_RELEASE)) {
8222 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8223 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8224 					      /*sks_valid*/ 1,
8225 					      /*command*/ 1,
8226 					      /*field*/ 2,
8227 					      /*bit_valid*/ 1,
8228 					      /*bit*/ 4);
8229 			ctl_done((union ctl_io *)ctsio);
8230 			return (CTL_RETVAL_COMPLETE);
8231 		}
8232 
8233 		if (type>8 || type==2 || type==4 || type==0) {
8234 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8235 					      /*sks_valid*/ 1,
8236 					      /*command*/ 1,
8237 					      /*field*/ 2,
8238 					      /*bit_valid*/ 1,
8239 					      /*bit*/ 0);
8240 			ctl_done((union ctl_io *)ctsio);
8241 			return (CTL_RETVAL_COMPLETE);
8242 		}
8243 	}
8244 
8245 	param_len = scsi_4btoul(cdb->length);
8246 
8247 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8248 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8249 		ctsio->kern_data_len = param_len;
8250 		ctsio->kern_total_len = param_len;
8251 		ctsio->kern_rel_offset = 0;
8252 		ctsio->kern_sg_entries = 0;
8253 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8254 		ctsio->be_move_done = ctl_config_move_done;
8255 		ctl_datamove((union ctl_io *)ctsio);
8256 
8257 		return (CTL_RETVAL_COMPLETE);
8258 	}
8259 
8260 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8261 
8262 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8263 	res_key = scsi_8btou64(param->res_key.key);
8264 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8265 
8266 	/*
8267 	 * Validate the reservation key here except for SPRO_REG_IGNO
8268 	 * This must be done for all other service actions
8269 	 */
8270 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8271 		mtx_lock(&lun->lun_lock);
8272 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8273 			if (res_key != key) {
8274 				/*
8275 				 * The current key passed in doesn't match
8276 				 * the one the initiator previously
8277 				 * registered.
8278 				 */
8279 				mtx_unlock(&lun->lun_lock);
8280 				free(ctsio->kern_data_ptr, M_CTL);
8281 				ctl_set_reservation_conflict(ctsio);
8282 				ctl_done((union ctl_io *)ctsio);
8283 				return (CTL_RETVAL_COMPLETE);
8284 			}
8285 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8286 			/*
8287 			 * We are not registered
8288 			 */
8289 			mtx_unlock(&lun->lun_lock);
8290 			free(ctsio->kern_data_ptr, M_CTL);
8291 			ctl_set_reservation_conflict(ctsio);
8292 			ctl_done((union ctl_io *)ctsio);
8293 			return (CTL_RETVAL_COMPLETE);
8294 		} else if (res_key != 0) {
8295 			/*
8296 			 * We are not registered and trying to register but
8297 			 * the register key isn't zero.
8298 			 */
8299 			mtx_unlock(&lun->lun_lock);
8300 			free(ctsio->kern_data_ptr, M_CTL);
8301 			ctl_set_reservation_conflict(ctsio);
8302 			ctl_done((union ctl_io *)ctsio);
8303 			return (CTL_RETVAL_COMPLETE);
8304 		}
8305 		mtx_unlock(&lun->lun_lock);
8306 	}
8307 
8308 	switch (cdb->action & SPRO_ACTION_MASK) {
8309 	case SPRO_REGISTER:
8310 	case SPRO_REG_IGNO: {
8311 		/*
8312 		 * We don't support any of these options, as we report in
8313 		 * the read capabilities request (see
8314 		 * ctl_persistent_reserve_in(), above).
8315 		 */
8316 		if ((param->flags & SPR_SPEC_I_PT)
8317 		 || (param->flags & SPR_ALL_TG_PT)
8318 		 || (param->flags & SPR_APTPL)) {
8319 			int bit_ptr;
8320 
8321 			if (param->flags & SPR_APTPL)
8322 				bit_ptr = 0;
8323 			else if (param->flags & SPR_ALL_TG_PT)
8324 				bit_ptr = 2;
8325 			else /* SPR_SPEC_I_PT */
8326 				bit_ptr = 3;
8327 
8328 			free(ctsio->kern_data_ptr, M_CTL);
8329 			ctl_set_invalid_field(ctsio,
8330 					      /*sks_valid*/ 1,
8331 					      /*command*/ 0,
8332 					      /*field*/ 20,
8333 					      /*bit_valid*/ 1,
8334 					      /*bit*/ bit_ptr);
8335 			ctl_done((union ctl_io *)ctsio);
8336 			return (CTL_RETVAL_COMPLETE);
8337 		}
8338 
8339 		mtx_lock(&lun->lun_lock);
8340 
8341 		/*
8342 		 * The initiator wants to clear the
8343 		 * key/unregister.
8344 		 */
8345 		if (sa_res_key == 0) {
8346 			if ((res_key == 0
8347 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8348 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8349 			  && ctl_get_prkey(lun, residx) == 0)) {
8350 				mtx_unlock(&lun->lun_lock);
8351 				goto done;
8352 			}
8353 
8354 			ctl_clr_prkey(lun, residx);
8355 			lun->pr_key_count--;
8356 
8357 			if (residx == lun->pr_res_idx) {
8358 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8359 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8360 
8361 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8362 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8363 				    lun->pr_key_count) {
8364 					/*
8365 					 * If the reservation is a registrants
8366 					 * only type we need to generate a UA
8367 					 * for other registered inits.  The
8368 					 * sense code should be RESERVATIONS
8369 					 * RELEASED
8370 					 */
8371 
8372 					for (i = softc->init_min; i < softc->init_max; i++){
8373 						if (ctl_get_prkey(lun, i) == 0)
8374 							continue;
8375 						ctl_est_ua(lun, i,
8376 						    CTL_UA_RES_RELEASE);
8377 					}
8378 				}
8379 				lun->pr_res_type = 0;
8380 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8381 				if (lun->pr_key_count==0) {
8382 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8383 					lun->pr_res_type = 0;
8384 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8385 				}
8386 			}
8387 			lun->pr_generation++;
8388 			mtx_unlock(&lun->lun_lock);
8389 
8390 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8391 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8392 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8393 			persis_io.pr.pr_info.residx = residx;
8394 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8395 			    sizeof(persis_io.pr), M_WAITOK);
8396 		} else /* sa_res_key != 0 */ {
8397 			/*
8398 			 * If we aren't registered currently then increment
8399 			 * the key count and set the registered flag.
8400 			 */
8401 			ctl_alloc_prkey(lun, residx);
8402 			if (ctl_get_prkey(lun, residx) == 0)
8403 				lun->pr_key_count++;
8404 			ctl_set_prkey(lun, residx, sa_res_key);
8405 			lun->pr_generation++;
8406 			mtx_unlock(&lun->lun_lock);
8407 
8408 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8409 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8410 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8411 			persis_io.pr.pr_info.residx = residx;
8412 			memcpy(persis_io.pr.pr_info.sa_res_key,
8413 			       param->serv_act_res_key,
8414 			       sizeof(param->serv_act_res_key));
8415 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8416 			    sizeof(persis_io.pr), M_WAITOK);
8417 		}
8418 
8419 		break;
8420 	}
8421 	case SPRO_RESERVE:
8422 		mtx_lock(&lun->lun_lock);
8423 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8424 			/*
8425 			 * if this isn't the reservation holder and it's
8426 			 * not a "all registrants" type or if the type is
8427 			 * different then we have a conflict
8428 			 */
8429 			if ((lun->pr_res_idx != residx
8430 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8431 			 || lun->pr_res_type != type) {
8432 				mtx_unlock(&lun->lun_lock);
8433 				free(ctsio->kern_data_ptr, M_CTL);
8434 				ctl_set_reservation_conflict(ctsio);
8435 				ctl_done((union ctl_io *)ctsio);
8436 				return (CTL_RETVAL_COMPLETE);
8437 			}
8438 			mtx_unlock(&lun->lun_lock);
8439 		} else /* create a reservation */ {
8440 			/*
8441 			 * If it's not an "all registrants" type record
8442 			 * reservation holder
8443 			 */
8444 			if (type != SPR_TYPE_WR_EX_AR
8445 			 && type != SPR_TYPE_EX_AC_AR)
8446 				lun->pr_res_idx = residx; /* Res holder */
8447 			else
8448 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8449 
8450 			lun->flags |= CTL_LUN_PR_RESERVED;
8451 			lun->pr_res_type = type;
8452 
8453 			mtx_unlock(&lun->lun_lock);
8454 
8455 			/* send msg to other side */
8456 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8457 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8458 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8459 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8460 			persis_io.pr.pr_info.res_type = type;
8461 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8462 			    sizeof(persis_io.pr), M_WAITOK);
8463 		}
8464 		break;
8465 
8466 	case SPRO_RELEASE:
8467 		mtx_lock(&lun->lun_lock);
8468 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8469 			/* No reservation exists return good status */
8470 			mtx_unlock(&lun->lun_lock);
8471 			goto done;
8472 		}
8473 		/*
8474 		 * Is this nexus a reservation holder?
8475 		 */
8476 		if (lun->pr_res_idx != residx
8477 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8478 			/*
8479 			 * not a res holder return good status but
8480 			 * do nothing
8481 			 */
8482 			mtx_unlock(&lun->lun_lock);
8483 			goto done;
8484 		}
8485 
8486 		if (lun->pr_res_type != type) {
8487 			mtx_unlock(&lun->lun_lock);
8488 			free(ctsio->kern_data_ptr, M_CTL);
8489 			ctl_set_illegal_pr_release(ctsio);
8490 			ctl_done((union ctl_io *)ctsio);
8491 			return (CTL_RETVAL_COMPLETE);
8492 		}
8493 
8494 		/* okay to release */
8495 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8496 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8497 		lun->pr_res_type = 0;
8498 
8499 		/*
8500 		 * If this isn't an exclusive access reservation and NUAR
8501 		 * is not set, generate UA for all other registrants.
8502 		 */
8503 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8504 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8505 			for (i = softc->init_min; i < softc->init_max; i++) {
8506 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8507 					continue;
8508 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8509 			}
8510 		}
8511 		mtx_unlock(&lun->lun_lock);
8512 
8513 		/* Send msg to other side */
8514 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8515 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8516 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8517 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8518 		     sizeof(persis_io.pr), M_WAITOK);
8519 		break;
8520 
8521 	case SPRO_CLEAR:
8522 		/* send msg to other side */
8523 
8524 		mtx_lock(&lun->lun_lock);
8525 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8526 		lun->pr_res_type = 0;
8527 		lun->pr_key_count = 0;
8528 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8529 
8530 		ctl_clr_prkey(lun, residx);
8531 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8532 			if (ctl_get_prkey(lun, i) != 0) {
8533 				ctl_clr_prkey(lun, i);
8534 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8535 			}
8536 		lun->pr_generation++;
8537 		mtx_unlock(&lun->lun_lock);
8538 
8539 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8540 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8541 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8542 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8543 		     sizeof(persis_io.pr), M_WAITOK);
8544 		break;
8545 
8546 	case SPRO_PREEMPT:
8547 	case SPRO_PRE_ABO: {
8548 		int nretval;
8549 
8550 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8551 					  residx, ctsio, cdb, param);
8552 		if (nretval != 0)
8553 			return (CTL_RETVAL_COMPLETE);
8554 		break;
8555 	}
8556 	default:
8557 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8558 	}
8559 
8560 done:
8561 	free(ctsio->kern_data_ptr, M_CTL);
8562 	ctl_set_success(ctsio);
8563 	ctl_done((union ctl_io *)ctsio);
8564 
8565 	return (retval);
8566 }
8567 
8568 /*
8569  * This routine is for handling a message from the other SC pertaining to
8570  * persistent reserve out. All the error checking will have been done
8571  * so only perorming the action need be done here to keep the two
8572  * in sync.
8573  */
8574 static void
8575 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8576 {
8577 	struct ctl_softc *softc = CTL_SOFTC(io);
8578 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8579 	struct ctl_lun *lun;
8580 	int i;
8581 	uint32_t residx, targ_lun;
8582 
8583 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8584 	mtx_lock(&softc->ctl_lock);
8585 	if (targ_lun >= ctl_max_luns ||
8586 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8587 		mtx_unlock(&softc->ctl_lock);
8588 		return;
8589 	}
8590 	mtx_lock(&lun->lun_lock);
8591 	mtx_unlock(&softc->ctl_lock);
8592 	if (lun->flags & CTL_LUN_DISABLED) {
8593 		mtx_unlock(&lun->lun_lock);
8594 		return;
8595 	}
8596 	residx = ctl_get_initindex(&msg->hdr.nexus);
8597 	switch(msg->pr.pr_info.action) {
8598 	case CTL_PR_REG_KEY:
8599 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8600 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8601 			lun->pr_key_count++;
8602 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8603 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8604 		lun->pr_generation++;
8605 		break;
8606 
8607 	case CTL_PR_UNREG_KEY:
8608 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8609 		lun->pr_key_count--;
8610 
8611 		/* XXX Need to see if the reservation has been released */
8612 		/* if so do we need to generate UA? */
8613 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8614 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8615 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8616 
8617 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8618 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8619 			    lun->pr_key_count) {
8620 				/*
8621 				 * If the reservation is a registrants
8622 				 * only type we need to generate a UA
8623 				 * for other registered inits.  The
8624 				 * sense code should be RESERVATIONS
8625 				 * RELEASED
8626 				 */
8627 
8628 				for (i = softc->init_min; i < softc->init_max; i++) {
8629 					if (ctl_get_prkey(lun, i) == 0)
8630 						continue;
8631 
8632 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8633 				}
8634 			}
8635 			lun->pr_res_type = 0;
8636 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8637 			if (lun->pr_key_count==0) {
8638 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8639 				lun->pr_res_type = 0;
8640 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8641 			}
8642 		}
8643 		lun->pr_generation++;
8644 		break;
8645 
8646 	case CTL_PR_RESERVE:
8647 		lun->flags |= CTL_LUN_PR_RESERVED;
8648 		lun->pr_res_type = msg->pr.pr_info.res_type;
8649 		lun->pr_res_idx = msg->pr.pr_info.residx;
8650 
8651 		break;
8652 
8653 	case CTL_PR_RELEASE:
8654 		/*
8655 		 * If this isn't an exclusive access reservation and NUAR
8656 		 * is not set, generate UA for all other registrants.
8657 		 */
8658 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8659 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8660 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8661 			for (i = softc->init_min; i < softc->init_max; i++) {
8662 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8663 					continue;
8664 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8665 			}
8666 		}
8667 
8668 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8669 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8670 		lun->pr_res_type = 0;
8671 		break;
8672 
8673 	case CTL_PR_PREEMPT:
8674 		ctl_pro_preempt_other(lun, msg);
8675 		break;
8676 	case CTL_PR_CLEAR:
8677 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8678 		lun->pr_res_type = 0;
8679 		lun->pr_key_count = 0;
8680 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8681 
8682 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8683 			if (ctl_get_prkey(lun, i) == 0)
8684 				continue;
8685 			ctl_clr_prkey(lun, i);
8686 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8687 		}
8688 		lun->pr_generation++;
8689 		break;
8690 	}
8691 
8692 	mtx_unlock(&lun->lun_lock);
8693 }
8694 
8695 int
8696 ctl_read_write(struct ctl_scsiio *ctsio)
8697 {
8698 	struct ctl_lun *lun = CTL_LUN(ctsio);
8699 	struct ctl_lba_len_flags *lbalen;
8700 	uint64_t lba;
8701 	uint32_t num_blocks;
8702 	int flags, retval;
8703 	int isread;
8704 
8705 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8706 
8707 	flags = 0;
8708 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8709 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8710 	switch (ctsio->cdb[0]) {
8711 	case READ_6:
8712 	case WRITE_6: {
8713 		struct scsi_rw_6 *cdb;
8714 
8715 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8716 
8717 		lba = scsi_3btoul(cdb->addr);
8718 		/* only 5 bits are valid in the most significant address byte */
8719 		lba &= 0x1fffff;
8720 		num_blocks = cdb->length;
8721 		/*
8722 		 * This is correct according to SBC-2.
8723 		 */
8724 		if (num_blocks == 0)
8725 			num_blocks = 256;
8726 		break;
8727 	}
8728 	case READ_10:
8729 	case WRITE_10: {
8730 		struct scsi_rw_10 *cdb;
8731 
8732 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8733 		if (cdb->byte2 & SRW10_FUA)
8734 			flags |= CTL_LLF_FUA;
8735 		if (cdb->byte2 & SRW10_DPO)
8736 			flags |= CTL_LLF_DPO;
8737 		lba = scsi_4btoul(cdb->addr);
8738 		num_blocks = scsi_2btoul(cdb->length);
8739 		break;
8740 	}
8741 	case WRITE_VERIFY_10: {
8742 		struct scsi_write_verify_10 *cdb;
8743 
8744 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8745 		flags |= CTL_LLF_FUA;
8746 		if (cdb->byte2 & SWV_DPO)
8747 			flags |= CTL_LLF_DPO;
8748 		lba = scsi_4btoul(cdb->addr);
8749 		num_blocks = scsi_2btoul(cdb->length);
8750 		break;
8751 	}
8752 	case READ_12:
8753 	case WRITE_12: {
8754 		struct scsi_rw_12 *cdb;
8755 
8756 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8757 		if (cdb->byte2 & SRW12_FUA)
8758 			flags |= CTL_LLF_FUA;
8759 		if (cdb->byte2 & SRW12_DPO)
8760 			flags |= CTL_LLF_DPO;
8761 		lba = scsi_4btoul(cdb->addr);
8762 		num_blocks = scsi_4btoul(cdb->length);
8763 		break;
8764 	}
8765 	case WRITE_VERIFY_12: {
8766 		struct scsi_write_verify_12 *cdb;
8767 
8768 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8769 		flags |= CTL_LLF_FUA;
8770 		if (cdb->byte2 & SWV_DPO)
8771 			flags |= CTL_LLF_DPO;
8772 		lba = scsi_4btoul(cdb->addr);
8773 		num_blocks = scsi_4btoul(cdb->length);
8774 		break;
8775 	}
8776 	case READ_16:
8777 	case WRITE_16: {
8778 		struct scsi_rw_16 *cdb;
8779 
8780 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8781 		if (cdb->byte2 & SRW12_FUA)
8782 			flags |= CTL_LLF_FUA;
8783 		if (cdb->byte2 & SRW12_DPO)
8784 			flags |= CTL_LLF_DPO;
8785 		lba = scsi_8btou64(cdb->addr);
8786 		num_blocks = scsi_4btoul(cdb->length);
8787 		break;
8788 	}
8789 	case WRITE_ATOMIC_16: {
8790 		struct scsi_write_atomic_16 *cdb;
8791 
8792 		if (lun->be_lun->atomicblock == 0) {
8793 			ctl_set_invalid_opcode(ctsio);
8794 			ctl_done((union ctl_io *)ctsio);
8795 			return (CTL_RETVAL_COMPLETE);
8796 		}
8797 
8798 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8799 		if (cdb->byte2 & SRW12_FUA)
8800 			flags |= CTL_LLF_FUA;
8801 		if (cdb->byte2 & SRW12_DPO)
8802 			flags |= CTL_LLF_DPO;
8803 		lba = scsi_8btou64(cdb->addr);
8804 		num_blocks = scsi_2btoul(cdb->length);
8805 		if (num_blocks > lun->be_lun->atomicblock) {
8806 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8807 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8808 			    /*bit*/ 0);
8809 			ctl_done((union ctl_io *)ctsio);
8810 			return (CTL_RETVAL_COMPLETE);
8811 		}
8812 		break;
8813 	}
8814 	case WRITE_VERIFY_16: {
8815 		struct scsi_write_verify_16 *cdb;
8816 
8817 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8818 		flags |= CTL_LLF_FUA;
8819 		if (cdb->byte2 & SWV_DPO)
8820 			flags |= CTL_LLF_DPO;
8821 		lba = scsi_8btou64(cdb->addr);
8822 		num_blocks = scsi_4btoul(cdb->length);
8823 		break;
8824 	}
8825 	default:
8826 		/*
8827 		 * We got a command we don't support.  This shouldn't
8828 		 * happen, commands should be filtered out above us.
8829 		 */
8830 		ctl_set_invalid_opcode(ctsio);
8831 		ctl_done((union ctl_io *)ctsio);
8832 
8833 		return (CTL_RETVAL_COMPLETE);
8834 		break; /* NOTREACHED */
8835 	}
8836 
8837 	/*
8838 	 * The first check is to make sure we're in bounds, the second
8839 	 * check is to catch wrap-around problems.  If the lba + num blocks
8840 	 * is less than the lba, then we've wrapped around and the block
8841 	 * range is invalid anyway.
8842 	 */
8843 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8844 	 || ((lba + num_blocks) < lba)) {
8845 		ctl_set_lba_out_of_range(ctsio,
8846 		    MAX(lba, lun->be_lun->maxlba + 1));
8847 		ctl_done((union ctl_io *)ctsio);
8848 		return (CTL_RETVAL_COMPLETE);
8849 	}
8850 
8851 	/*
8852 	 * According to SBC-3, a transfer length of 0 is not an error.
8853 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8854 	 * translates to 256 blocks for those commands.
8855 	 */
8856 	if (num_blocks == 0) {
8857 		ctl_set_success(ctsio);
8858 		ctl_done((union ctl_io *)ctsio);
8859 		return (CTL_RETVAL_COMPLETE);
8860 	}
8861 
8862 	/* Set FUA and/or DPO if caches are disabled. */
8863 	if (isread) {
8864 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8865 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8866 	} else {
8867 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8868 			flags |= CTL_LLF_FUA;
8869 	}
8870 
8871 	lbalen = (struct ctl_lba_len_flags *)
8872 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8873 	lbalen->lba = lba;
8874 	lbalen->len = num_blocks;
8875 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8876 
8877 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8878 	ctsio->kern_rel_offset = 0;
8879 
8880 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8881 
8882 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8883 	return (retval);
8884 }
8885 
8886 static int
8887 ctl_cnw_cont(union ctl_io *io)
8888 {
8889 	struct ctl_lun *lun = CTL_LUN(io);
8890 	struct ctl_scsiio *ctsio;
8891 	struct ctl_lba_len_flags *lbalen;
8892 	int retval;
8893 
8894 	ctsio = &io->scsiio;
8895 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8896 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8897 	lbalen = (struct ctl_lba_len_flags *)
8898 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8899 	lbalen->flags &= ~CTL_LLF_COMPARE;
8900 	lbalen->flags |= CTL_LLF_WRITE;
8901 
8902 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8903 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8904 	return (retval);
8905 }
8906 
8907 int
8908 ctl_cnw(struct ctl_scsiio *ctsio)
8909 {
8910 	struct ctl_lun *lun = CTL_LUN(ctsio);
8911 	struct ctl_lba_len_flags *lbalen;
8912 	uint64_t lba;
8913 	uint32_t num_blocks;
8914 	int flags, retval;
8915 
8916 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8917 
8918 	flags = 0;
8919 	switch (ctsio->cdb[0]) {
8920 	case COMPARE_AND_WRITE: {
8921 		struct scsi_compare_and_write *cdb;
8922 
8923 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8924 		if (cdb->byte2 & SRW10_FUA)
8925 			flags |= CTL_LLF_FUA;
8926 		if (cdb->byte2 & SRW10_DPO)
8927 			flags |= CTL_LLF_DPO;
8928 		lba = scsi_8btou64(cdb->addr);
8929 		num_blocks = cdb->length;
8930 		break;
8931 	}
8932 	default:
8933 		/*
8934 		 * We got a command we don't support.  This shouldn't
8935 		 * happen, commands should be filtered out above us.
8936 		 */
8937 		ctl_set_invalid_opcode(ctsio);
8938 		ctl_done((union ctl_io *)ctsio);
8939 
8940 		return (CTL_RETVAL_COMPLETE);
8941 		break; /* NOTREACHED */
8942 	}
8943 
8944 	/*
8945 	 * The first check is to make sure we're in bounds, the second
8946 	 * check is to catch wrap-around problems.  If the lba + num blocks
8947 	 * is less than the lba, then we've wrapped around and the block
8948 	 * range is invalid anyway.
8949 	 */
8950 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8951 	 || ((lba + num_blocks) < lba)) {
8952 		ctl_set_lba_out_of_range(ctsio,
8953 		    MAX(lba, lun->be_lun->maxlba + 1));
8954 		ctl_done((union ctl_io *)ctsio);
8955 		return (CTL_RETVAL_COMPLETE);
8956 	}
8957 
8958 	/*
8959 	 * According to SBC-3, a transfer length of 0 is not an error.
8960 	 */
8961 	if (num_blocks == 0) {
8962 		ctl_set_success(ctsio);
8963 		ctl_done((union ctl_io *)ctsio);
8964 		return (CTL_RETVAL_COMPLETE);
8965 	}
8966 
8967 	/* Set FUA if write cache is disabled. */
8968 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8969 		flags |= CTL_LLF_FUA;
8970 
8971 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8972 	ctsio->kern_rel_offset = 0;
8973 
8974 	/*
8975 	 * Set the IO_CONT flag, so that if this I/O gets passed to
8976 	 * ctl_data_submit_done(), it'll get passed back to
8977 	 * ctl_ctl_cnw_cont() for further processing.
8978 	 */
8979 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8980 	ctsio->io_cont = ctl_cnw_cont;
8981 
8982 	lbalen = (struct ctl_lba_len_flags *)
8983 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8984 	lbalen->lba = lba;
8985 	lbalen->len = num_blocks;
8986 	lbalen->flags = CTL_LLF_COMPARE | flags;
8987 
8988 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8989 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8990 	return (retval);
8991 }
8992 
8993 int
8994 ctl_verify(struct ctl_scsiio *ctsio)
8995 {
8996 	struct ctl_lun *lun = CTL_LUN(ctsio);
8997 	struct ctl_lba_len_flags *lbalen;
8998 	uint64_t lba;
8999 	uint32_t num_blocks;
9000 	int bytchk, flags;
9001 	int retval;
9002 
9003 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9004 
9005 	bytchk = 0;
9006 	flags = CTL_LLF_FUA;
9007 	switch (ctsio->cdb[0]) {
9008 	case VERIFY_10: {
9009 		struct scsi_verify_10 *cdb;
9010 
9011 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9012 		if (cdb->byte2 & SVFY_BYTCHK)
9013 			bytchk = 1;
9014 		if (cdb->byte2 & SVFY_DPO)
9015 			flags |= CTL_LLF_DPO;
9016 		lba = scsi_4btoul(cdb->addr);
9017 		num_blocks = scsi_2btoul(cdb->length);
9018 		break;
9019 	}
9020 	case VERIFY_12: {
9021 		struct scsi_verify_12 *cdb;
9022 
9023 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9024 		if (cdb->byte2 & SVFY_BYTCHK)
9025 			bytchk = 1;
9026 		if (cdb->byte2 & SVFY_DPO)
9027 			flags |= CTL_LLF_DPO;
9028 		lba = scsi_4btoul(cdb->addr);
9029 		num_blocks = scsi_4btoul(cdb->length);
9030 		break;
9031 	}
9032 	case VERIFY_16: {
9033 		struct scsi_rw_16 *cdb;
9034 
9035 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9036 		if (cdb->byte2 & SVFY_BYTCHK)
9037 			bytchk = 1;
9038 		if (cdb->byte2 & SVFY_DPO)
9039 			flags |= CTL_LLF_DPO;
9040 		lba = scsi_8btou64(cdb->addr);
9041 		num_blocks = scsi_4btoul(cdb->length);
9042 		break;
9043 	}
9044 	default:
9045 		/*
9046 		 * We got a command we don't support.  This shouldn't
9047 		 * happen, commands should be filtered out above us.
9048 		 */
9049 		ctl_set_invalid_opcode(ctsio);
9050 		ctl_done((union ctl_io *)ctsio);
9051 		return (CTL_RETVAL_COMPLETE);
9052 	}
9053 
9054 	/*
9055 	 * The first check is to make sure we're in bounds, the second
9056 	 * check is to catch wrap-around problems.  If the lba + num blocks
9057 	 * is less than the lba, then we've wrapped around and the block
9058 	 * range is invalid anyway.
9059 	 */
9060 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9061 	 || ((lba + num_blocks) < lba)) {
9062 		ctl_set_lba_out_of_range(ctsio,
9063 		    MAX(lba, lun->be_lun->maxlba + 1));
9064 		ctl_done((union ctl_io *)ctsio);
9065 		return (CTL_RETVAL_COMPLETE);
9066 	}
9067 
9068 	/*
9069 	 * According to SBC-3, a transfer length of 0 is not an error.
9070 	 */
9071 	if (num_blocks == 0) {
9072 		ctl_set_success(ctsio);
9073 		ctl_done((union ctl_io *)ctsio);
9074 		return (CTL_RETVAL_COMPLETE);
9075 	}
9076 
9077 	lbalen = (struct ctl_lba_len_flags *)
9078 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9079 	lbalen->lba = lba;
9080 	lbalen->len = num_blocks;
9081 	if (bytchk) {
9082 		lbalen->flags = CTL_LLF_COMPARE | flags;
9083 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9084 	} else {
9085 		lbalen->flags = CTL_LLF_VERIFY | flags;
9086 		ctsio->kern_total_len = 0;
9087 	}
9088 	ctsio->kern_rel_offset = 0;
9089 
9090 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9091 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9092 	return (retval);
9093 }
9094 
9095 int
9096 ctl_report_luns(struct ctl_scsiio *ctsio)
9097 {
9098 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9099 	struct ctl_port *port = CTL_PORT(ctsio);
9100 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9101 	struct scsi_report_luns *cdb;
9102 	struct scsi_report_luns_data *lun_data;
9103 	int num_filled, num_luns, num_port_luns, retval;
9104 	uint32_t alloc_len, lun_datalen;
9105 	uint32_t initidx, targ_lun_id, lun_id;
9106 
9107 	retval = CTL_RETVAL_COMPLETE;
9108 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9109 
9110 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9111 
9112 	num_luns = 0;
9113 	num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
9114 	mtx_lock(&softc->ctl_lock);
9115 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9116 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9117 			num_luns++;
9118 	}
9119 	mtx_unlock(&softc->ctl_lock);
9120 
9121 	switch (cdb->select_report) {
9122 	case RPL_REPORT_DEFAULT:
9123 	case RPL_REPORT_ALL:
9124 	case RPL_REPORT_NONSUBSID:
9125 		break;
9126 	case RPL_REPORT_WELLKNOWN:
9127 	case RPL_REPORT_ADMIN:
9128 	case RPL_REPORT_CONGLOM:
9129 		num_luns = 0;
9130 		break;
9131 	default:
9132 		ctl_set_invalid_field(ctsio,
9133 				      /*sks_valid*/ 1,
9134 				      /*command*/ 1,
9135 				      /*field*/ 2,
9136 				      /*bit_valid*/ 0,
9137 				      /*bit*/ 0);
9138 		ctl_done((union ctl_io *)ctsio);
9139 		return (retval);
9140 		break; /* NOTREACHED */
9141 	}
9142 
9143 	alloc_len = scsi_4btoul(cdb->length);
9144 	/*
9145 	 * The initiator has to allocate at least 16 bytes for this request,
9146 	 * so he can at least get the header and the first LUN.  Otherwise
9147 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9148 	 */
9149 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9150 	    sizeof(struct scsi_report_luns_lundata))) {
9151 		ctl_set_invalid_field(ctsio,
9152 				      /*sks_valid*/ 1,
9153 				      /*command*/ 1,
9154 				      /*field*/ 6,
9155 				      /*bit_valid*/ 0,
9156 				      /*bit*/ 0);
9157 		ctl_done((union ctl_io *)ctsio);
9158 		return (retval);
9159 	}
9160 
9161 	lun_datalen = sizeof(*lun_data) +
9162 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9163 
9164 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9165 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9166 	ctsio->kern_sg_entries = 0;
9167 
9168 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9169 
9170 	mtx_lock(&softc->ctl_lock);
9171 	for (targ_lun_id = 0, num_filled = 0;
9172 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9173 	    targ_lun_id++) {
9174 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9175 		if (lun_id == UINT32_MAX)
9176 			continue;
9177 		lun = softc->ctl_luns[lun_id];
9178 		if (lun == NULL)
9179 			continue;
9180 
9181 		be64enc(lun_data->luns[num_filled++].lundata,
9182 		    ctl_encode_lun(targ_lun_id));
9183 
9184 		/*
9185 		 * According to SPC-3, rev 14 section 6.21:
9186 		 *
9187 		 * "The execution of a REPORT LUNS command to any valid and
9188 		 * installed logical unit shall clear the REPORTED LUNS DATA
9189 		 * HAS CHANGED unit attention condition for all logical
9190 		 * units of that target with respect to the requesting
9191 		 * initiator. A valid and installed logical unit is one
9192 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9193 		 * INQUIRY data (see 6.4.2)."
9194 		 *
9195 		 * If request_lun is NULL, the LUN this report luns command
9196 		 * was issued to is either disabled or doesn't exist. In that
9197 		 * case, we shouldn't clear any pending lun change unit
9198 		 * attention.
9199 		 */
9200 		if (request_lun != NULL) {
9201 			mtx_lock(&lun->lun_lock);
9202 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9203 			mtx_unlock(&lun->lun_lock);
9204 		}
9205 	}
9206 	mtx_unlock(&softc->ctl_lock);
9207 
9208 	/*
9209 	 * It's quite possible that we've returned fewer LUNs than we allocated
9210 	 * space for.  Trim it.
9211 	 */
9212 	lun_datalen = sizeof(*lun_data) +
9213 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9214 	ctsio->kern_rel_offset = 0;
9215 	ctsio->kern_sg_entries = 0;
9216 	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9217 	ctsio->kern_total_len = ctsio->kern_data_len;
9218 
9219 	/*
9220 	 * We set this to the actual data length, regardless of how much
9221 	 * space we actually have to return results.  If the user looks at
9222 	 * this value, he'll know whether or not he allocated enough space
9223 	 * and reissue the command if necessary.  We don't support well
9224 	 * known logical units, so if the user asks for that, return none.
9225 	 */
9226 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9227 
9228 	/*
9229 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9230 	 * this request.
9231 	 */
9232 	ctl_set_success(ctsio);
9233 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9234 	ctsio->be_move_done = ctl_config_move_done;
9235 	ctl_datamove((union ctl_io *)ctsio);
9236 	return (retval);
9237 }
9238 
9239 int
9240 ctl_request_sense(struct ctl_scsiio *ctsio)
9241 {
9242 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9243 	struct ctl_lun *lun = CTL_LUN(ctsio);
9244 	struct scsi_request_sense *cdb;
9245 	struct scsi_sense_data *sense_ptr, *ps;
9246 	uint32_t initidx;
9247 	int have_error;
9248 	u_int sense_len = SSD_FULL_SIZE;
9249 	scsi_sense_data_type sense_format;
9250 	ctl_ua_type ua_type;
9251 	uint8_t asc = 0, ascq = 0;
9252 
9253 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9254 
9255 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9256 
9257 	/*
9258 	 * Determine which sense format the user wants.
9259 	 */
9260 	if (cdb->byte2 & SRS_DESC)
9261 		sense_format = SSD_TYPE_DESC;
9262 	else
9263 		sense_format = SSD_TYPE_FIXED;
9264 
9265 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9266 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9267 	ctsio->kern_sg_entries = 0;
9268 	ctsio->kern_rel_offset = 0;
9269 
9270 	/*
9271 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9272 	 * larger than the largest allowed value for the length field in the
9273 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9274 	 */
9275 	ctsio->kern_data_len = cdb->length;
9276 	ctsio->kern_total_len = cdb->length;
9277 
9278 	/*
9279 	 * If we don't have a LUN, we don't have any pending sense.
9280 	 */
9281 	if (lun == NULL ||
9282 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9283 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9284 		/* "Logical unit not supported" */
9285 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9286 		    /*current_error*/ 1,
9287 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9288 		    /*asc*/ 0x25,
9289 		    /*ascq*/ 0x00,
9290 		    SSD_ELEM_NONE);
9291 		goto send;
9292 	}
9293 
9294 	have_error = 0;
9295 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9296 	/*
9297 	 * Check for pending sense, and then for pending unit attentions.
9298 	 * Pending sense gets returned first, then pending unit attentions.
9299 	 */
9300 	mtx_lock(&lun->lun_lock);
9301 	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9302 	if (ps != NULL)
9303 		ps += initidx % CTL_MAX_INIT_PER_PORT;
9304 	if (ps != NULL && ps->error_code != 0) {
9305 		scsi_sense_data_type stored_format;
9306 
9307 		/*
9308 		 * Check to see which sense format was used for the stored
9309 		 * sense data.
9310 		 */
9311 		stored_format = scsi_sense_type(ps);
9312 
9313 		/*
9314 		 * If the user requested a different sense format than the
9315 		 * one we stored, then we need to convert it to the other
9316 		 * format.  If we're going from descriptor to fixed format
9317 		 * sense data, we may lose things in translation, depending
9318 		 * on what options were used.
9319 		 *
9320 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9321 		 * for some reason we'll just copy it out as-is.
9322 		 */
9323 		if ((stored_format == SSD_TYPE_FIXED)
9324 		 && (sense_format == SSD_TYPE_DESC))
9325 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9326 			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9327 		else if ((stored_format == SSD_TYPE_DESC)
9328 		      && (sense_format == SSD_TYPE_FIXED))
9329 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9330 			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9331 		else
9332 			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9333 
9334 		ps->error_code = 0;
9335 		have_error = 1;
9336 	} else {
9337 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9338 		    sense_format);
9339 		if (ua_type != CTL_UA_NONE)
9340 			have_error = 1;
9341 	}
9342 	if (have_error == 0) {
9343 		/*
9344 		 * Report informational exception if have one and allowed.
9345 		 */
9346 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9347 			asc = lun->ie_asc;
9348 			ascq = lun->ie_ascq;
9349 		}
9350 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9351 		    /*current_error*/ 1,
9352 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9353 		    /*asc*/ asc,
9354 		    /*ascq*/ ascq,
9355 		    SSD_ELEM_NONE);
9356 	}
9357 	mtx_unlock(&lun->lun_lock);
9358 
9359 send:
9360 	/*
9361 	 * We report the SCSI status as OK, since the status of the command
9362 	 * itself is OK.  We're reporting sense as parameter data.
9363 	 */
9364 	ctl_set_success(ctsio);
9365 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9366 	ctsio->be_move_done = ctl_config_move_done;
9367 	ctl_datamove((union ctl_io *)ctsio);
9368 	return (CTL_RETVAL_COMPLETE);
9369 }
9370 
9371 int
9372 ctl_tur(struct ctl_scsiio *ctsio)
9373 {
9374 
9375 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9376 
9377 	ctl_set_success(ctsio);
9378 	ctl_done((union ctl_io *)ctsio);
9379 
9380 	return (CTL_RETVAL_COMPLETE);
9381 }
9382 
9383 /*
9384  * SCSI VPD page 0x00, the Supported VPD Pages page.
9385  */
9386 static int
9387 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9388 {
9389 	struct ctl_lun *lun = CTL_LUN(ctsio);
9390 	struct scsi_vpd_supported_pages *pages;
9391 	int sup_page_size;
9392 	int p;
9393 
9394 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9395 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9396 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9397 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9398 	ctsio->kern_rel_offset = 0;
9399 	ctsio->kern_sg_entries = 0;
9400 	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9401 	ctsio->kern_total_len = ctsio->kern_data_len;
9402 
9403 	/*
9404 	 * The control device is always connected.  The disk device, on the
9405 	 * other hand, may not be online all the time.  Need to change this
9406 	 * to figure out whether the disk device is actually online or not.
9407 	 */
9408 	if (lun != NULL)
9409 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9410 				lun->be_lun->lun_type;
9411 	else
9412 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9413 
9414 	p = 0;
9415 	/* Supported VPD pages */
9416 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9417 	/* Serial Number */
9418 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9419 	/* Device Identification */
9420 	pages->page_list[p++] = SVPD_DEVICE_ID;
9421 	/* Extended INQUIRY Data */
9422 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9423 	/* Mode Page Policy */
9424 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9425 	/* SCSI Ports */
9426 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9427 	/* Third-party Copy */
9428 	pages->page_list[p++] = SVPD_SCSI_TPC;
9429 	/* SCSI Feature Sets */
9430 	pages->page_list[p++] = SVPD_SCSI_SFS;
9431 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9432 		/* Block limits */
9433 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9434 		/* Block Device Characteristics */
9435 		pages->page_list[p++] = SVPD_BDC;
9436 		/* Logical Block Provisioning */
9437 		pages->page_list[p++] = SVPD_LBP;
9438 	}
9439 	pages->length = p;
9440 
9441 	ctl_set_success(ctsio);
9442 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9443 	ctsio->be_move_done = ctl_config_move_done;
9444 	ctl_datamove((union ctl_io *)ctsio);
9445 	return (CTL_RETVAL_COMPLETE);
9446 }
9447 
9448 /*
9449  * SCSI VPD page 0x80, the Unit Serial Number page.
9450  */
9451 static int
9452 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9453 {
9454 	struct ctl_lun *lun = CTL_LUN(ctsio);
9455 	struct scsi_vpd_unit_serial_number *sn_ptr;
9456 	int data_len;
9457 
9458 	data_len = 4 + CTL_SN_LEN;
9459 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9460 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9461 	ctsio->kern_rel_offset = 0;
9462 	ctsio->kern_sg_entries = 0;
9463 	ctsio->kern_data_len = min(data_len, alloc_len);
9464 	ctsio->kern_total_len = ctsio->kern_data_len;
9465 
9466 	/*
9467 	 * The control device is always connected.  The disk device, on the
9468 	 * other hand, may not be online all the time.  Need to change this
9469 	 * to figure out whether the disk device is actually online or not.
9470 	 */
9471 	if (lun != NULL)
9472 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9473 				  lun->be_lun->lun_type;
9474 	else
9475 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9476 
9477 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9478 	sn_ptr->length = CTL_SN_LEN;
9479 	/*
9480 	 * If we don't have a LUN, we just leave the serial number as
9481 	 * all spaces.
9482 	 */
9483 	if (lun != NULL) {
9484 		strncpy((char *)sn_ptr->serial_num,
9485 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9486 	} else
9487 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9488 
9489 	ctl_set_success(ctsio);
9490 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9491 	ctsio->be_move_done = ctl_config_move_done;
9492 	ctl_datamove((union ctl_io *)ctsio);
9493 	return (CTL_RETVAL_COMPLETE);
9494 }
9495 
9496 /*
9497  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9498  */
9499 static int
9500 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9501 {
9502 	struct ctl_lun *lun = CTL_LUN(ctsio);
9503 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9504 	int data_len;
9505 
9506 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9507 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9508 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9509 	ctsio->kern_sg_entries = 0;
9510 	ctsio->kern_rel_offset = 0;
9511 	ctsio->kern_data_len = min(data_len, alloc_len);
9512 	ctsio->kern_total_len = ctsio->kern_data_len;
9513 
9514 	/*
9515 	 * The control device is always connected.  The disk device, on the
9516 	 * other hand, may not be online all the time.
9517 	 */
9518 	if (lun != NULL)
9519 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9520 				     lun->be_lun->lun_type;
9521 	else
9522 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9523 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9524 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9525 	/*
9526 	 * We support head of queue, ordered and simple tags.
9527 	 */
9528 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9529 	/*
9530 	 * Volatile cache supported.
9531 	 */
9532 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9533 
9534 	/*
9535 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9536 	 * attention for a particular IT nexus on all LUNs once we report
9537 	 * it to that nexus once.  This bit is required as of SPC-4.
9538 	 */
9539 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9540 
9541 	/*
9542 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9543 	 */
9544 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9545 
9546 	/*
9547 	 * XXX KDM in order to correctly answer this, we would need
9548 	 * information from the SIM to determine how much sense data it
9549 	 * can send.  So this would really be a path inquiry field, most
9550 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9551 	 * but the hardware may or may not be able to support that much.
9552 	 * 0 just means that the maximum sense data length is not reported.
9553 	 */
9554 	eid_ptr->max_sense_length = 0;
9555 
9556 	ctl_set_success(ctsio);
9557 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9558 	ctsio->be_move_done = ctl_config_move_done;
9559 	ctl_datamove((union ctl_io *)ctsio);
9560 	return (CTL_RETVAL_COMPLETE);
9561 }
9562 
9563 static int
9564 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9565 {
9566 	struct ctl_lun *lun = CTL_LUN(ctsio);
9567 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9568 	int data_len;
9569 
9570 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9571 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9572 
9573 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9574 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9575 	ctsio->kern_rel_offset = 0;
9576 	ctsio->kern_sg_entries = 0;
9577 	ctsio->kern_data_len = min(data_len, alloc_len);
9578 	ctsio->kern_total_len = ctsio->kern_data_len;
9579 
9580 	/*
9581 	 * The control device is always connected.  The disk device, on the
9582 	 * other hand, may not be online all the time.
9583 	 */
9584 	if (lun != NULL)
9585 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9586 				     lun->be_lun->lun_type;
9587 	else
9588 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9589 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9590 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9591 	mpp_ptr->descr[0].page_code = 0x3f;
9592 	mpp_ptr->descr[0].subpage_code = 0xff;
9593 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9594 
9595 	ctl_set_success(ctsio);
9596 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9597 	ctsio->be_move_done = ctl_config_move_done;
9598 	ctl_datamove((union ctl_io *)ctsio);
9599 	return (CTL_RETVAL_COMPLETE);
9600 }
9601 
9602 /*
9603  * SCSI VPD page 0x83, the Device Identification page.
9604  */
9605 static int
9606 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9607 {
9608 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9609 	struct ctl_port *port = CTL_PORT(ctsio);
9610 	struct ctl_lun *lun = CTL_LUN(ctsio);
9611 	struct scsi_vpd_device_id *devid_ptr;
9612 	struct scsi_vpd_id_descriptor *desc;
9613 	int data_len, g;
9614 	uint8_t proto;
9615 
9616 	data_len = sizeof(struct scsi_vpd_device_id) +
9617 	    sizeof(struct scsi_vpd_id_descriptor) +
9618 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9619 	    sizeof(struct scsi_vpd_id_descriptor) +
9620 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9621 	if (lun && lun->lun_devid)
9622 		data_len += lun->lun_devid->len;
9623 	if (port && port->port_devid)
9624 		data_len += port->port_devid->len;
9625 	if (port && port->target_devid)
9626 		data_len += port->target_devid->len;
9627 
9628 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9629 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9630 	ctsio->kern_sg_entries = 0;
9631 	ctsio->kern_rel_offset = 0;
9632 	ctsio->kern_sg_entries = 0;
9633 	ctsio->kern_data_len = min(data_len, alloc_len);
9634 	ctsio->kern_total_len = ctsio->kern_data_len;
9635 
9636 	/*
9637 	 * The control device is always connected.  The disk device, on the
9638 	 * other hand, may not be online all the time.
9639 	 */
9640 	if (lun != NULL)
9641 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9642 				     lun->be_lun->lun_type;
9643 	else
9644 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9645 	devid_ptr->page_code = SVPD_DEVICE_ID;
9646 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9647 
9648 	if (port && port->port_type == CTL_PORT_FC)
9649 		proto = SCSI_PROTO_FC << 4;
9650 	else if (port && port->port_type == CTL_PORT_SAS)
9651 		proto = SCSI_PROTO_SAS << 4;
9652 	else if (port && port->port_type == CTL_PORT_ISCSI)
9653 		proto = SCSI_PROTO_ISCSI << 4;
9654 	else
9655 		proto = SCSI_PROTO_SPI << 4;
9656 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9657 
9658 	/*
9659 	 * We're using a LUN association here.  i.e., this device ID is a
9660 	 * per-LUN identifier.
9661 	 */
9662 	if (lun && lun->lun_devid) {
9663 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9664 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9665 		    lun->lun_devid->len);
9666 	}
9667 
9668 	/*
9669 	 * This is for the WWPN which is a port association.
9670 	 */
9671 	if (port && port->port_devid) {
9672 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9673 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9674 		    port->port_devid->len);
9675 	}
9676 
9677 	/*
9678 	 * This is for the Relative Target Port(type 4h) identifier
9679 	 */
9680 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9681 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9682 	    SVPD_ID_TYPE_RELTARG;
9683 	desc->length = 4;
9684 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9685 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9686 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9687 
9688 	/*
9689 	 * This is for the Target Port Group(type 5h) identifier
9690 	 */
9691 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9692 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9693 	    SVPD_ID_TYPE_TPORTGRP;
9694 	desc->length = 4;
9695 	if (softc->is_single ||
9696 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9697 		g = 1;
9698 	else
9699 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9700 	scsi_ulto2b(g, &desc->identifier[2]);
9701 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9702 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9703 
9704 	/*
9705 	 * This is for the Target identifier
9706 	 */
9707 	if (port && port->target_devid) {
9708 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9709 	}
9710 
9711 	ctl_set_success(ctsio);
9712 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9713 	ctsio->be_move_done = ctl_config_move_done;
9714 	ctl_datamove((union ctl_io *)ctsio);
9715 	return (CTL_RETVAL_COMPLETE);
9716 }
9717 
9718 static int
9719 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9720 {
9721 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9722 	struct ctl_lun *lun = CTL_LUN(ctsio);
9723 	struct scsi_vpd_scsi_ports *sp;
9724 	struct scsi_vpd_port_designation *pd;
9725 	struct scsi_vpd_port_designation_cont *pdc;
9726 	struct ctl_port *port;
9727 	int data_len, num_target_ports, iid_len, id_len;
9728 
9729 	num_target_ports = 0;
9730 	iid_len = 0;
9731 	id_len = 0;
9732 	mtx_lock(&softc->ctl_lock);
9733 	STAILQ_FOREACH(port, &softc->port_list, links) {
9734 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9735 			continue;
9736 		if (lun != NULL &&
9737 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9738 			continue;
9739 		num_target_ports++;
9740 		if (port->init_devid)
9741 			iid_len += port->init_devid->len;
9742 		if (port->port_devid)
9743 			id_len += port->port_devid->len;
9744 	}
9745 	mtx_unlock(&softc->ctl_lock);
9746 
9747 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9748 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9749 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9750 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9751 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9752 	ctsio->kern_sg_entries = 0;
9753 	ctsio->kern_rel_offset = 0;
9754 	ctsio->kern_sg_entries = 0;
9755 	ctsio->kern_data_len = min(data_len, alloc_len);
9756 	ctsio->kern_total_len = ctsio->kern_data_len;
9757 
9758 	/*
9759 	 * The control device is always connected.  The disk device, on the
9760 	 * other hand, may not be online all the time.  Need to change this
9761 	 * to figure out whether the disk device is actually online or not.
9762 	 */
9763 	if (lun != NULL)
9764 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9765 				  lun->be_lun->lun_type;
9766 	else
9767 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9768 
9769 	sp->page_code = SVPD_SCSI_PORTS;
9770 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9771 	    sp->page_length);
9772 	pd = &sp->design[0];
9773 
9774 	mtx_lock(&softc->ctl_lock);
9775 	STAILQ_FOREACH(port, &softc->port_list, links) {
9776 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9777 			continue;
9778 		if (lun != NULL &&
9779 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9780 			continue;
9781 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9782 		if (port->init_devid) {
9783 			iid_len = port->init_devid->len;
9784 			memcpy(pd->initiator_transportid,
9785 			    port->init_devid->data, port->init_devid->len);
9786 		} else
9787 			iid_len = 0;
9788 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9789 		pdc = (struct scsi_vpd_port_designation_cont *)
9790 		    (&pd->initiator_transportid[iid_len]);
9791 		if (port->port_devid) {
9792 			id_len = port->port_devid->len;
9793 			memcpy(pdc->target_port_descriptors,
9794 			    port->port_devid->data, port->port_devid->len);
9795 		} else
9796 			id_len = 0;
9797 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9798 		pd = (struct scsi_vpd_port_designation *)
9799 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9800 	}
9801 	mtx_unlock(&softc->ctl_lock);
9802 
9803 	ctl_set_success(ctsio);
9804 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9805 	ctsio->be_move_done = ctl_config_move_done;
9806 	ctl_datamove((union ctl_io *)ctsio);
9807 	return (CTL_RETVAL_COMPLETE);
9808 }
9809 
9810 static int
9811 ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len)
9812 {
9813 	struct ctl_lun *lun = CTL_LUN(ctsio);
9814 	struct scsi_vpd_sfs *sfs_ptr;
9815 	int sfs_page_size, n;
9816 
9817 	sfs_page_size = sizeof(*sfs_ptr) + 5 * 2;
9818 	ctsio->kern_data_ptr = malloc(sfs_page_size, M_CTL, M_WAITOK | M_ZERO);
9819 	sfs_ptr = (struct scsi_vpd_sfs *)ctsio->kern_data_ptr;
9820 	ctsio->kern_sg_entries = 0;
9821 	ctsio->kern_rel_offset = 0;
9822 	ctsio->kern_sg_entries = 0;
9823 	ctsio->kern_data_len = min(sfs_page_size, alloc_len);
9824 	ctsio->kern_total_len = ctsio->kern_data_len;
9825 
9826 	/*
9827 	 * The control device is always connected.  The disk device, on the
9828 	 * other hand, may not be online all the time.  Need to change this
9829 	 * to figure out whether the disk device is actually online or not.
9830 	 */
9831 	if (lun != NULL)
9832 		sfs_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9833 				  lun->be_lun->lun_type;
9834 	else
9835 		sfs_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9836 
9837 	sfs_ptr->page_code = SVPD_SCSI_SFS;
9838 	n = 0;
9839 	/* Discovery 2016 */
9840 	scsi_ulto2b(0x0001, &sfs_ptr->codes[2 * n++]);
9841 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9842 		 /* SBC Base 2016 */
9843 		scsi_ulto2b(0x0101, &sfs_ptr->codes[2 * n++]);
9844 		 /* SBC Base 2010 */
9845 		scsi_ulto2b(0x0102, &sfs_ptr->codes[2 * n++]);
9846 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9847 			/* Basic Provisioning 2016 */
9848 			scsi_ulto2b(0x0103, &sfs_ptr->codes[2 * n++]);
9849 		}
9850 		/* Drive Maintenance 2016 */
9851 		//scsi_ulto2b(0x0104, &sfs_ptr->codes[2 * n++]);
9852 	}
9853 	scsi_ulto2b(4 + 2 * n, sfs_ptr->page_length);
9854 
9855 	ctl_set_success(ctsio);
9856 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9857 	ctsio->be_move_done = ctl_config_move_done;
9858 	ctl_datamove((union ctl_io *)ctsio);
9859 	return (CTL_RETVAL_COMPLETE);
9860 }
9861 
9862 static int
9863 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9864 {
9865 	struct ctl_lun *lun = CTL_LUN(ctsio);
9866 	struct scsi_vpd_block_limits *bl_ptr;
9867 	const char *val;
9868 	uint64_t ival;
9869 
9870 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9871 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9872 	ctsio->kern_sg_entries = 0;
9873 	ctsio->kern_rel_offset = 0;
9874 	ctsio->kern_sg_entries = 0;
9875 	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9876 	ctsio->kern_total_len = ctsio->kern_data_len;
9877 
9878 	/*
9879 	 * The control device is always connected.  The disk device, on the
9880 	 * other hand, may not be online all the time.  Need to change this
9881 	 * to figure out whether the disk device is actually online or not.
9882 	 */
9883 	if (lun != NULL)
9884 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9885 				  lun->be_lun->lun_type;
9886 	else
9887 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9888 
9889 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9890 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9891 	bl_ptr->max_cmp_write_len = 0xff;
9892 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9893 	if (lun != NULL) {
9894 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9895 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9896 			ival = 0xffffffff;
9897 			val = dnvlist_get_string(lun->be_lun->options,
9898 			    "unmap_max_lba", NULL);
9899 			if (val != NULL)
9900 				ctl_expand_number(val, &ival);
9901 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9902 			ival = 0xffffffff;
9903 			val = dnvlist_get_string(lun->be_lun->options,
9904 			    "unmap_max_descr", NULL);
9905 			if (val != NULL)
9906 				ctl_expand_number(val, &ival);
9907 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9908 			if (lun->be_lun->ublockexp != 0) {
9909 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9910 				    bl_ptr->opt_unmap_grain);
9911 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9912 				    bl_ptr->unmap_grain_align);
9913 			}
9914 		}
9915 		scsi_ulto4b(lun->be_lun->atomicblock,
9916 		    bl_ptr->max_atomic_transfer_length);
9917 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9918 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9919 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9920 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9921 		ival = UINT64_MAX;
9922 		val = dnvlist_get_string(lun->be_lun->options,
9923 		    "write_same_max_lba", NULL);
9924 		if (val != NULL)
9925 			ctl_expand_number(val, &ival);
9926 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9927 		if (lun->be_lun->maxlba + 1 > ival)
9928 			bl_ptr->flags |= SVPD_BL_WSNZ;
9929 	}
9930 
9931 	ctl_set_success(ctsio);
9932 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9933 	ctsio->be_move_done = ctl_config_move_done;
9934 	ctl_datamove((union ctl_io *)ctsio);
9935 	return (CTL_RETVAL_COMPLETE);
9936 }
9937 
9938 static int
9939 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9940 {
9941 	struct ctl_lun *lun = CTL_LUN(ctsio);
9942 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9943 	const char *value;
9944 	u_int i;
9945 
9946 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9947 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9948 	ctsio->kern_sg_entries = 0;
9949 	ctsio->kern_rel_offset = 0;
9950 	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
9951 	ctsio->kern_total_len = ctsio->kern_data_len;
9952 
9953 	/*
9954 	 * The control device is always connected.  The disk device, on the
9955 	 * other hand, may not be online all the time.  Need to change this
9956 	 * to figure out whether the disk device is actually online or not.
9957 	 */
9958 	if (lun != NULL)
9959 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9960 				  lun->be_lun->lun_type;
9961 	else
9962 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9963 	bdc_ptr->page_code = SVPD_BDC;
9964 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9965 	if (lun != NULL &&
9966 	    (value = dnvlist_get_string(lun->be_lun->options, "rpm", NULL)) != NULL)
9967 		i = strtol(value, NULL, 0);
9968 	else
9969 		i = CTL_DEFAULT_ROTATION_RATE;
9970 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9971 	if (lun != NULL &&
9972 	    (value = dnvlist_get_string(lun->be_lun->options, "formfactor", NULL)) != NULL)
9973 		i = strtol(value, NULL, 0);
9974 	else
9975 		i = 0;
9976 	bdc_ptr->wab_wac_ff = (i & 0x0f);
9977 	bdc_ptr->flags = SVPD_RBWZ | SVPD_FUAB | SVPD_VBULS;
9978 
9979 	ctl_set_success(ctsio);
9980 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9981 	ctsio->be_move_done = ctl_config_move_done;
9982 	ctl_datamove((union ctl_io *)ctsio);
9983 	return (CTL_RETVAL_COMPLETE);
9984 }
9985 
9986 static int
9987 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9988 {
9989 	struct ctl_lun *lun = CTL_LUN(ctsio);
9990 	struct scsi_vpd_logical_block_prov *lbp_ptr;
9991 	const char *value;
9992 
9993 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9994 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9995 	ctsio->kern_sg_entries = 0;
9996 	ctsio->kern_rel_offset = 0;
9997 	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
9998 	ctsio->kern_total_len = ctsio->kern_data_len;
9999 
10000 	/*
10001 	 * The control device is always connected.  The disk device, on the
10002 	 * other hand, may not be online all the time.  Need to change this
10003 	 * to figure out whether the disk device is actually online or not.
10004 	 */
10005 	if (lun != NULL)
10006 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10007 				  lun->be_lun->lun_type;
10008 	else
10009 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10010 
10011 	lbp_ptr->page_code = SVPD_LBP;
10012 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10013 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10014 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10015 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10016 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10017 		value = dnvlist_get_string(lun->be_lun->options,
10018 		    "provisioning_type", NULL);
10019 		if (value != NULL) {
10020 			if (strcmp(value, "resource") == 0)
10021 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10022 			else if (strcmp(value, "thin") == 0)
10023 				lbp_ptr->prov_type = SVPD_LBP_THIN;
10024 		} else
10025 			lbp_ptr->prov_type = SVPD_LBP_THIN;
10026 	}
10027 
10028 	ctl_set_success(ctsio);
10029 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10030 	ctsio->be_move_done = ctl_config_move_done;
10031 	ctl_datamove((union ctl_io *)ctsio);
10032 	return (CTL_RETVAL_COMPLETE);
10033 }
10034 
10035 /*
10036  * INQUIRY with the EVPD bit set.
10037  */
10038 static int
10039 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10040 {
10041 	struct ctl_lun *lun = CTL_LUN(ctsio);
10042 	struct scsi_inquiry *cdb;
10043 	int alloc_len, retval;
10044 
10045 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10046 	alloc_len = scsi_2btoul(cdb->length);
10047 
10048 	switch (cdb->page_code) {
10049 	case SVPD_SUPPORTED_PAGES:
10050 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10051 		break;
10052 	case SVPD_UNIT_SERIAL_NUMBER:
10053 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10054 		break;
10055 	case SVPD_DEVICE_ID:
10056 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10057 		break;
10058 	case SVPD_EXTENDED_INQUIRY_DATA:
10059 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10060 		break;
10061 	case SVPD_MODE_PAGE_POLICY:
10062 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10063 		break;
10064 	case SVPD_SCSI_PORTS:
10065 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10066 		break;
10067 	case SVPD_SCSI_TPC:
10068 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10069 		break;
10070 	case SVPD_SCSI_SFS:
10071 		retval = ctl_inquiry_evpd_sfs(ctsio, alloc_len);
10072 		break;
10073 	case SVPD_BLOCK_LIMITS:
10074 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10075 			goto err;
10076 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10077 		break;
10078 	case SVPD_BDC:
10079 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10080 			goto err;
10081 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10082 		break;
10083 	case SVPD_LBP:
10084 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10085 			goto err;
10086 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10087 		break;
10088 	default:
10089 err:
10090 		ctl_set_invalid_field(ctsio,
10091 				      /*sks_valid*/ 1,
10092 				      /*command*/ 1,
10093 				      /*field*/ 2,
10094 				      /*bit_valid*/ 0,
10095 				      /*bit*/ 0);
10096 		ctl_done((union ctl_io *)ctsio);
10097 		retval = CTL_RETVAL_COMPLETE;
10098 		break;
10099 	}
10100 
10101 	return (retval);
10102 }
10103 
10104 /*
10105  * Standard INQUIRY data.
10106  */
10107 static int
10108 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10109 {
10110 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
10111 	struct ctl_port *port = CTL_PORT(ctsio);
10112 	struct ctl_lun *lun = CTL_LUN(ctsio);
10113 	struct scsi_inquiry_data *inq_ptr;
10114 	struct scsi_inquiry *cdb;
10115 	const char *val;
10116 	uint32_t alloc_len, data_len;
10117 	ctl_port_type port_type;
10118 
10119 	port_type = port->port_type;
10120 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10121 		port_type = CTL_PORT_SCSI;
10122 
10123 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10124 	alloc_len = scsi_2btoul(cdb->length);
10125 
10126 	/*
10127 	 * We malloc the full inquiry data size here and fill it
10128 	 * in.  If the user only asks for less, we'll give him
10129 	 * that much.
10130 	 */
10131 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10132 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10133 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10134 	ctsio->kern_sg_entries = 0;
10135 	ctsio->kern_rel_offset = 0;
10136 	ctsio->kern_data_len = min(data_len, alloc_len);
10137 	ctsio->kern_total_len = ctsio->kern_data_len;
10138 
10139 	if (lun != NULL) {
10140 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10141 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10142 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10143 			    lun->be_lun->lun_type;
10144 		} else {
10145 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10146 			    lun->be_lun->lun_type;
10147 		}
10148 		if (lun->flags & CTL_LUN_REMOVABLE)
10149 			inq_ptr->dev_qual2 |= SID_RMB;
10150 	} else
10151 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10152 
10153 	/* RMB in byte 2 is 0 */
10154 	inq_ptr->version = SCSI_REV_SPC5;
10155 
10156 	/*
10157 	 * According to SAM-3, even if a device only supports a single
10158 	 * level of LUN addressing, it should still set the HISUP bit:
10159 	 *
10160 	 * 4.9.1 Logical unit numbers overview
10161 	 *
10162 	 * All logical unit number formats described in this standard are
10163 	 * hierarchical in structure even when only a single level in that
10164 	 * hierarchy is used. The HISUP bit shall be set to one in the
10165 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10166 	 * format described in this standard is used.  Non-hierarchical
10167 	 * formats are outside the scope of this standard.
10168 	 *
10169 	 * Therefore we set the HiSup bit here.
10170 	 *
10171 	 * The response format is 2, per SPC-3.
10172 	 */
10173 	inq_ptr->response_format = SID_HiSup | 2;
10174 
10175 	inq_ptr->additional_length = data_len -
10176 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10177 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10178 			 inq_ptr->additional_length));
10179 
10180 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10181 	if (port_type == CTL_PORT_SCSI)
10182 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10183 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10184 	inq_ptr->flags = SID_CmdQue;
10185 	if (port_type == CTL_PORT_SCSI)
10186 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10187 
10188 	/*
10189 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10190 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10191 	 * name and 4 bytes for the revision.
10192 	 */
10193 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10194 	    "vendor", NULL)) == NULL) {
10195 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10196 	} else {
10197 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10198 		strncpy(inq_ptr->vendor, val,
10199 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10200 	}
10201 	if (lun == NULL) {
10202 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10203 		    sizeof(inq_ptr->product));
10204 	} else if ((val = dnvlist_get_string(lun->be_lun->options, "product",
10205 	    NULL)) == NULL) {
10206 		switch (lun->be_lun->lun_type) {
10207 		case T_DIRECT:
10208 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10209 			    sizeof(inq_ptr->product));
10210 			break;
10211 		case T_PROCESSOR:
10212 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10213 			    sizeof(inq_ptr->product));
10214 			break;
10215 		case T_CDROM:
10216 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10217 			    sizeof(inq_ptr->product));
10218 			break;
10219 		default:
10220 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10221 			    sizeof(inq_ptr->product));
10222 			break;
10223 		}
10224 	} else {
10225 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10226 		strncpy(inq_ptr->product, val,
10227 		    min(sizeof(inq_ptr->product), strlen(val)));
10228 	}
10229 
10230 	/*
10231 	 * XXX make this a macro somewhere so it automatically gets
10232 	 * incremented when we make changes.
10233 	 */
10234 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10235 	    "revision", NULL)) == NULL) {
10236 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10237 	} else {
10238 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10239 		strncpy(inq_ptr->revision, val,
10240 		    min(sizeof(inq_ptr->revision), strlen(val)));
10241 	}
10242 
10243 	/*
10244 	 * For parallel SCSI, we support double transition and single
10245 	 * transition clocking.  We also support QAS (Quick Arbitration
10246 	 * and Selection) and Information Unit transfers on both the
10247 	 * control and array devices.
10248 	 */
10249 	if (port_type == CTL_PORT_SCSI)
10250 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10251 				    SID_SPI_IUS;
10252 
10253 	/* SAM-6 (no version claimed) */
10254 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10255 	/* SPC-5 (no version claimed) */
10256 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10257 	if (port_type == CTL_PORT_FC) {
10258 		/* FCP-2 ANSI INCITS.350:2003 */
10259 		scsi_ulto2b(0x0917, inq_ptr->version3);
10260 	} else if (port_type == CTL_PORT_SCSI) {
10261 		/* SPI-4 ANSI INCITS.362:200x */
10262 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10263 	} else if (port_type == CTL_PORT_ISCSI) {
10264 		/* iSCSI (no version claimed) */
10265 		scsi_ulto2b(0x0960, inq_ptr->version3);
10266 	} else if (port_type == CTL_PORT_SAS) {
10267 		/* SAS (no version claimed) */
10268 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10269 	} else if (port_type == CTL_PORT_UMASS) {
10270 		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10271 		scsi_ulto2b(0x1730, inq_ptr->version3);
10272 	}
10273 
10274 	if (lun == NULL) {
10275 		/* SBC-4 (no version claimed) */
10276 		scsi_ulto2b(0x0600, inq_ptr->version4);
10277 	} else {
10278 		switch (lun->be_lun->lun_type) {
10279 		case T_DIRECT:
10280 			/* SBC-4 (no version claimed) */
10281 			scsi_ulto2b(0x0600, inq_ptr->version4);
10282 			break;
10283 		case T_PROCESSOR:
10284 			break;
10285 		case T_CDROM:
10286 			/* MMC-6 (no version claimed) */
10287 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10288 			break;
10289 		default:
10290 			break;
10291 		}
10292 	}
10293 
10294 	ctl_set_success(ctsio);
10295 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10296 	ctsio->be_move_done = ctl_config_move_done;
10297 	ctl_datamove((union ctl_io *)ctsio);
10298 	return (CTL_RETVAL_COMPLETE);
10299 }
10300 
10301 int
10302 ctl_inquiry(struct ctl_scsiio *ctsio)
10303 {
10304 	struct scsi_inquiry *cdb;
10305 	int retval;
10306 
10307 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10308 
10309 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10310 	if (cdb->byte2 & SI_EVPD)
10311 		retval = ctl_inquiry_evpd(ctsio);
10312 	else if (cdb->page_code == 0)
10313 		retval = ctl_inquiry_std(ctsio);
10314 	else {
10315 		ctl_set_invalid_field(ctsio,
10316 				      /*sks_valid*/ 1,
10317 				      /*command*/ 1,
10318 				      /*field*/ 2,
10319 				      /*bit_valid*/ 0,
10320 				      /*bit*/ 0);
10321 		ctl_done((union ctl_io *)ctsio);
10322 		return (CTL_RETVAL_COMPLETE);
10323 	}
10324 
10325 	return (retval);
10326 }
10327 
10328 int
10329 ctl_get_config(struct ctl_scsiio *ctsio)
10330 {
10331 	struct ctl_lun *lun = CTL_LUN(ctsio);
10332 	struct scsi_get_config_header *hdr;
10333 	struct scsi_get_config_feature *feature;
10334 	struct scsi_get_config *cdb;
10335 	uint32_t alloc_len, data_len;
10336 	int rt, starting;
10337 
10338 	cdb = (struct scsi_get_config *)ctsio->cdb;
10339 	rt = (cdb->rt & SGC_RT_MASK);
10340 	starting = scsi_2btoul(cdb->starting_feature);
10341 	alloc_len = scsi_2btoul(cdb->length);
10342 
10343 	data_len = sizeof(struct scsi_get_config_header) +
10344 	    sizeof(struct scsi_get_config_feature) + 8 +
10345 	    sizeof(struct scsi_get_config_feature) + 8 +
10346 	    sizeof(struct scsi_get_config_feature) + 4 +
10347 	    sizeof(struct scsi_get_config_feature) + 4 +
10348 	    sizeof(struct scsi_get_config_feature) + 8 +
10349 	    sizeof(struct scsi_get_config_feature) +
10350 	    sizeof(struct scsi_get_config_feature) + 4 +
10351 	    sizeof(struct scsi_get_config_feature) + 4 +
10352 	    sizeof(struct scsi_get_config_feature) + 4 +
10353 	    sizeof(struct scsi_get_config_feature) + 4 +
10354 	    sizeof(struct scsi_get_config_feature) + 4 +
10355 	    sizeof(struct scsi_get_config_feature) + 4;
10356 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10357 	ctsio->kern_sg_entries = 0;
10358 	ctsio->kern_rel_offset = 0;
10359 
10360 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10361 	if (lun->flags & CTL_LUN_NO_MEDIA)
10362 		scsi_ulto2b(0x0000, hdr->current_profile);
10363 	else
10364 		scsi_ulto2b(0x0010, hdr->current_profile);
10365 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10366 
10367 	if (starting > 0x003b)
10368 		goto done;
10369 	if (starting > 0x003a)
10370 		goto f3b;
10371 	if (starting > 0x002b)
10372 		goto f3a;
10373 	if (starting > 0x002a)
10374 		goto f2b;
10375 	if (starting > 0x001f)
10376 		goto f2a;
10377 	if (starting > 0x001e)
10378 		goto f1f;
10379 	if (starting > 0x001d)
10380 		goto f1e;
10381 	if (starting > 0x0010)
10382 		goto f1d;
10383 	if (starting > 0x0003)
10384 		goto f10;
10385 	if (starting > 0x0002)
10386 		goto f3;
10387 	if (starting > 0x0001)
10388 		goto f2;
10389 	if (starting > 0x0000)
10390 		goto f1;
10391 
10392 	/* Profile List */
10393 	scsi_ulto2b(0x0000, feature->feature_code);
10394 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10395 	feature->add_length = 8;
10396 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10397 	feature->feature_data[2] = 0x00;
10398 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10399 	feature->feature_data[6] = 0x01;
10400 	feature = (struct scsi_get_config_feature *)
10401 	    &feature->feature_data[feature->add_length];
10402 
10403 f1:	/* Core */
10404 	scsi_ulto2b(0x0001, feature->feature_code);
10405 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10406 	feature->add_length = 8;
10407 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10408 	feature->feature_data[4] = 0x03;
10409 	feature = (struct scsi_get_config_feature *)
10410 	    &feature->feature_data[feature->add_length];
10411 
10412 f2:	/* Morphing */
10413 	scsi_ulto2b(0x0002, feature->feature_code);
10414 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10415 	feature->add_length = 4;
10416 	feature->feature_data[0] = 0x02;
10417 	feature = (struct scsi_get_config_feature *)
10418 	    &feature->feature_data[feature->add_length];
10419 
10420 f3:	/* Removable Medium */
10421 	scsi_ulto2b(0x0003, feature->feature_code);
10422 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10423 	feature->add_length = 4;
10424 	feature->feature_data[0] = 0x39;
10425 	feature = (struct scsi_get_config_feature *)
10426 	    &feature->feature_data[feature->add_length];
10427 
10428 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10429 		goto done;
10430 
10431 f10:	/* Random Read */
10432 	scsi_ulto2b(0x0010, feature->feature_code);
10433 	feature->flags = 0x00;
10434 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10435 		feature->flags |= SGC_F_CURRENT;
10436 	feature->add_length = 8;
10437 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10438 	scsi_ulto2b(1, &feature->feature_data[4]);
10439 	feature->feature_data[6] = 0x00;
10440 	feature = (struct scsi_get_config_feature *)
10441 	    &feature->feature_data[feature->add_length];
10442 
10443 f1d:	/* Multi-Read */
10444 	scsi_ulto2b(0x001D, feature->feature_code);
10445 	feature->flags = 0x00;
10446 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10447 		feature->flags |= SGC_F_CURRENT;
10448 	feature->add_length = 0;
10449 	feature = (struct scsi_get_config_feature *)
10450 	    &feature->feature_data[feature->add_length];
10451 
10452 f1e:	/* CD Read */
10453 	scsi_ulto2b(0x001E, feature->feature_code);
10454 	feature->flags = 0x00;
10455 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10456 		feature->flags |= SGC_F_CURRENT;
10457 	feature->add_length = 4;
10458 	feature->feature_data[0] = 0x00;
10459 	feature = (struct scsi_get_config_feature *)
10460 	    &feature->feature_data[feature->add_length];
10461 
10462 f1f:	/* DVD Read */
10463 	scsi_ulto2b(0x001F, feature->feature_code);
10464 	feature->flags = 0x08;
10465 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10466 		feature->flags |= SGC_F_CURRENT;
10467 	feature->add_length = 4;
10468 	feature->feature_data[0] = 0x01;
10469 	feature->feature_data[2] = 0x03;
10470 	feature = (struct scsi_get_config_feature *)
10471 	    &feature->feature_data[feature->add_length];
10472 
10473 f2a:	/* DVD+RW */
10474 	scsi_ulto2b(0x002A, feature->feature_code);
10475 	feature->flags = 0x04;
10476 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10477 		feature->flags |= SGC_F_CURRENT;
10478 	feature->add_length = 4;
10479 	feature->feature_data[0] = 0x00;
10480 	feature->feature_data[1] = 0x00;
10481 	feature = (struct scsi_get_config_feature *)
10482 	    &feature->feature_data[feature->add_length];
10483 
10484 f2b:	/* DVD+R */
10485 	scsi_ulto2b(0x002B, feature->feature_code);
10486 	feature->flags = 0x00;
10487 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10488 		feature->flags |= SGC_F_CURRENT;
10489 	feature->add_length = 4;
10490 	feature->feature_data[0] = 0x00;
10491 	feature = (struct scsi_get_config_feature *)
10492 	    &feature->feature_data[feature->add_length];
10493 
10494 f3a:	/* DVD+RW Dual Layer */
10495 	scsi_ulto2b(0x003A, feature->feature_code);
10496 	feature->flags = 0x00;
10497 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10498 		feature->flags |= SGC_F_CURRENT;
10499 	feature->add_length = 4;
10500 	feature->feature_data[0] = 0x00;
10501 	feature->feature_data[1] = 0x00;
10502 	feature = (struct scsi_get_config_feature *)
10503 	    &feature->feature_data[feature->add_length];
10504 
10505 f3b:	/* DVD+R Dual Layer */
10506 	scsi_ulto2b(0x003B, feature->feature_code);
10507 	feature->flags = 0x00;
10508 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10509 		feature->flags |= SGC_F_CURRENT;
10510 	feature->add_length = 4;
10511 	feature->feature_data[0] = 0x00;
10512 	feature = (struct scsi_get_config_feature *)
10513 	    &feature->feature_data[feature->add_length];
10514 
10515 done:
10516 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10517 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10518 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10519 		if (scsi_2btoul(feature->feature_code) == starting)
10520 			feature = (struct scsi_get_config_feature *)
10521 			    &feature->feature_data[feature->add_length];
10522 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10523 	}
10524 	scsi_ulto4b(data_len - 4, hdr->data_length);
10525 	ctsio->kern_data_len = min(data_len, alloc_len);
10526 	ctsio->kern_total_len = ctsio->kern_data_len;
10527 
10528 	ctl_set_success(ctsio);
10529 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10530 	ctsio->be_move_done = ctl_config_move_done;
10531 	ctl_datamove((union ctl_io *)ctsio);
10532 	return (CTL_RETVAL_COMPLETE);
10533 }
10534 
10535 int
10536 ctl_get_event_status(struct ctl_scsiio *ctsio)
10537 {
10538 	struct scsi_get_event_status_header *hdr;
10539 	struct scsi_get_event_status *cdb;
10540 	uint32_t alloc_len, data_len;
10541 
10542 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10543 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10544 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10545 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10546 		ctl_done((union ctl_io *)ctsio);
10547 		return (CTL_RETVAL_COMPLETE);
10548 	}
10549 	alloc_len = scsi_2btoul(cdb->length);
10550 
10551 	data_len = sizeof(struct scsi_get_event_status_header);
10552 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10553 	ctsio->kern_sg_entries = 0;
10554 	ctsio->kern_rel_offset = 0;
10555 	ctsio->kern_data_len = min(data_len, alloc_len);
10556 	ctsio->kern_total_len = ctsio->kern_data_len;
10557 
10558 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10559 	scsi_ulto2b(0, hdr->descr_length);
10560 	hdr->nea_class = SGESN_NEA;
10561 	hdr->supported_class = 0;
10562 
10563 	ctl_set_success(ctsio);
10564 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10565 	ctsio->be_move_done = ctl_config_move_done;
10566 	ctl_datamove((union ctl_io *)ctsio);
10567 	return (CTL_RETVAL_COMPLETE);
10568 }
10569 
10570 int
10571 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10572 {
10573 	struct scsi_mechanism_status_header *hdr;
10574 	struct scsi_mechanism_status *cdb;
10575 	uint32_t alloc_len, data_len;
10576 
10577 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10578 	alloc_len = scsi_2btoul(cdb->length);
10579 
10580 	data_len = sizeof(struct scsi_mechanism_status_header);
10581 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10582 	ctsio->kern_sg_entries = 0;
10583 	ctsio->kern_rel_offset = 0;
10584 	ctsio->kern_data_len = min(data_len, alloc_len);
10585 	ctsio->kern_total_len = ctsio->kern_data_len;
10586 
10587 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10588 	hdr->state1 = 0x00;
10589 	hdr->state2 = 0xe0;
10590 	scsi_ulto3b(0, hdr->lba);
10591 	hdr->slots_num = 0;
10592 	scsi_ulto2b(0, hdr->slots_length);
10593 
10594 	ctl_set_success(ctsio);
10595 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10596 	ctsio->be_move_done = ctl_config_move_done;
10597 	ctl_datamove((union ctl_io *)ctsio);
10598 	return (CTL_RETVAL_COMPLETE);
10599 }
10600 
10601 static void
10602 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10603 {
10604 
10605 	lba += 150;
10606 	buf[0] = 0;
10607 	buf[1] = bin2bcd((lba / 75) / 60);
10608 	buf[2] = bin2bcd((lba / 75) % 60);
10609 	buf[3] = bin2bcd(lba % 75);
10610 }
10611 
10612 int
10613 ctl_read_toc(struct ctl_scsiio *ctsio)
10614 {
10615 	struct ctl_lun *lun = CTL_LUN(ctsio);
10616 	struct scsi_read_toc_hdr *hdr;
10617 	struct scsi_read_toc_type01_descr *descr;
10618 	struct scsi_read_toc *cdb;
10619 	uint32_t alloc_len, data_len;
10620 	int format, msf;
10621 
10622 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10623 	msf = (cdb->byte2 & CD_MSF) != 0;
10624 	format = cdb->format;
10625 	alloc_len = scsi_2btoul(cdb->data_len);
10626 
10627 	data_len = sizeof(struct scsi_read_toc_hdr);
10628 	if (format == 0)
10629 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10630 	else
10631 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10632 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10633 	ctsio->kern_sg_entries = 0;
10634 	ctsio->kern_rel_offset = 0;
10635 	ctsio->kern_data_len = min(data_len, alloc_len);
10636 	ctsio->kern_total_len = ctsio->kern_data_len;
10637 
10638 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10639 	if (format == 0) {
10640 		scsi_ulto2b(0x12, hdr->data_length);
10641 		hdr->first = 1;
10642 		hdr->last = 1;
10643 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10644 		descr->addr_ctl = 0x14;
10645 		descr->track_number = 1;
10646 		if (msf)
10647 			ctl_ultomsf(0, descr->track_start);
10648 		else
10649 			scsi_ulto4b(0, descr->track_start);
10650 		descr++;
10651 		descr->addr_ctl = 0x14;
10652 		descr->track_number = 0xaa;
10653 		if (msf)
10654 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10655 		else
10656 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10657 	} else {
10658 		scsi_ulto2b(0x0a, hdr->data_length);
10659 		hdr->first = 1;
10660 		hdr->last = 1;
10661 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10662 		descr->addr_ctl = 0x14;
10663 		descr->track_number = 1;
10664 		if (msf)
10665 			ctl_ultomsf(0, descr->track_start);
10666 		else
10667 			scsi_ulto4b(0, descr->track_start);
10668 	}
10669 
10670 	ctl_set_success(ctsio);
10671 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10672 	ctsio->be_move_done = ctl_config_move_done;
10673 	ctl_datamove((union ctl_io *)ctsio);
10674 	return (CTL_RETVAL_COMPLETE);
10675 }
10676 
10677 /*
10678  * For known CDB types, parse the LBA and length.
10679  */
10680 static int
10681 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10682 {
10683 
10684 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10685 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10686 
10687 	switch (io->scsiio.cdb[0]) {
10688 	case COMPARE_AND_WRITE: {
10689 		struct scsi_compare_and_write *cdb;
10690 
10691 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10692 
10693 		*lba = scsi_8btou64(cdb->addr);
10694 		*len = cdb->length;
10695 		break;
10696 	}
10697 	case READ_6:
10698 	case WRITE_6: {
10699 		struct scsi_rw_6 *cdb;
10700 
10701 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10702 
10703 		*lba = scsi_3btoul(cdb->addr);
10704 		/* only 5 bits are valid in the most significant address byte */
10705 		*lba &= 0x1fffff;
10706 		*len = cdb->length;
10707 		break;
10708 	}
10709 	case READ_10:
10710 	case WRITE_10: {
10711 		struct scsi_rw_10 *cdb;
10712 
10713 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10714 
10715 		*lba = scsi_4btoul(cdb->addr);
10716 		*len = scsi_2btoul(cdb->length);
10717 		break;
10718 	}
10719 	case WRITE_VERIFY_10: {
10720 		struct scsi_write_verify_10 *cdb;
10721 
10722 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10723 
10724 		*lba = scsi_4btoul(cdb->addr);
10725 		*len = scsi_2btoul(cdb->length);
10726 		break;
10727 	}
10728 	case READ_12:
10729 	case WRITE_12: {
10730 		struct scsi_rw_12 *cdb;
10731 
10732 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10733 
10734 		*lba = scsi_4btoul(cdb->addr);
10735 		*len = scsi_4btoul(cdb->length);
10736 		break;
10737 	}
10738 	case WRITE_VERIFY_12: {
10739 		struct scsi_write_verify_12 *cdb;
10740 
10741 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10742 
10743 		*lba = scsi_4btoul(cdb->addr);
10744 		*len = scsi_4btoul(cdb->length);
10745 		break;
10746 	}
10747 	case READ_16:
10748 	case WRITE_16: {
10749 		struct scsi_rw_16 *cdb;
10750 
10751 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10752 
10753 		*lba = scsi_8btou64(cdb->addr);
10754 		*len = scsi_4btoul(cdb->length);
10755 		break;
10756 	}
10757 	case WRITE_ATOMIC_16: {
10758 		struct scsi_write_atomic_16 *cdb;
10759 
10760 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10761 
10762 		*lba = scsi_8btou64(cdb->addr);
10763 		*len = scsi_2btoul(cdb->length);
10764 		break;
10765 	}
10766 	case WRITE_VERIFY_16: {
10767 		struct scsi_write_verify_16 *cdb;
10768 
10769 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10770 
10771 		*lba = scsi_8btou64(cdb->addr);
10772 		*len = scsi_4btoul(cdb->length);
10773 		break;
10774 	}
10775 	case WRITE_SAME_10: {
10776 		struct scsi_write_same_10 *cdb;
10777 
10778 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10779 
10780 		*lba = scsi_4btoul(cdb->addr);
10781 		*len = scsi_2btoul(cdb->length);
10782 		break;
10783 	}
10784 	case WRITE_SAME_16: {
10785 		struct scsi_write_same_16 *cdb;
10786 
10787 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10788 
10789 		*lba = scsi_8btou64(cdb->addr);
10790 		*len = scsi_4btoul(cdb->length);
10791 		break;
10792 	}
10793 	case VERIFY_10: {
10794 		struct scsi_verify_10 *cdb;
10795 
10796 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10797 
10798 		*lba = scsi_4btoul(cdb->addr);
10799 		*len = scsi_2btoul(cdb->length);
10800 		break;
10801 	}
10802 	case VERIFY_12: {
10803 		struct scsi_verify_12 *cdb;
10804 
10805 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10806 
10807 		*lba = scsi_4btoul(cdb->addr);
10808 		*len = scsi_4btoul(cdb->length);
10809 		break;
10810 	}
10811 	case VERIFY_16: {
10812 		struct scsi_verify_16 *cdb;
10813 
10814 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10815 
10816 		*lba = scsi_8btou64(cdb->addr);
10817 		*len = scsi_4btoul(cdb->length);
10818 		break;
10819 	}
10820 	case UNMAP: {
10821 		*lba = 0;
10822 		*len = UINT64_MAX;
10823 		break;
10824 	}
10825 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10826 		struct scsi_get_lba_status *cdb;
10827 
10828 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10829 		*lba = scsi_8btou64(cdb->addr);
10830 		*len = UINT32_MAX;
10831 		break;
10832 	}
10833 	default:
10834 		return (1);
10835 		break; /* NOTREACHED */
10836 	}
10837 
10838 	return (0);
10839 }
10840 
10841 static ctl_action
10842 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10843     bool seq)
10844 {
10845 	uint64_t endlba1, endlba2;
10846 
10847 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10848 	endlba2 = lba2 + len2 - 1;
10849 
10850 	if ((endlba1 < lba2) || (endlba2 < lba1))
10851 		return (CTL_ACTION_PASS);
10852 	else
10853 		return (CTL_ACTION_BLOCK);
10854 }
10855 
10856 static int
10857 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10858 {
10859 	struct ctl_ptr_len_flags *ptrlen;
10860 	struct scsi_unmap_desc *buf, *end, *range;
10861 	uint64_t lba;
10862 	uint32_t len;
10863 
10864 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10865 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10866 
10867 	/* If not UNMAP -- go other way. */
10868 	if (io->scsiio.cdb[0] != UNMAP)
10869 		return (CTL_ACTION_ERROR);
10870 
10871 	/* If UNMAP without data -- block and wait for data. */
10872 	ptrlen = (struct ctl_ptr_len_flags *)
10873 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10874 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10875 	    ptrlen->ptr == NULL)
10876 		return (CTL_ACTION_BLOCK);
10877 
10878 	/* UNMAP with data -- check for collision. */
10879 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10880 	end = buf + ptrlen->len / sizeof(*buf);
10881 	for (range = buf; range < end; range++) {
10882 		lba = scsi_8btou64(range->lba);
10883 		len = scsi_4btoul(range->length);
10884 		if ((lba < lba2 + len2) && (lba + len > lba2))
10885 			return (CTL_ACTION_BLOCK);
10886 	}
10887 	return (CTL_ACTION_PASS);
10888 }
10889 
10890 static ctl_action
10891 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10892 {
10893 	uint64_t lba1, lba2;
10894 	uint64_t len1, len2;
10895 	int retval;
10896 
10897 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10898 		return (CTL_ACTION_ERROR);
10899 
10900 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10901 	if (retval != CTL_ACTION_ERROR)
10902 		return (retval);
10903 
10904 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10905 		return (CTL_ACTION_ERROR);
10906 
10907 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10908 		seq = FALSE;
10909 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10910 }
10911 
10912 static ctl_action
10913 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10914 {
10915 	uint64_t lba1, lba2;
10916 	uint64_t len1, len2;
10917 
10918 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10919 		return (CTL_ACTION_PASS);
10920 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10921 		return (CTL_ACTION_ERROR);
10922 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10923 		return (CTL_ACTION_ERROR);
10924 
10925 	if (lba1 + len1 == lba2)
10926 		return (CTL_ACTION_BLOCK);
10927 	return (CTL_ACTION_PASS);
10928 }
10929 
10930 static ctl_action
10931 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10932     union ctl_io *ooa_io)
10933 {
10934 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10935 	const ctl_serialize_action *serialize_row;
10936 
10937 	/*
10938 	 * Aborted commands are not going to be executed and may even
10939 	 * not report completion, so we don't care about their order.
10940 	 * Let them complete ASAP to clean the OOA queue.
10941 	 */
10942 	if (pending_io->io_hdr.flags & CTL_FLAG_ABORT)
10943 		return (CTL_ACTION_SKIP);
10944 
10945 	/*
10946 	 * The initiator attempted multiple untagged commands at the same
10947 	 * time.  Can't do that.
10948 	 */
10949 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10950 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10951 	 && ((pending_io->io_hdr.nexus.targ_port ==
10952 	      ooa_io->io_hdr.nexus.targ_port)
10953 	  && (pending_io->io_hdr.nexus.initid ==
10954 	      ooa_io->io_hdr.nexus.initid))
10955 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10956 	      CTL_FLAG_STATUS_SENT)) == 0))
10957 		return (CTL_ACTION_OVERLAP);
10958 
10959 	/*
10960 	 * The initiator attempted to send multiple tagged commands with
10961 	 * the same ID.  (It's fine if different initiators have the same
10962 	 * tag ID.)
10963 	 *
10964 	 * Even if all of those conditions are true, we don't kill the I/O
10965 	 * if the command ahead of us has been aborted.  We won't end up
10966 	 * sending it to the FETD, and it's perfectly legal to resend a
10967 	 * command with the same tag number as long as the previous
10968 	 * instance of this tag number has been aborted somehow.
10969 	 */
10970 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10971 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10972 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10973 	 && ((pending_io->io_hdr.nexus.targ_port ==
10974 	      ooa_io->io_hdr.nexus.targ_port)
10975 	  && (pending_io->io_hdr.nexus.initid ==
10976 	      ooa_io->io_hdr.nexus.initid))
10977 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10978 	      CTL_FLAG_STATUS_SENT)) == 0))
10979 		return (CTL_ACTION_OVERLAP_TAG);
10980 
10981 	/*
10982 	 * If we get a head of queue tag, SAM-3 says that we should
10983 	 * immediately execute it.
10984 	 *
10985 	 * What happens if this command would normally block for some other
10986 	 * reason?  e.g. a request sense with a head of queue tag
10987 	 * immediately after a write.  Normally that would block, but this
10988 	 * will result in its getting executed immediately...
10989 	 *
10990 	 * We currently return "pass" instead of "skip", so we'll end up
10991 	 * going through the rest of the queue to check for overlapped tags.
10992 	 *
10993 	 * XXX KDM check for other types of blockage first??
10994 	 */
10995 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10996 		return (CTL_ACTION_PASS);
10997 
10998 	/*
10999 	 * Ordered tags have to block until all items ahead of them
11000 	 * have completed.  If we get called with an ordered tag, we always
11001 	 * block, if something else is ahead of us in the queue.
11002 	 */
11003 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11004 		return (CTL_ACTION_BLOCK);
11005 
11006 	/*
11007 	 * Simple tags get blocked until all head of queue and ordered tags
11008 	 * ahead of them have completed.  I'm lumping untagged commands in
11009 	 * with simple tags here.  XXX KDM is that the right thing to do?
11010 	 */
11011 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11012 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11013 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11014 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11015 		return (CTL_ACTION_BLOCK);
11016 
11017 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11018 	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11019 	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11020 	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11021 	     pending_io->scsiio.cdb[1], pending_io));
11022 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11023 	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11024 		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11025 	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11026 	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11027 	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11028 	     ooa_io->scsiio.cdb[1], ooa_io));
11029 
11030 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11031 
11032 	switch (serialize_row[pending_entry->seridx]) {
11033 	case CTL_SER_BLOCK:
11034 		return (CTL_ACTION_BLOCK);
11035 	case CTL_SER_EXTENT:
11036 		return (ctl_extent_check(ooa_io, pending_io,
11037 		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11038 	case CTL_SER_EXTENTOPT:
11039 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11040 		    SCP_QUEUE_ALG_UNRESTRICTED)
11041 			return (ctl_extent_check(ooa_io, pending_io,
11042 			    (lun->be_lun &&
11043 			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11044 		return (CTL_ACTION_PASS);
11045 	case CTL_SER_EXTENTSEQ:
11046 		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11047 			return (ctl_extent_check_seq(ooa_io, pending_io));
11048 		return (CTL_ACTION_PASS);
11049 	case CTL_SER_PASS:
11050 		return (CTL_ACTION_PASS);
11051 	case CTL_SER_BLOCKOPT:
11052 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11053 		    SCP_QUEUE_ALG_UNRESTRICTED)
11054 			return (CTL_ACTION_BLOCK);
11055 		return (CTL_ACTION_PASS);
11056 	case CTL_SER_SKIP:
11057 		return (CTL_ACTION_SKIP);
11058 	default:
11059 		panic("%s: Invalid serialization value %d for %d => %d",
11060 		    __func__, serialize_row[pending_entry->seridx],
11061 		    pending_entry->seridx, ooa_entry->seridx);
11062 	}
11063 
11064 	return (CTL_ACTION_ERROR);
11065 }
11066 
11067 /*
11068  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11069  * Assumptions:
11070  * - pending_io is generally either incoming, or on the blocked queue
11071  * - starting I/O is the I/O we want to start the check with.
11072  */
11073 static ctl_action
11074 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11075 	      union ctl_io **starting_io)
11076 {
11077 	union ctl_io *ooa_io;
11078 	ctl_action action;
11079 
11080 	mtx_assert(&lun->lun_lock, MA_OWNED);
11081 
11082 	/*
11083 	 * Run back along the OOA queue, starting with the current
11084 	 * blocked I/O and going through every I/O before it on the
11085 	 * queue.  If starting_io is NULL, we'll just end up returning
11086 	 * CTL_ACTION_PASS.
11087 	 */
11088 	for (ooa_io = *starting_io; ooa_io != NULL;
11089 	     ooa_io = (union ctl_io *)LIST_NEXT(&ooa_io->io_hdr, ooa_links)) {
11090 		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11091 		if (action != CTL_ACTION_PASS) {
11092 			*starting_io = ooa_io;
11093 			return (action);
11094 		}
11095 	}
11096 
11097 	*starting_io = NULL;
11098 	return (CTL_ACTION_PASS);
11099 }
11100 
11101 /*
11102  * Try to unblock the specified I/O.
11103  *
11104  * skip parameter allows explicitly skip present blocker of the I/O,
11105  * starting from the previous one on OOA queue.  It can be used when
11106  * we know for sure that the blocker I/O does no longer count.
11107  */
11108 static void
11109 ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io, bool skip)
11110 {
11111 	struct ctl_softc *softc = lun->ctl_softc;
11112 	union ctl_io *bio, *obio;
11113 	const struct ctl_cmd_entry *entry;
11114 	union ctl_ha_msg msg_info;
11115 	ctl_action action;
11116 
11117 	mtx_assert(&lun->lun_lock, MA_OWNED);
11118 
11119 	if (io->io_hdr.blocker == NULL)
11120 		return;
11121 
11122 	obio = bio = io->io_hdr.blocker;
11123 	if (skip)
11124 		bio = (union ctl_io *)LIST_NEXT(&bio->io_hdr, ooa_links);
11125 	action = ctl_check_ooa(lun, io, &bio);
11126 	if (action == CTL_ACTION_BLOCK) {
11127 		/* Still blocked, but may be by different I/O now. */
11128 		if (bio != obio) {
11129 			TAILQ_REMOVE(&obio->io_hdr.blocked_queue,
11130 			    &io->io_hdr, blocked_links);
11131 			TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue,
11132 			    &io->io_hdr, blocked_links);
11133 			io->io_hdr.blocker = bio;
11134 		}
11135 		return;
11136 	}
11137 
11138 	/* No longer blocked, one way or another. */
11139 	TAILQ_REMOVE(&obio->io_hdr.blocked_queue, &io->io_hdr, blocked_links);
11140 	io->io_hdr.blocker = NULL;
11141 
11142 	switch (action) {
11143 	case CTL_ACTION_OVERLAP:
11144 		ctl_set_overlapped_cmd(&io->scsiio);
11145 		goto error;
11146 	case CTL_ACTION_OVERLAP_TAG:
11147 		ctl_set_overlapped_tag(&io->scsiio,
11148 		    io->scsiio.tag_num & 0xff);
11149 		goto error;
11150 	case CTL_ACTION_PASS:
11151 	case CTL_ACTION_SKIP:
11152 
11153 		/* Serializing commands from the other SC retire there. */
11154 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11155 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11156 			io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11157 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11158 			msg_info.hdr.serializing_sc = io;
11159 			msg_info.hdr.msg_type = CTL_MSG_R2R;
11160 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11161 			    sizeof(msg_info.hdr), M_NOWAIT);
11162 			break;
11163 		}
11164 
11165 		/*
11166 		 * Check this I/O for LUN state changes that may have happened
11167 		 * while this command was blocked. The LUN state may have been
11168 		 * changed by a command ahead of us in the queue.
11169 		 */
11170 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11171 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
11172 			ctl_done(io);
11173 			break;
11174 		}
11175 
11176 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11177 		ctl_enqueue_rtr(io);
11178 		break;
11179 	case CTL_ACTION_ERROR:
11180 	default:
11181 		ctl_set_internal_failure(&io->scsiio,
11182 					 /*sks_valid*/ 0,
11183 					 /*retry_count*/ 0);
11184 
11185 error:
11186 		/* Serializing commands from the other SC are done here. */
11187 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11188 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11189 			ctl_try_unblock_others(lun, io, TRUE);
11190 			LIST_REMOVE(&io->io_hdr, ooa_links);
11191 
11192 			ctl_copy_sense_data_back(io, &msg_info);
11193 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11194 			msg_info.hdr.serializing_sc = NULL;
11195 			msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
11196 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11197 			    sizeof(msg_info.scsi), M_WAITOK);
11198 			ctl_free_io(io);
11199 			break;
11200 		}
11201 
11202 		ctl_done(io);
11203 		break;
11204 	}
11205 }
11206 
11207 /*
11208  * Try to unblock I/Os blocked by the specified I/O.
11209  *
11210  * skip parameter allows explicitly skip the specified I/O as blocker,
11211  * starting from the previous one on the OOA queue.  It can be used when
11212  * we know for sure that the specified I/O does no longer count (done).
11213  * It has to be still on OOA queue though so that we know where to start.
11214  */
11215 static void
11216 ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *bio, bool skip)
11217 {
11218 	union ctl_io *io, *next_io;
11219 
11220 	mtx_assert(&lun->lun_lock, MA_OWNED);
11221 
11222 	for (io = (union ctl_io *)TAILQ_FIRST(&bio->io_hdr.blocked_queue);
11223 	     io != NULL; io = next_io) {
11224 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, blocked_links);
11225 
11226 		KASSERT(io->io_hdr.blocker != NULL,
11227 		    ("I/O %p on blocked list without blocker", io));
11228 		ctl_try_unblock_io(lun, io, skip);
11229 	}
11230 	KASSERT(!skip || TAILQ_EMPTY(&bio->io_hdr.blocked_queue),
11231 	    ("blocked_queue is not empty after skipping %p", bio));
11232 }
11233 
11234 /*
11235  * This routine (with one exception) checks LUN flags that can be set by
11236  * commands ahead of us in the OOA queue.  These flags have to be checked
11237  * when a command initially comes in, and when we pull a command off the
11238  * blocked queue and are preparing to execute it.  The reason we have to
11239  * check these flags for commands on the blocked queue is that the LUN
11240  * state may have been changed by a command ahead of us while we're on the
11241  * blocked queue.
11242  *
11243  * Ordering is somewhat important with these checks, so please pay
11244  * careful attention to the placement of any new checks.
11245  */
11246 static int
11247 ctl_scsiio_lun_check(struct ctl_lun *lun,
11248     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11249 {
11250 	struct ctl_softc *softc = lun->ctl_softc;
11251 	int retval;
11252 	uint32_t residx;
11253 
11254 	retval = 0;
11255 
11256 	mtx_assert(&lun->lun_lock, MA_OWNED);
11257 
11258 	/*
11259 	 * If this shelf is a secondary shelf controller, we may have to
11260 	 * reject some commands disallowed by HA mode and link state.
11261 	 */
11262 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11263 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11264 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11265 			ctl_set_lun_unavail(ctsio);
11266 			retval = 1;
11267 			goto bailout;
11268 		}
11269 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11270 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11271 			ctl_set_lun_transit(ctsio);
11272 			retval = 1;
11273 			goto bailout;
11274 		}
11275 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11276 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11277 			ctl_set_lun_standby(ctsio);
11278 			retval = 1;
11279 			goto bailout;
11280 		}
11281 
11282 		/* The rest of checks are only done on executing side */
11283 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11284 			goto bailout;
11285 	}
11286 
11287 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11288 		if (lun->be_lun &&
11289 		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11290 			ctl_set_hw_write_protected(ctsio);
11291 			retval = 1;
11292 			goto bailout;
11293 		}
11294 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11295 			ctl_set_sense(ctsio, /*current_error*/ 1,
11296 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11297 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11298 			retval = 1;
11299 			goto bailout;
11300 		}
11301 	}
11302 
11303 	/*
11304 	 * Check for a reservation conflict.  If this command isn't allowed
11305 	 * even on reserved LUNs, and if this initiator isn't the one who
11306 	 * reserved us, reject the command with a reservation conflict.
11307 	 */
11308 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11309 	if ((lun->flags & CTL_LUN_RESERVED)
11310 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11311 		if (lun->res_idx != residx) {
11312 			ctl_set_reservation_conflict(ctsio);
11313 			retval = 1;
11314 			goto bailout;
11315 		}
11316 	}
11317 
11318 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11319 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11320 		/* No reservation or command is allowed. */;
11321 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11322 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11323 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11324 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11325 		/* The command is allowed for Write Exclusive resv. */;
11326 	} else {
11327 		/*
11328 		 * if we aren't registered or it's a res holder type
11329 		 * reservation and this isn't the res holder then set a
11330 		 * conflict.
11331 		 */
11332 		if (ctl_get_prkey(lun, residx) == 0 ||
11333 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11334 			ctl_set_reservation_conflict(ctsio);
11335 			retval = 1;
11336 			goto bailout;
11337 		}
11338 	}
11339 
11340 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11341 		if (lun->flags & CTL_LUN_EJECTED)
11342 			ctl_set_lun_ejected(ctsio);
11343 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11344 			if (lun->flags & CTL_LUN_REMOVABLE)
11345 				ctl_set_lun_no_media(ctsio);
11346 			else
11347 				ctl_set_lun_int_reqd(ctsio);
11348 		} else if (lun->flags & CTL_LUN_STOPPED)
11349 			ctl_set_lun_stopped(ctsio);
11350 		else
11351 			goto bailout;
11352 		retval = 1;
11353 		goto bailout;
11354 	}
11355 
11356 bailout:
11357 	return (retval);
11358 }
11359 
11360 static void
11361 ctl_failover_io(union ctl_io *io, int have_lock)
11362 {
11363 	ctl_set_busy(&io->scsiio);
11364 	ctl_done(io);
11365 }
11366 
11367 static void
11368 ctl_failover_lun(union ctl_io *rio)
11369 {
11370 	struct ctl_softc *softc = CTL_SOFTC(rio);
11371 	struct ctl_lun *lun;
11372 	struct ctl_io_hdr *io, *next_io;
11373 	uint32_t targ_lun;
11374 
11375 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11376 	CTL_DEBUG_PRINT(("FAILOVER for lun %u\n", targ_lun));
11377 
11378 	/* Find and lock the LUN. */
11379 	mtx_lock(&softc->ctl_lock);
11380 	if (targ_lun > ctl_max_luns ||
11381 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11382 		mtx_unlock(&softc->ctl_lock);
11383 		return;
11384 	}
11385 	mtx_lock(&lun->lun_lock);
11386 	mtx_unlock(&softc->ctl_lock);
11387 	if (lun->flags & CTL_LUN_DISABLED) {
11388 		mtx_unlock(&lun->lun_lock);
11389 		return;
11390 	}
11391 
11392 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11393 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11394 			/* We are master */
11395 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11396 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11397 					io->flags |= CTL_FLAG_ABORT;
11398 					io->flags |= CTL_FLAG_FAILOVER;
11399 					ctl_try_unblock_io(lun,
11400 					    (union ctl_io *)io, FALSE);
11401 				} else { /* This can be only due to DATAMOVE */
11402 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11403 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11404 					io->flags |= CTL_FLAG_IO_ACTIVE;
11405 					io->port_status = 31340;
11406 					ctl_enqueue_isc((union ctl_io *)io);
11407 				}
11408 			} else
11409 			/* We are slave */
11410 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11411 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11412 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11413 					io->flags |= CTL_FLAG_FAILOVER;
11414 				} else {
11415 					ctl_set_busy(&((union ctl_io *)io)->
11416 					    scsiio);
11417 					ctl_done((union ctl_io *)io);
11418 				}
11419 			}
11420 		}
11421 	} else { /* SERIALIZE modes */
11422 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11423 			/* We are master */
11424 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11425 				if (io->blocker != NULL) {
11426 					TAILQ_REMOVE(&io->blocker->io_hdr.blocked_queue,
11427 					    io, blocked_links);
11428 					io->blocker = NULL;
11429 				}
11430 				ctl_try_unblock_others(lun, (union ctl_io *)io,
11431 				    TRUE);
11432 				LIST_REMOVE(io, ooa_links);
11433 				ctl_free_io((union ctl_io *)io);
11434 			} else
11435 			/* We are slave */
11436 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11437 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11438 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11439 					ctl_set_busy(&((union ctl_io *)io)->
11440 					    scsiio);
11441 					ctl_done((union ctl_io *)io);
11442 				}
11443 			}
11444 		}
11445 	}
11446 	mtx_unlock(&lun->lun_lock);
11447 }
11448 
11449 static void
11450 ctl_scsiio_precheck(struct ctl_scsiio *ctsio)
11451 {
11452 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
11453 	struct ctl_lun *lun;
11454 	const struct ctl_cmd_entry *entry;
11455 	union ctl_io *bio;
11456 	uint32_t initidx, targ_lun;
11457 
11458 	lun = NULL;
11459 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11460 	if (targ_lun < ctl_max_luns)
11461 		lun = softc->ctl_luns[targ_lun];
11462 	if (lun) {
11463 		/*
11464 		 * If the LUN is invalid, pretend that it doesn't exist.
11465 		 * It will go away as soon as all pending I/O has been
11466 		 * completed.
11467 		 */
11468 		mtx_lock(&lun->lun_lock);
11469 		if (lun->flags & CTL_LUN_DISABLED) {
11470 			mtx_unlock(&lun->lun_lock);
11471 			lun = NULL;
11472 		}
11473 	}
11474 	CTL_LUN(ctsio) = lun;
11475 	if (lun) {
11476 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11477 
11478 		/*
11479 		 * Every I/O goes into the OOA queue for a particular LUN,
11480 		 * and stays there until completion.
11481 		 */
11482 #ifdef CTL_TIME_IO
11483 		if (LIST_EMPTY(&lun->ooa_queue))
11484 			lun->idle_time += getsbinuptime() - lun->last_busy;
11485 #endif
11486 		LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11487 	}
11488 
11489 	/* Get command entry and return error if it is unsuppotyed. */
11490 	entry = ctl_validate_command(ctsio);
11491 	if (entry == NULL) {
11492 		if (lun)
11493 			mtx_unlock(&lun->lun_lock);
11494 		return;
11495 	}
11496 
11497 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11498 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11499 
11500 	/*
11501 	 * Check to see whether we can send this command to LUNs that don't
11502 	 * exist.  This should pretty much only be the case for inquiry
11503 	 * and request sense.  Further checks, below, really require having
11504 	 * a LUN, so we can't really check the command anymore.  Just put
11505 	 * it on the rtr queue.
11506 	 */
11507 	if (lun == NULL) {
11508 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11509 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11510 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11511 			return;
11512 		}
11513 
11514 		ctl_set_unsupported_lun(ctsio);
11515 		ctl_done((union ctl_io *)ctsio);
11516 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11517 		return;
11518 	} else {
11519 		/*
11520 		 * Make sure we support this particular command on this LUN.
11521 		 * e.g., we don't support writes to the control LUN.
11522 		 */
11523 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11524 			mtx_unlock(&lun->lun_lock);
11525 			ctl_set_invalid_opcode(ctsio);
11526 			ctl_done((union ctl_io *)ctsio);
11527 			return;
11528 		}
11529 	}
11530 
11531 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11532 
11533 	/*
11534 	 * If we've got a request sense, it'll clear the contingent
11535 	 * allegiance condition.  Otherwise, if we have a CA condition for
11536 	 * this initiator, clear it, because it sent down a command other
11537 	 * than request sense.
11538 	 */
11539 	if (ctsio->cdb[0] != REQUEST_SENSE) {
11540 		struct scsi_sense_data *ps;
11541 
11542 		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11543 		if (ps != NULL)
11544 			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11545 	}
11546 
11547 	/*
11548 	 * If the command has this flag set, it handles its own unit
11549 	 * attention reporting, we shouldn't do anything.  Otherwise we
11550 	 * check for any pending unit attentions, and send them back to the
11551 	 * initiator.  We only do this when a command initially comes in,
11552 	 * not when we pull it off the blocked queue.
11553 	 *
11554 	 * According to SAM-3, section 5.3.2, the order that things get
11555 	 * presented back to the host is basically unit attentions caused
11556 	 * by some sort of reset event, busy status, reservation conflicts
11557 	 * or task set full, and finally any other status.
11558 	 *
11559 	 * One issue here is that some of the unit attentions we report
11560 	 * don't fall into the "reset" category (e.g. "reported luns data
11561 	 * has changed").  So reporting it here, before the reservation
11562 	 * check, may be technically wrong.  I guess the only thing to do
11563 	 * would be to check for and report the reset events here, and then
11564 	 * check for the other unit attention types after we check for a
11565 	 * reservation conflict.
11566 	 *
11567 	 * XXX KDM need to fix this
11568 	 */
11569 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11570 		ctl_ua_type ua_type;
11571 		u_int sense_len = 0;
11572 
11573 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11574 		    &sense_len, SSD_TYPE_NONE);
11575 		if (ua_type != CTL_UA_NONE) {
11576 			mtx_unlock(&lun->lun_lock);
11577 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11578 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11579 			ctsio->sense_len = sense_len;
11580 			ctl_done((union ctl_io *)ctsio);
11581 			return;
11582 		}
11583 	}
11584 
11585 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11586 		mtx_unlock(&lun->lun_lock);
11587 		ctl_done((union ctl_io *)ctsio);
11588 		return;
11589 	}
11590 
11591 	/*
11592 	 * XXX CHD this is where we want to send IO to other side if
11593 	 * this LUN is secondary on this SC. We will need to make a copy
11594 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11595 	 * the copy we send as FROM_OTHER.
11596 	 * We also need to stuff the address of the original IO so we can
11597 	 * find it easily. Something similar will need be done on the other
11598 	 * side so when we are done we can find the copy.
11599 	 */
11600 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11601 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11602 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11603 		union ctl_ha_msg msg_info;
11604 		int isc_retval;
11605 
11606 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11607 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11608 		mtx_unlock(&lun->lun_lock);
11609 
11610 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11611 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11612 		msg_info.hdr.serializing_sc = NULL;
11613 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11614 		msg_info.scsi.tag_num = ctsio->tag_num;
11615 		msg_info.scsi.tag_type = ctsio->tag_type;
11616 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11617 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11618 		msg_info.scsi.priority = ctsio->priority;
11619 
11620 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11621 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11622 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11623 			ctl_set_busy(ctsio);
11624 			ctl_done((union ctl_io *)ctsio);
11625 			return;
11626 		}
11627 		return;
11628 	}
11629 
11630 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
11631 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
11632 	case CTL_ACTION_BLOCK:
11633 		ctsio->io_hdr.blocker = bio;
11634 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
11635 				  blocked_links);
11636 		mtx_unlock(&lun->lun_lock);
11637 		break;
11638 	case CTL_ACTION_PASS:
11639 	case CTL_ACTION_SKIP:
11640 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11641 		mtx_unlock(&lun->lun_lock);
11642 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11643 		break;
11644 	case CTL_ACTION_OVERLAP:
11645 		mtx_unlock(&lun->lun_lock);
11646 		ctl_set_overlapped_cmd(ctsio);
11647 		ctl_done((union ctl_io *)ctsio);
11648 		break;
11649 	case CTL_ACTION_OVERLAP_TAG:
11650 		mtx_unlock(&lun->lun_lock);
11651 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11652 		ctl_done((union ctl_io *)ctsio);
11653 		break;
11654 	case CTL_ACTION_ERROR:
11655 	default:
11656 		mtx_unlock(&lun->lun_lock);
11657 		ctl_set_internal_failure(ctsio,
11658 					 /*sks_valid*/ 0,
11659 					 /*retry_count*/ 0);
11660 		ctl_done((union ctl_io *)ctsio);
11661 		break;
11662 	}
11663 }
11664 
11665 const struct ctl_cmd_entry *
11666 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11667 {
11668 	const struct ctl_cmd_entry *entry;
11669 	int service_action;
11670 
11671 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11672 	if (sa)
11673 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11674 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11675 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11676 		entry = &((const struct ctl_cmd_entry *)
11677 		    entry->execute)[service_action];
11678 	}
11679 	return (entry);
11680 }
11681 
11682 const struct ctl_cmd_entry *
11683 ctl_validate_command(struct ctl_scsiio *ctsio)
11684 {
11685 	const struct ctl_cmd_entry *entry;
11686 	int i, sa;
11687 	uint8_t diff;
11688 
11689 	entry = ctl_get_cmd_entry(ctsio, &sa);
11690 	if (entry->execute == NULL) {
11691 		if (sa)
11692 			ctl_set_invalid_field(ctsio,
11693 					      /*sks_valid*/ 1,
11694 					      /*command*/ 1,
11695 					      /*field*/ 1,
11696 					      /*bit_valid*/ 1,
11697 					      /*bit*/ 4);
11698 		else
11699 			ctl_set_invalid_opcode(ctsio);
11700 		ctl_done((union ctl_io *)ctsio);
11701 		return (NULL);
11702 	}
11703 	KASSERT(entry->length > 0,
11704 	    ("Not defined length for command 0x%02x/0x%02x",
11705 	     ctsio->cdb[0], ctsio->cdb[1]));
11706 	for (i = 1; i < entry->length; i++) {
11707 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11708 		if (diff == 0)
11709 			continue;
11710 		ctl_set_invalid_field(ctsio,
11711 				      /*sks_valid*/ 1,
11712 				      /*command*/ 1,
11713 				      /*field*/ i,
11714 				      /*bit_valid*/ 1,
11715 				      /*bit*/ fls(diff) - 1);
11716 		ctl_done((union ctl_io *)ctsio);
11717 		return (NULL);
11718 	}
11719 	return (entry);
11720 }
11721 
11722 static int
11723 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11724 {
11725 
11726 	switch (lun_type) {
11727 	case T_DIRECT:
11728 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11729 			return (0);
11730 		break;
11731 	case T_PROCESSOR:
11732 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11733 			return (0);
11734 		break;
11735 	case T_CDROM:
11736 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11737 			return (0);
11738 		break;
11739 	default:
11740 		return (0);
11741 	}
11742 	return (1);
11743 }
11744 
11745 static int
11746 ctl_scsiio(struct ctl_scsiio *ctsio)
11747 {
11748 	int retval;
11749 	const struct ctl_cmd_entry *entry;
11750 
11751 	retval = CTL_RETVAL_COMPLETE;
11752 
11753 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11754 
11755 	entry = ctl_get_cmd_entry(ctsio, NULL);
11756 
11757 	/*
11758 	 * If this I/O has been aborted, just send it straight to
11759 	 * ctl_done() without executing it.
11760 	 */
11761 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11762 		ctl_done((union ctl_io *)ctsio);
11763 		goto bailout;
11764 	}
11765 
11766 	/*
11767 	 * All the checks should have been handled by ctl_scsiio_precheck().
11768 	 * We should be clear now to just execute the I/O.
11769 	 */
11770 	retval = entry->execute(ctsio);
11771 
11772 bailout:
11773 	return (retval);
11774 }
11775 
11776 static int
11777 ctl_target_reset(union ctl_io *io)
11778 {
11779 	struct ctl_softc *softc = CTL_SOFTC(io);
11780 	struct ctl_port *port = CTL_PORT(io);
11781 	struct ctl_lun *lun;
11782 	uint32_t initidx;
11783 	ctl_ua_type ua_type;
11784 
11785 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11786 		union ctl_ha_msg msg_info;
11787 
11788 		msg_info.hdr.nexus = io->io_hdr.nexus;
11789 		msg_info.task.task_action = io->taskio.task_action;
11790 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11791 		msg_info.hdr.original_sc = NULL;
11792 		msg_info.hdr.serializing_sc = NULL;
11793 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11794 		    sizeof(msg_info.task), M_WAITOK);
11795 	}
11796 
11797 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11798 	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11799 		ua_type = CTL_UA_TARG_RESET;
11800 	else
11801 		ua_type = CTL_UA_BUS_RESET;
11802 	mtx_lock(&softc->ctl_lock);
11803 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11804 		if (port != NULL &&
11805 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11806 			continue;
11807 		ctl_do_lun_reset(lun, initidx, ua_type);
11808 	}
11809 	mtx_unlock(&softc->ctl_lock);
11810 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11811 	return (0);
11812 }
11813 
11814 /*
11815  * The LUN should always be set.  The I/O is optional, and is used to
11816  * distinguish between I/Os sent by this initiator, and by other
11817  * initiators.  We set unit attention for initiators other than this one.
11818  * SAM-3 is vague on this point.  It does say that a unit attention should
11819  * be established for other initiators when a LUN is reset (see section
11820  * 5.7.3), but it doesn't specifically say that the unit attention should
11821  * be established for this particular initiator when a LUN is reset.  Here
11822  * is the relevant text, from SAM-3 rev 8:
11823  *
11824  * 5.7.2 When a SCSI initiator port aborts its own tasks
11825  *
11826  * When a SCSI initiator port causes its own task(s) to be aborted, no
11827  * notification that the task(s) have been aborted shall be returned to
11828  * the SCSI initiator port other than the completion response for the
11829  * command or task management function action that caused the task(s) to
11830  * be aborted and notification(s) associated with related effects of the
11831  * action (e.g., a reset unit attention condition).
11832  *
11833  * XXX KDM for now, we're setting unit attention for all initiators.
11834  */
11835 static void
11836 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11837 {
11838 	struct ctl_io_hdr *xioh;
11839 	int i;
11840 
11841 	mtx_lock(&lun->lun_lock);
11842 	/* Abort tasks. */
11843 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11844 		xioh->flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11845 		ctl_try_unblock_io(lun, (union ctl_io *)xioh, FALSE);
11846 	}
11847 	/* Clear CA. */
11848 	for (i = 0; i < ctl_max_ports; i++) {
11849 		free(lun->pending_sense[i], M_CTL);
11850 		lun->pending_sense[i] = NULL;
11851 	}
11852 	/* Clear reservation. */
11853 	lun->flags &= ~CTL_LUN_RESERVED;
11854 	/* Clear prevent media removal. */
11855 	if (lun->prevent) {
11856 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11857 			ctl_clear_mask(lun->prevent, i);
11858 		lun->prevent_count = 0;
11859 	}
11860 	/* Clear TPC status */
11861 	ctl_tpc_lun_clear(lun, -1);
11862 	/* Establish UA. */
11863 #if 0
11864 	ctl_est_ua_all(lun, initidx, ua_type);
11865 #else
11866 	ctl_est_ua_all(lun, -1, ua_type);
11867 #endif
11868 	mtx_unlock(&lun->lun_lock);
11869 }
11870 
11871 static int
11872 ctl_lun_reset(union ctl_io *io)
11873 {
11874 	struct ctl_softc *softc = CTL_SOFTC(io);
11875 	struct ctl_lun *lun;
11876 	uint32_t targ_lun, initidx;
11877 
11878 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11879 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11880 	mtx_lock(&softc->ctl_lock);
11881 	if (targ_lun >= ctl_max_luns ||
11882 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11883 		mtx_unlock(&softc->ctl_lock);
11884 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11885 		return (1);
11886 	}
11887 	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11888 	mtx_unlock(&softc->ctl_lock);
11889 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11890 
11891 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11892 		union ctl_ha_msg msg_info;
11893 
11894 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11895 		msg_info.hdr.nexus = io->io_hdr.nexus;
11896 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11897 		msg_info.hdr.original_sc = NULL;
11898 		msg_info.hdr.serializing_sc = NULL;
11899 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11900 		    sizeof(msg_info.task), M_WAITOK);
11901 	}
11902 	return (0);
11903 }
11904 
11905 static void
11906 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11907     int other_sc)
11908 {
11909 	struct ctl_io_hdr *xioh;
11910 
11911 	mtx_assert(&lun->lun_lock, MA_OWNED);
11912 
11913 	/*
11914 	 * Run through the OOA queue and attempt to find the given I/O.
11915 	 * The target port, initiator ID, tag type and tag number have to
11916 	 * match the values that we got from the initiator.  If we have an
11917 	 * untagged command to abort, simply abort the first untagged command
11918 	 * we come to.  We only allow one untagged command at a time of course.
11919 	 */
11920 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11921 		union ctl_io *xio = (union ctl_io *)xioh;
11922 		if ((targ_port == UINT32_MAX ||
11923 		     targ_port == xioh->nexus.targ_port) &&
11924 		    (init_id == UINT32_MAX ||
11925 		     init_id == xioh->nexus.initid)) {
11926 			if (targ_port != xioh->nexus.targ_port ||
11927 			    init_id != xioh->nexus.initid)
11928 				xioh->flags |= CTL_FLAG_ABORT_STATUS;
11929 			xioh->flags |= CTL_FLAG_ABORT;
11930 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11931 				union ctl_ha_msg msg_info;
11932 
11933 				msg_info.hdr.nexus = xioh->nexus;
11934 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11935 				msg_info.task.tag_num = xio->scsiio.tag_num;
11936 				msg_info.task.tag_type = xio->scsiio.tag_type;
11937 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11938 				msg_info.hdr.original_sc = NULL;
11939 				msg_info.hdr.serializing_sc = NULL;
11940 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11941 				    sizeof(msg_info.task), M_NOWAIT);
11942 			}
11943 			ctl_try_unblock_io(lun, xio, FALSE);
11944 		}
11945 	}
11946 }
11947 
11948 static int
11949 ctl_abort_task_set(union ctl_io *io)
11950 {
11951 	struct ctl_softc *softc = CTL_SOFTC(io);
11952 	struct ctl_lun *lun;
11953 	uint32_t targ_lun;
11954 
11955 	/*
11956 	 * Look up the LUN.
11957 	 */
11958 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11959 	mtx_lock(&softc->ctl_lock);
11960 	if (targ_lun >= ctl_max_luns ||
11961 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11962 		mtx_unlock(&softc->ctl_lock);
11963 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11964 		return (1);
11965 	}
11966 
11967 	mtx_lock(&lun->lun_lock);
11968 	mtx_unlock(&softc->ctl_lock);
11969 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11970 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11971 		    io->io_hdr.nexus.initid,
11972 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11973 	} else { /* CTL_TASK_CLEAR_TASK_SET */
11974 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11975 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11976 	}
11977 	mtx_unlock(&lun->lun_lock);
11978 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11979 	return (0);
11980 }
11981 
11982 static void
11983 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
11984     ctl_ua_type ua_type)
11985 {
11986 	struct ctl_lun *lun;
11987 	struct scsi_sense_data *ps;
11988 	uint32_t p, i;
11989 
11990 	p = initidx / CTL_MAX_INIT_PER_PORT;
11991 	i = initidx % CTL_MAX_INIT_PER_PORT;
11992 	mtx_lock(&softc->ctl_lock);
11993 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11994 		mtx_lock(&lun->lun_lock);
11995 		/* Abort tasks. */
11996 		ctl_abort_tasks_lun(lun, p, i, 1);
11997 		/* Clear CA. */
11998 		ps = lun->pending_sense[p];
11999 		if (ps != NULL)
12000 			ps[i].error_code = 0;
12001 		/* Clear reservation. */
12002 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12003 			lun->flags &= ~CTL_LUN_RESERVED;
12004 		/* Clear prevent media removal. */
12005 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
12006 			ctl_clear_mask(lun->prevent, initidx);
12007 			lun->prevent_count--;
12008 		}
12009 		/* Clear TPC status */
12010 		ctl_tpc_lun_clear(lun, initidx);
12011 		/* Establish UA. */
12012 		ctl_est_ua(lun, initidx, ua_type);
12013 		mtx_unlock(&lun->lun_lock);
12014 	}
12015 	mtx_unlock(&softc->ctl_lock);
12016 }
12017 
12018 static int
12019 ctl_i_t_nexus_reset(union ctl_io *io)
12020 {
12021 	struct ctl_softc *softc = CTL_SOFTC(io);
12022 	uint32_t initidx;
12023 
12024 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12025 		union ctl_ha_msg msg_info;
12026 
12027 		msg_info.hdr.nexus = io->io_hdr.nexus;
12028 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12029 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12030 		msg_info.hdr.original_sc = NULL;
12031 		msg_info.hdr.serializing_sc = NULL;
12032 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12033 		    sizeof(msg_info.task), M_WAITOK);
12034 	}
12035 
12036 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12037 	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
12038 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12039 	return (0);
12040 }
12041 
12042 static int
12043 ctl_abort_task(union ctl_io *io)
12044 {
12045 	struct ctl_softc *softc = CTL_SOFTC(io);
12046 	struct ctl_io_hdr *xioh;
12047 	struct ctl_lun *lun;
12048 	uint32_t targ_lun;
12049 
12050 	/*
12051 	 * Look up the LUN.
12052 	 */
12053 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12054 	mtx_lock(&softc->ctl_lock);
12055 	if (targ_lun >= ctl_max_luns ||
12056 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12057 		mtx_unlock(&softc->ctl_lock);
12058 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12059 		return (1);
12060 	}
12061 
12062 	mtx_lock(&lun->lun_lock);
12063 	mtx_unlock(&softc->ctl_lock);
12064 	/*
12065 	 * Run through the OOA queue and attempt to find the given I/O.
12066 	 * The target port, initiator ID, tag type and tag number have to
12067 	 * match the values that we got from the initiator.  If we have an
12068 	 * untagged command to abort, simply abort the first untagged command
12069 	 * we come to.  We only allow one untagged command at a time of course.
12070 	 */
12071 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12072 		union ctl_io *xio = (union ctl_io *)xioh;
12073 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12074 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12075 		 || (xioh->flags & CTL_FLAG_ABORT))
12076 			continue;
12077 
12078 		/*
12079 		 * If the abort says that the task is untagged, the
12080 		 * task in the queue must be untagged.  Otherwise,
12081 		 * we just check to see whether the tag numbers
12082 		 * match.  This is because the QLogic firmware
12083 		 * doesn't pass back the tag type in an abort
12084 		 * request.
12085 		 */
12086 #if 0
12087 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12088 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12089 		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12090 #else
12091 		/*
12092 		 * XXX KDM we've got problems with FC, because it
12093 		 * doesn't send down a tag type with aborts.  So we
12094 		 * can only really go by the tag number...
12095 		 * This may cause problems with parallel SCSI.
12096 		 * Need to figure that out!!
12097 		 */
12098 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12099 #endif
12100 			xioh->flags |= CTL_FLAG_ABORT;
12101 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12102 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12103 				union ctl_ha_msg msg_info;
12104 
12105 				msg_info.hdr.nexus = io->io_hdr.nexus;
12106 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12107 				msg_info.task.tag_num = io->taskio.tag_num;
12108 				msg_info.task.tag_type = io->taskio.tag_type;
12109 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12110 				msg_info.hdr.original_sc = NULL;
12111 				msg_info.hdr.serializing_sc = NULL;
12112 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12113 				    sizeof(msg_info.task), M_NOWAIT);
12114 			}
12115 			ctl_try_unblock_io(lun, xio, FALSE);
12116 		}
12117 	}
12118 	mtx_unlock(&lun->lun_lock);
12119 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12120 	return (0);
12121 }
12122 
12123 static int
12124 ctl_query_task(union ctl_io *io, int task_set)
12125 {
12126 	struct ctl_softc *softc = CTL_SOFTC(io);
12127 	struct ctl_io_hdr *xioh;
12128 	struct ctl_lun *lun;
12129 	int found = 0;
12130 	uint32_t targ_lun;
12131 
12132 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12133 	mtx_lock(&softc->ctl_lock);
12134 	if (targ_lun >= ctl_max_luns ||
12135 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12136 		mtx_unlock(&softc->ctl_lock);
12137 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12138 		return (1);
12139 	}
12140 	mtx_lock(&lun->lun_lock);
12141 	mtx_unlock(&softc->ctl_lock);
12142 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12143 		union ctl_io *xio = (union ctl_io *)xioh;
12144 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12145 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12146 		 || (xioh->flags & CTL_FLAG_ABORT))
12147 			continue;
12148 
12149 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12150 			found = 1;
12151 			break;
12152 		}
12153 	}
12154 	mtx_unlock(&lun->lun_lock);
12155 	if (found)
12156 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12157 	else
12158 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12159 	return (0);
12160 }
12161 
12162 static int
12163 ctl_query_async_event(union ctl_io *io)
12164 {
12165 	struct ctl_softc *softc = CTL_SOFTC(io);
12166 	struct ctl_lun *lun;
12167 	ctl_ua_type ua;
12168 	uint32_t targ_lun, initidx;
12169 
12170 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12171 	mtx_lock(&softc->ctl_lock);
12172 	if (targ_lun >= ctl_max_luns ||
12173 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12174 		mtx_unlock(&softc->ctl_lock);
12175 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12176 		return (1);
12177 	}
12178 	mtx_lock(&lun->lun_lock);
12179 	mtx_unlock(&softc->ctl_lock);
12180 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12181 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12182 	mtx_unlock(&lun->lun_lock);
12183 	if (ua != CTL_UA_NONE)
12184 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12185 	else
12186 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12187 	return (0);
12188 }
12189 
12190 static void
12191 ctl_run_task(union ctl_io *io)
12192 {
12193 	int retval = 1;
12194 
12195 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12196 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12197 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12198 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12199 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12200 	switch (io->taskio.task_action) {
12201 	case CTL_TASK_ABORT_TASK:
12202 		retval = ctl_abort_task(io);
12203 		break;
12204 	case CTL_TASK_ABORT_TASK_SET:
12205 	case CTL_TASK_CLEAR_TASK_SET:
12206 		retval = ctl_abort_task_set(io);
12207 		break;
12208 	case CTL_TASK_CLEAR_ACA:
12209 		break;
12210 	case CTL_TASK_I_T_NEXUS_RESET:
12211 		retval = ctl_i_t_nexus_reset(io);
12212 		break;
12213 	case CTL_TASK_LUN_RESET:
12214 		retval = ctl_lun_reset(io);
12215 		break;
12216 	case CTL_TASK_TARGET_RESET:
12217 	case CTL_TASK_BUS_RESET:
12218 		retval = ctl_target_reset(io);
12219 		break;
12220 	case CTL_TASK_PORT_LOGIN:
12221 		break;
12222 	case CTL_TASK_PORT_LOGOUT:
12223 		break;
12224 	case CTL_TASK_QUERY_TASK:
12225 		retval = ctl_query_task(io, 0);
12226 		break;
12227 	case CTL_TASK_QUERY_TASK_SET:
12228 		retval = ctl_query_task(io, 1);
12229 		break;
12230 	case CTL_TASK_QUERY_ASYNC_EVENT:
12231 		retval = ctl_query_async_event(io);
12232 		break;
12233 	default:
12234 		printf("%s: got unknown task management event %d\n",
12235 		       __func__, io->taskio.task_action);
12236 		break;
12237 	}
12238 	if (retval == 0)
12239 		io->io_hdr.status = CTL_SUCCESS;
12240 	else
12241 		io->io_hdr.status = CTL_ERROR;
12242 	ctl_done(io);
12243 }
12244 
12245 /*
12246  * For HA operation.  Handle commands that come in from the other
12247  * controller.
12248  */
12249 static void
12250 ctl_handle_isc(union ctl_io *io)
12251 {
12252 	struct ctl_softc *softc = CTL_SOFTC(io);
12253 	struct ctl_lun *lun;
12254 	const struct ctl_cmd_entry *entry;
12255 	uint32_t targ_lun;
12256 
12257 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12258 	switch (io->io_hdr.msg_type) {
12259 	case CTL_MSG_SERIALIZE:
12260 		ctl_serialize_other_sc_cmd(&io->scsiio);
12261 		break;
12262 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12263 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12264 		if (targ_lun >= ctl_max_luns ||
12265 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12266 			ctl_done(io);
12267 			break;
12268 		}
12269 		mtx_lock(&lun->lun_lock);
12270 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12271 			mtx_unlock(&lun->lun_lock);
12272 			ctl_done(io);
12273 			break;
12274 		}
12275 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12276 		mtx_unlock(&lun->lun_lock);
12277 		ctl_enqueue_rtr(io);
12278 		break;
12279 	case CTL_MSG_FINISH_IO:
12280 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12281 			ctl_done(io);
12282 			break;
12283 		}
12284 		if (targ_lun >= ctl_max_luns ||
12285 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12286 			ctl_free_io(io);
12287 			break;
12288 		}
12289 		mtx_lock(&lun->lun_lock);
12290 		ctl_try_unblock_others(lun, io, TRUE);
12291 		LIST_REMOVE(&io->io_hdr, ooa_links);
12292 		mtx_unlock(&lun->lun_lock);
12293 		ctl_free_io(io);
12294 		break;
12295 	case CTL_MSG_PERS_ACTION:
12296 		ctl_hndl_per_res_out_on_other_sc(io);
12297 		ctl_free_io(io);
12298 		break;
12299 	case CTL_MSG_BAD_JUJU:
12300 		ctl_done(io);
12301 		break;
12302 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12303 		ctl_datamove_remote(io);
12304 		break;
12305 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12306 		io->scsiio.be_move_done(io);
12307 		break;
12308 	case CTL_MSG_FAILOVER:
12309 		ctl_failover_lun(io);
12310 		ctl_free_io(io);
12311 		break;
12312 	default:
12313 		printf("%s: Invalid message type %d\n",
12314 		       __func__, io->io_hdr.msg_type);
12315 		ctl_free_io(io);
12316 		break;
12317 	}
12318 
12319 }
12320 
12321 /*
12322  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12323  * there is no match.
12324  */
12325 static ctl_lun_error_pattern
12326 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12327 {
12328 	const struct ctl_cmd_entry *entry;
12329 	ctl_lun_error_pattern filtered_pattern, pattern;
12330 
12331 	pattern = desc->error_pattern;
12332 
12333 	/*
12334 	 * XXX KDM we need more data passed into this function to match a
12335 	 * custom pattern, and we actually need to implement custom pattern
12336 	 * matching.
12337 	 */
12338 	if (pattern & CTL_LUN_PAT_CMD)
12339 		return (CTL_LUN_PAT_CMD);
12340 
12341 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12342 		return (CTL_LUN_PAT_ANY);
12343 
12344 	entry = ctl_get_cmd_entry(ctsio, NULL);
12345 
12346 	filtered_pattern = entry->pattern & pattern;
12347 
12348 	/*
12349 	 * If the user requested specific flags in the pattern (e.g.
12350 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12351 	 * flags.
12352 	 *
12353 	 * If the user did not specify any flags, it doesn't matter whether
12354 	 * or not the command supports the flags.
12355 	 */
12356 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12357 	     (pattern & ~CTL_LUN_PAT_MASK))
12358 		return (CTL_LUN_PAT_NONE);
12359 
12360 	/*
12361 	 * If the user asked for a range check, see if the requested LBA
12362 	 * range overlaps with this command's LBA range.
12363 	 */
12364 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12365 		uint64_t lba1;
12366 		uint64_t len1;
12367 		ctl_action action;
12368 		int retval;
12369 
12370 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12371 		if (retval != 0)
12372 			return (CTL_LUN_PAT_NONE);
12373 
12374 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12375 					      desc->lba_range.len, FALSE);
12376 		/*
12377 		 * A "pass" means that the LBA ranges don't overlap, so
12378 		 * this doesn't match the user's range criteria.
12379 		 */
12380 		if (action == CTL_ACTION_PASS)
12381 			return (CTL_LUN_PAT_NONE);
12382 	}
12383 
12384 	return (filtered_pattern);
12385 }
12386 
12387 static void
12388 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12389 {
12390 	struct ctl_error_desc *desc, *desc2;
12391 
12392 	mtx_assert(&lun->lun_lock, MA_OWNED);
12393 
12394 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12395 		ctl_lun_error_pattern pattern;
12396 		/*
12397 		 * Check to see whether this particular command matches
12398 		 * the pattern in the descriptor.
12399 		 */
12400 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12401 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12402 			continue;
12403 
12404 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12405 		case CTL_LUN_INJ_ABORTED:
12406 			ctl_set_aborted(&io->scsiio);
12407 			break;
12408 		case CTL_LUN_INJ_MEDIUM_ERR:
12409 			ctl_set_medium_error(&io->scsiio,
12410 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12411 			     CTL_FLAG_DATA_OUT);
12412 			break;
12413 		case CTL_LUN_INJ_UA:
12414 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12415 			 * OCCURRED */
12416 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12417 			break;
12418 		case CTL_LUN_INJ_CUSTOM:
12419 			/*
12420 			 * We're assuming the user knows what he is doing.
12421 			 * Just copy the sense information without doing
12422 			 * checks.
12423 			 */
12424 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12425 			      MIN(sizeof(desc->custom_sense),
12426 				  sizeof(io->scsiio.sense_data)));
12427 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12428 			io->scsiio.sense_len = SSD_FULL_SIZE;
12429 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12430 			break;
12431 		case CTL_LUN_INJ_NONE:
12432 		default:
12433 			/*
12434 			 * If this is an error injection type we don't know
12435 			 * about, clear the continuous flag (if it is set)
12436 			 * so it will get deleted below.
12437 			 */
12438 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12439 			break;
12440 		}
12441 		/*
12442 		 * By default, each error injection action is a one-shot
12443 		 */
12444 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12445 			continue;
12446 
12447 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12448 
12449 		free(desc, M_CTL);
12450 	}
12451 }
12452 
12453 #ifdef CTL_IO_DELAY
12454 static void
12455 ctl_datamove_timer_wakeup(void *arg)
12456 {
12457 	union ctl_io *io;
12458 
12459 	io = (union ctl_io *)arg;
12460 
12461 	ctl_datamove(io);
12462 }
12463 #endif /* CTL_IO_DELAY */
12464 
12465 void
12466 ctl_datamove(union ctl_io *io)
12467 {
12468 	void (*fe_datamove)(union ctl_io *io);
12469 
12470 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12471 
12472 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12473 
12474 	/* No data transferred yet.  Frontend must update this when done. */
12475 	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12476 
12477 #ifdef CTL_TIME_IO
12478 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12479 		char str[256];
12480 		char path_str[64];
12481 		struct sbuf sb;
12482 
12483 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12484 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12485 
12486 		sbuf_cat(&sb, path_str);
12487 		switch (io->io_hdr.io_type) {
12488 		case CTL_IO_SCSI:
12489 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12490 			sbuf_printf(&sb, "\n");
12491 			sbuf_cat(&sb, path_str);
12492 			sbuf_printf(&sb, "Tag: 0x%04x/%d, Prio: %d\n",
12493 				    io->scsiio.tag_num, io->scsiio.tag_type,
12494 				    io->scsiio.priority);
12495 			break;
12496 		case CTL_IO_TASK:
12497 			sbuf_printf(&sb, "Task Action: %d Tag: 0x%04x/%d\n",
12498 				    io->taskio.task_action,
12499 				    io->taskio.tag_num, io->taskio.tag_type);
12500 			break;
12501 		default:
12502 			panic("%s: Invalid CTL I/O type %d\n",
12503 			    __func__, io->io_hdr.io_type);
12504 		}
12505 		sbuf_cat(&sb, path_str);
12506 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12507 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12508 		sbuf_finish(&sb);
12509 		printf("%s", sbuf_data(&sb));
12510 	}
12511 #endif /* CTL_TIME_IO */
12512 
12513 #ifdef CTL_IO_DELAY
12514 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12515 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12516 	} else {
12517 		struct ctl_lun *lun;
12518 
12519 		lun = CTL_LUN(io);
12520 		if ((lun != NULL)
12521 		 && (lun->delay_info.datamove_delay > 0)) {
12522 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12523 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12524 			callout_reset(&io->io_hdr.delay_callout,
12525 				      lun->delay_info.datamove_delay * hz,
12526 				      ctl_datamove_timer_wakeup, io);
12527 			if (lun->delay_info.datamove_type ==
12528 			    CTL_DELAY_TYPE_ONESHOT)
12529 				lun->delay_info.datamove_delay = 0;
12530 			return;
12531 		}
12532 	}
12533 #endif
12534 
12535 	/*
12536 	 * This command has been aborted.  Set the port status, so we fail
12537 	 * the data move.
12538 	 */
12539 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12540 		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12541 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12542 		       io->io_hdr.nexus.targ_port,
12543 		       io->io_hdr.nexus.targ_lun);
12544 		io->io_hdr.port_status = 31337;
12545 		/*
12546 		 * Note that the backend, in this case, will get the
12547 		 * callback in its context.  In other cases it may get
12548 		 * called in the frontend's interrupt thread context.
12549 		 */
12550 		io->scsiio.be_move_done(io);
12551 		return;
12552 	}
12553 
12554 	/* Don't confuse frontend with zero length data move. */
12555 	if (io->scsiio.kern_data_len == 0) {
12556 		io->scsiio.be_move_done(io);
12557 		return;
12558 	}
12559 
12560 	fe_datamove = CTL_PORT(io)->fe_datamove;
12561 	fe_datamove(io);
12562 }
12563 
12564 static void
12565 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12566 {
12567 	union ctl_ha_msg msg;
12568 #ifdef CTL_TIME_IO
12569 	struct bintime cur_bt;
12570 #endif
12571 
12572 	memset(&msg, 0, sizeof(msg));
12573 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12574 	msg.hdr.original_sc = io;
12575 	msg.hdr.serializing_sc = io->io_hdr.remote_io;
12576 	msg.hdr.nexus = io->io_hdr.nexus;
12577 	msg.hdr.status = io->io_hdr.status;
12578 	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12579 	msg.scsi.tag_num = io->scsiio.tag_num;
12580 	msg.scsi.tag_type = io->scsiio.tag_type;
12581 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12582 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12583 	       io->scsiio.sense_len);
12584 	msg.scsi.sense_len = io->scsiio.sense_len;
12585 	msg.scsi.port_status = io->io_hdr.port_status;
12586 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12587 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12588 		ctl_failover_io(io, /*have_lock*/ have_lock);
12589 		return;
12590 	}
12591 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12592 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12593 	    msg.scsi.sense_len, M_WAITOK);
12594 
12595 #ifdef CTL_TIME_IO
12596 	getbinuptime(&cur_bt);
12597 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12598 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12599 #endif
12600 	io->io_hdr.num_dmas++;
12601 }
12602 
12603 /*
12604  * The DMA to the remote side is done, now we need to tell the other side
12605  * we're done so it can continue with its data movement.
12606  */
12607 static void
12608 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12609 {
12610 	union ctl_io *io;
12611 	uint32_t i;
12612 
12613 	io = rq->context;
12614 
12615 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12616 		printf("%s: ISC DMA write failed with error %d", __func__,
12617 		       rq->ret);
12618 		ctl_set_internal_failure(&io->scsiio,
12619 					 /*sks_valid*/ 1,
12620 					 /*retry_count*/ rq->ret);
12621 	}
12622 
12623 	ctl_dt_req_free(rq);
12624 
12625 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12626 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12627 	free(CTL_RSGL(io), M_CTL);
12628 	CTL_RSGL(io) = NULL;
12629 	CTL_LSGL(io) = NULL;
12630 
12631 	/*
12632 	 * The data is in local and remote memory, so now we need to send
12633 	 * status (good or back) back to the other side.
12634 	 */
12635 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12636 }
12637 
12638 /*
12639  * We've moved the data from the host/controller into local memory.  Now we
12640  * need to push it over to the remote controller's memory.
12641  */
12642 static int
12643 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12644 {
12645 	int retval;
12646 
12647 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12648 					  ctl_datamove_remote_write_cb);
12649 	return (retval);
12650 }
12651 
12652 static void
12653 ctl_datamove_remote_write(union ctl_io *io)
12654 {
12655 	int retval;
12656 	void (*fe_datamove)(union ctl_io *io);
12657 
12658 	/*
12659 	 * - Get the data from the host/HBA into local memory.
12660 	 * - DMA memory from the local controller to the remote controller.
12661 	 * - Send status back to the remote controller.
12662 	 */
12663 
12664 	retval = ctl_datamove_remote_sgl_setup(io);
12665 	if (retval != 0)
12666 		return;
12667 
12668 	/* Switch the pointer over so the FETD knows what to do */
12669 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12670 
12671 	/*
12672 	 * Use a custom move done callback, since we need to send completion
12673 	 * back to the other controller, not to the backend on this side.
12674 	 */
12675 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12676 
12677 	fe_datamove = CTL_PORT(io)->fe_datamove;
12678 	fe_datamove(io);
12679 }
12680 
12681 static int
12682 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12683 {
12684 	uint32_t i;
12685 
12686 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12687 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12688 	free(CTL_RSGL(io), M_CTL);
12689 	CTL_RSGL(io) = NULL;
12690 	CTL_LSGL(io) = NULL;
12691 
12692 	/*
12693 	 * The read is done, now we need to send status (good or bad) back
12694 	 * to the other side.
12695 	 */
12696 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12697 
12698 	return (0);
12699 }
12700 
12701 static void
12702 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12703 {
12704 	union ctl_io *io;
12705 	void (*fe_datamove)(union ctl_io *io);
12706 
12707 	io = rq->context;
12708 
12709 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12710 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12711 		       rq->ret);
12712 		ctl_set_internal_failure(&io->scsiio,
12713 					 /*sks_valid*/ 1,
12714 					 /*retry_count*/ rq->ret);
12715 	}
12716 
12717 	ctl_dt_req_free(rq);
12718 
12719 	/* Switch the pointer over so the FETD knows what to do */
12720 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12721 
12722 	/*
12723 	 * Use a custom move done callback, since we need to send completion
12724 	 * back to the other controller, not to the backend on this side.
12725 	 */
12726 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12727 
12728 	/* XXX KDM add checks like the ones in ctl_datamove? */
12729 
12730 	fe_datamove = CTL_PORT(io)->fe_datamove;
12731 	fe_datamove(io);
12732 }
12733 
12734 static int
12735 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12736 {
12737 	struct ctl_sg_entry *local_sglist;
12738 	uint32_t len_to_go;
12739 	int retval;
12740 	int i;
12741 
12742 	retval = 0;
12743 	local_sglist = CTL_LSGL(io);
12744 	len_to_go = io->scsiio.kern_data_len;
12745 
12746 	/*
12747 	 * The difficult thing here is that the size of the various
12748 	 * S/G segments may be different than the size from the
12749 	 * remote controller.  That'll make it harder when DMAing
12750 	 * the data back to the other side.
12751 	 */
12752 	for (i = 0; len_to_go > 0; i++) {
12753 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12754 		local_sglist[i].addr =
12755 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12756 
12757 		len_to_go -= local_sglist[i].len;
12758 	}
12759 	/*
12760 	 * Reset the number of S/G entries accordingly.  The original
12761 	 * number of S/G entries is available in rem_sg_entries.
12762 	 */
12763 	io->scsiio.kern_sg_entries = i;
12764 
12765 	return (retval);
12766 }
12767 
12768 static int
12769 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12770 			 ctl_ha_dt_cb callback)
12771 {
12772 	struct ctl_ha_dt_req *rq;
12773 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12774 	uint32_t local_used, remote_used, total_used;
12775 	int i, j, isc_ret;
12776 
12777 	rq = ctl_dt_req_alloc();
12778 
12779 	/*
12780 	 * If we failed to allocate the request, and if the DMA didn't fail
12781 	 * anyway, set busy status.  This is just a resource allocation
12782 	 * failure.
12783 	 */
12784 	if ((rq == NULL)
12785 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12786 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12787 		ctl_set_busy(&io->scsiio);
12788 
12789 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12790 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12791 		if (rq != NULL)
12792 			ctl_dt_req_free(rq);
12793 
12794 		/*
12795 		 * The data move failed.  We need to return status back
12796 		 * to the other controller.  No point in trying to DMA
12797 		 * data to the remote controller.
12798 		 */
12799 
12800 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12801 
12802 		return (1);
12803 	}
12804 
12805 	local_sglist = CTL_LSGL(io);
12806 	remote_sglist = CTL_RSGL(io);
12807 	local_used = 0;
12808 	remote_used = 0;
12809 	total_used = 0;
12810 
12811 	/*
12812 	 * Pull/push the data over the wire from/to the other controller.
12813 	 * This takes into account the possibility that the local and
12814 	 * remote sglists may not be identical in terms of the size of
12815 	 * the elements and the number of elements.
12816 	 *
12817 	 * One fundamental assumption here is that the length allocated for
12818 	 * both the local and remote sglists is identical.  Otherwise, we've
12819 	 * essentially got a coding error of some sort.
12820 	 */
12821 	isc_ret = CTL_HA_STATUS_SUCCESS;
12822 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12823 		uint32_t cur_len;
12824 		uint8_t *tmp_ptr;
12825 
12826 		rq->command = command;
12827 		rq->context = io;
12828 
12829 		/*
12830 		 * Both pointers should be aligned.  But it is possible
12831 		 * that the allocation length is not.  They should both
12832 		 * also have enough slack left over at the end, though,
12833 		 * to round up to the next 8 byte boundary.
12834 		 */
12835 		cur_len = MIN(local_sglist[i].len - local_used,
12836 			      remote_sglist[j].len - remote_used);
12837 		rq->size = cur_len;
12838 
12839 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12840 		tmp_ptr += local_used;
12841 
12842 #if 0
12843 		/* Use physical addresses when talking to ISC hardware */
12844 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12845 			/* XXX KDM use busdma */
12846 			rq->local = vtophys(tmp_ptr);
12847 		} else
12848 			rq->local = tmp_ptr;
12849 #else
12850 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12851 		    ("HA does not support BUS_ADDR"));
12852 		rq->local = tmp_ptr;
12853 #endif
12854 
12855 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12856 		tmp_ptr += remote_used;
12857 		rq->remote = tmp_ptr;
12858 
12859 		rq->callback = NULL;
12860 
12861 		local_used += cur_len;
12862 		if (local_used >= local_sglist[i].len) {
12863 			i++;
12864 			local_used = 0;
12865 		}
12866 
12867 		remote_used += cur_len;
12868 		if (remote_used >= remote_sglist[j].len) {
12869 			j++;
12870 			remote_used = 0;
12871 		}
12872 		total_used += cur_len;
12873 
12874 		if (total_used >= io->scsiio.kern_data_len)
12875 			rq->callback = callback;
12876 
12877 		isc_ret = ctl_dt_single(rq);
12878 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12879 			break;
12880 	}
12881 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12882 		rq->ret = isc_ret;
12883 		callback(rq);
12884 	}
12885 
12886 	return (0);
12887 }
12888 
12889 static void
12890 ctl_datamove_remote_read(union ctl_io *io)
12891 {
12892 	int retval;
12893 	uint32_t i;
12894 
12895 	/*
12896 	 * This will send an error to the other controller in the case of a
12897 	 * failure.
12898 	 */
12899 	retval = ctl_datamove_remote_sgl_setup(io);
12900 	if (retval != 0)
12901 		return;
12902 
12903 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12904 					  ctl_datamove_remote_read_cb);
12905 	if (retval != 0) {
12906 		/*
12907 		 * Make sure we free memory if there was an error..  The
12908 		 * ctl_datamove_remote_xfer() function will send the
12909 		 * datamove done message, or call the callback with an
12910 		 * error if there is a problem.
12911 		 */
12912 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12913 			free(CTL_LSGLT(io)[i].addr, M_CTL);
12914 		free(CTL_RSGL(io), M_CTL);
12915 		CTL_RSGL(io) = NULL;
12916 		CTL_LSGL(io) = NULL;
12917 	}
12918 }
12919 
12920 /*
12921  * Process a datamove request from the other controller.  This is used for
12922  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12923  * first.  Once that is complete, the data gets DMAed into the remote
12924  * controller's memory.  For reads, we DMA from the remote controller's
12925  * memory into our memory first, and then move it out to the FETD.
12926  */
12927 static void
12928 ctl_datamove_remote(union ctl_io *io)
12929 {
12930 
12931 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12932 
12933 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12934 		ctl_failover_io(io, /*have_lock*/ 0);
12935 		return;
12936 	}
12937 
12938 	/*
12939 	 * Note that we look for an aborted I/O here, but don't do some of
12940 	 * the other checks that ctl_datamove() normally does.
12941 	 * We don't need to run the datamove delay code, since that should
12942 	 * have been done if need be on the other controller.
12943 	 */
12944 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12945 		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12946 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12947 		       io->io_hdr.nexus.targ_port,
12948 		       io->io_hdr.nexus.targ_lun);
12949 		io->io_hdr.port_status = 31338;
12950 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12951 		return;
12952 	}
12953 
12954 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12955 		ctl_datamove_remote_write(io);
12956 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12957 		ctl_datamove_remote_read(io);
12958 	else {
12959 		io->io_hdr.port_status = 31339;
12960 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12961 	}
12962 }
12963 
12964 static void
12965 ctl_process_done(union ctl_io *io)
12966 {
12967 	struct ctl_softc *softc = CTL_SOFTC(io);
12968 	struct ctl_port *port = CTL_PORT(io);
12969 	struct ctl_lun *lun = CTL_LUN(io);
12970 	void (*fe_done)(union ctl_io *io);
12971 	union ctl_ha_msg msg;
12972 
12973 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12974 	fe_done = port->fe_done;
12975 
12976 #ifdef CTL_TIME_IO
12977 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12978 		char str[256];
12979 		char path_str[64];
12980 		struct sbuf sb;
12981 
12982 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12983 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12984 
12985 		sbuf_cat(&sb, path_str);
12986 		switch (io->io_hdr.io_type) {
12987 		case CTL_IO_SCSI:
12988 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12989 			sbuf_printf(&sb, "\n");
12990 			sbuf_cat(&sb, path_str);
12991 			sbuf_printf(&sb, "Tag: 0x%04x/%d, Prio: %d\n",
12992 				    io->scsiio.tag_num, io->scsiio.tag_type,
12993 				    io->scsiio.priority);
12994 			break;
12995 		case CTL_IO_TASK:
12996 			sbuf_printf(&sb, "Task Action: %d Tag: 0x%04x/%d\n",
12997 				    io->taskio.task_action,
12998 				    io->taskio.tag_num, io->taskio.tag_type);
12999 			break;
13000 		default:
13001 			panic("%s: Invalid CTL I/O type %d\n",
13002 			    __func__, io->io_hdr.io_type);
13003 		}
13004 		sbuf_cat(&sb, path_str);
13005 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13006 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13007 		sbuf_finish(&sb);
13008 		printf("%s", sbuf_data(&sb));
13009 	}
13010 #endif /* CTL_TIME_IO */
13011 
13012 	switch (io->io_hdr.io_type) {
13013 	case CTL_IO_SCSI:
13014 		break;
13015 	case CTL_IO_TASK:
13016 		if (ctl_debug & CTL_DEBUG_INFO)
13017 			ctl_io_error_print(io, NULL);
13018 		fe_done(io);
13019 		return;
13020 	default:
13021 		panic("%s: Invalid CTL I/O type %d\n",
13022 		    __func__, io->io_hdr.io_type);
13023 	}
13024 
13025 	if (lun == NULL) {
13026 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13027 				 io->io_hdr.nexus.targ_mapped_lun));
13028 		goto bailout;
13029 	}
13030 
13031 	mtx_lock(&lun->lun_lock);
13032 
13033 	/*
13034 	 * Check to see if we have any informational exception and status
13035 	 * of this command can be modified to report it in form of either
13036 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13037 	 */
13038 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13039 	    io->io_hdr.status == CTL_SUCCESS &&
13040 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13041 		uint8_t mrie = lun->MODE_IE.mrie;
13042 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13043 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13044 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13045 		     mrie == SIEP_MRIE_REC_UNCOND ||
13046 		     mrie == SIEP_MRIE_NO_SENSE) &&
13047 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13048 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13049 			ctl_set_sense(&io->scsiio,
13050 			      /*current_error*/ 1,
13051 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13052 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13053 			      /*asc*/ lun->ie_asc,
13054 			      /*ascq*/ lun->ie_ascq,
13055 			      SSD_ELEM_NONE);
13056 			lun->ie_reported = 1;
13057 		}
13058 	} else if (lun->ie_reported < 0)
13059 		lun->ie_reported = 0;
13060 
13061 	/*
13062 	 * Check to see if we have any errors to inject here.  We only
13063 	 * inject errors for commands that don't already have errors set.
13064 	 */
13065 	if (!STAILQ_EMPTY(&lun->error_list) &&
13066 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13067 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13068 		ctl_inject_error(lun, io);
13069 
13070 	/*
13071 	 * XXX KDM how do we treat commands that aren't completed
13072 	 * successfully?
13073 	 *
13074 	 * XXX KDM should we also track I/O latency?
13075 	 */
13076 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13077 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13078 		int type;
13079 #ifdef CTL_TIME_IO
13080 		struct bintime bt;
13081 
13082 		getbinuptime(&bt);
13083 		bintime_sub(&bt, &io->io_hdr.start_bt);
13084 #endif
13085 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13086 		    CTL_FLAG_DATA_IN)
13087 			type = CTL_STATS_READ;
13088 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13089 		    CTL_FLAG_DATA_OUT)
13090 			type = CTL_STATS_WRITE;
13091 		else
13092 			type = CTL_STATS_NO_IO;
13093 
13094 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
13095 		lun->stats.operations[type] ++;
13096 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13097 #ifdef CTL_TIME_IO
13098 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13099 		bintime_add(&lun->stats.time[type], &bt);
13100 #endif
13101 
13102 		mtx_lock(&port->port_lock);
13103 		port->stats.bytes[type] += io->scsiio.kern_total_len;
13104 		port->stats.operations[type] ++;
13105 		port->stats.dmas[type] += io->io_hdr.num_dmas;
13106 #ifdef CTL_TIME_IO
13107 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13108 		bintime_add(&port->stats.time[type], &bt);
13109 #endif
13110 		mtx_unlock(&port->port_lock);
13111 	}
13112 
13113 	/*
13114 	 * Run through the blocked queue of this I/O and see if anything
13115 	 * can be unblocked, now that this I/O is done and will be removed.
13116 	 * We need to do it before removal to have OOA position to start.
13117 	 */
13118 	ctl_try_unblock_others(lun, io, TRUE);
13119 
13120 	/*
13121 	 * Remove this from the OOA queue.
13122 	 */
13123 	LIST_REMOVE(&io->io_hdr, ooa_links);
13124 #ifdef CTL_TIME_IO
13125 	if (LIST_EMPTY(&lun->ooa_queue))
13126 		lun->last_busy = getsbinuptime();
13127 #endif
13128 
13129 	/*
13130 	 * If the LUN has been invalidated, free it if there is nothing
13131 	 * left on its OOA queue.
13132 	 */
13133 	if ((lun->flags & CTL_LUN_INVALID)
13134 	 && LIST_EMPTY(&lun->ooa_queue)) {
13135 		mtx_unlock(&lun->lun_lock);
13136 		ctl_free_lun(lun);
13137 	} else
13138 		mtx_unlock(&lun->lun_lock);
13139 
13140 bailout:
13141 
13142 	/*
13143 	 * If this command has been aborted, make sure we set the status
13144 	 * properly.  The FETD is responsible for freeing the I/O and doing
13145 	 * whatever it needs to do to clean up its state.
13146 	 */
13147 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13148 		ctl_set_task_aborted(&io->scsiio);
13149 
13150 	/*
13151 	 * If enabled, print command error status.
13152 	 */
13153 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13154 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13155 		ctl_io_error_print(io, NULL);
13156 
13157 	/*
13158 	 * Tell the FETD or the other shelf controller we're done with this
13159 	 * command.  Note that only SCSI commands get to this point.  Task
13160 	 * management commands are completed above.
13161 	 */
13162 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13163 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13164 		memset(&msg, 0, sizeof(msg));
13165 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13166 		msg.hdr.serializing_sc = io->io_hdr.remote_io;
13167 		msg.hdr.nexus = io->io_hdr.nexus;
13168 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13169 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13170 		    M_WAITOK);
13171 	}
13172 
13173 	fe_done(io);
13174 }
13175 
13176 /*
13177  * Front end should call this if it doesn't do autosense.  When the request
13178  * sense comes back in from the initiator, we'll dequeue this and send it.
13179  */
13180 int
13181 ctl_queue_sense(union ctl_io *io)
13182 {
13183 	struct ctl_softc *softc = CTL_SOFTC(io);
13184 	struct ctl_port *port = CTL_PORT(io);
13185 	struct ctl_lun *lun;
13186 	struct scsi_sense_data *ps;
13187 	uint32_t initidx, p, targ_lun;
13188 
13189 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13190 
13191 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13192 
13193 	/*
13194 	 * LUN lookup will likely move to the ctl_work_thread() once we
13195 	 * have our new queueing infrastructure (that doesn't put things on
13196 	 * a per-LUN queue initially).  That is so that we can handle
13197 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13198 	 * can't deal with that right now.
13199 	 * If we don't have a LUN for this, just toss the sense information.
13200 	 */
13201 	mtx_lock(&softc->ctl_lock);
13202 	if (targ_lun >= ctl_max_luns ||
13203 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13204 		mtx_unlock(&softc->ctl_lock);
13205 		goto bailout;
13206 	}
13207 	mtx_lock(&lun->lun_lock);
13208 	mtx_unlock(&softc->ctl_lock);
13209 
13210 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13211 	p = initidx / CTL_MAX_INIT_PER_PORT;
13212 	if (lun->pending_sense[p] == NULL) {
13213 		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13214 		    M_CTL, M_NOWAIT | M_ZERO);
13215 	}
13216 	if ((ps = lun->pending_sense[p]) != NULL) {
13217 		ps += initidx % CTL_MAX_INIT_PER_PORT;
13218 		memset(ps, 0, sizeof(*ps));
13219 		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13220 	}
13221 	mtx_unlock(&lun->lun_lock);
13222 
13223 bailout:
13224 	ctl_free_io(io);
13225 	return (CTL_RETVAL_COMPLETE);
13226 }
13227 
13228 /*
13229  * Primary command inlet from frontend ports.  All SCSI and task I/O
13230  * requests must go through this function.
13231  */
13232 int
13233 ctl_queue(union ctl_io *io)
13234 {
13235 	struct ctl_port *port = CTL_PORT(io);
13236 
13237 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13238 
13239 #ifdef CTL_TIME_IO
13240 	io->io_hdr.start_time = time_uptime;
13241 	getbinuptime(&io->io_hdr.start_bt);
13242 #endif /* CTL_TIME_IO */
13243 
13244 	/* Map FE-specific LUN ID into global one. */
13245 	io->io_hdr.nexus.targ_mapped_lun =
13246 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13247 
13248 	switch (io->io_hdr.io_type) {
13249 	case CTL_IO_SCSI:
13250 	case CTL_IO_TASK:
13251 		if (ctl_debug & CTL_DEBUG_CDB)
13252 			ctl_io_print(io);
13253 		ctl_enqueue_incoming(io);
13254 		break;
13255 	default:
13256 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13257 		return (EINVAL);
13258 	}
13259 
13260 	return (CTL_RETVAL_COMPLETE);
13261 }
13262 
13263 int
13264 ctl_run(union ctl_io *io)
13265 {
13266 	struct ctl_port *port = CTL_PORT(io);
13267 
13268 	CTL_DEBUG_PRINT(("ctl_run 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 		if (ctl_debug & CTL_DEBUG_CDB)
13282 			ctl_io_print(io);
13283 		ctl_scsiio_precheck(&io->scsiio);
13284 		break;
13285 	case CTL_IO_TASK:
13286 		if (ctl_debug & CTL_DEBUG_CDB)
13287 			ctl_io_print(io);
13288 		ctl_run_task(io);
13289 		break;
13290 	default:
13291 		printf("ctl_run: unknown I/O type %d\n", io->io_hdr.io_type);
13292 		return (EINVAL);
13293 	}
13294 
13295 	return (CTL_RETVAL_COMPLETE);
13296 }
13297 
13298 #ifdef CTL_IO_DELAY
13299 static void
13300 ctl_done_timer_wakeup(void *arg)
13301 {
13302 	union ctl_io *io;
13303 
13304 	io = (union ctl_io *)arg;
13305 	ctl_done(io);
13306 }
13307 #endif /* CTL_IO_DELAY */
13308 
13309 void
13310 ctl_serseq_done(union ctl_io *io)
13311 {
13312 	struct ctl_lun *lun = CTL_LUN(io);
13313 
13314 	if (lun->be_lun == NULL ||
13315 	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13316 		return;
13317 	mtx_lock(&lun->lun_lock);
13318 	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13319 	ctl_try_unblock_others(lun, io, FALSE);
13320 	mtx_unlock(&lun->lun_lock);
13321 }
13322 
13323 void
13324 ctl_done(union ctl_io *io)
13325 {
13326 
13327 	/*
13328 	 * Enable this to catch duplicate completion issues.
13329 	 */
13330 #if 0
13331 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13332 		printf("%s: type %d msg %d cdb %x iptl: "
13333 		       "%u:%u:%u tag 0x%04x "
13334 		       "flag %#x status %x\n",
13335 			__func__,
13336 			io->io_hdr.io_type,
13337 			io->io_hdr.msg_type,
13338 			io->scsiio.cdb[0],
13339 			io->io_hdr.nexus.initid,
13340 			io->io_hdr.nexus.targ_port,
13341 			io->io_hdr.nexus.targ_lun,
13342 			(io->io_hdr.io_type ==
13343 			CTL_IO_TASK) ?
13344 			io->taskio.tag_num :
13345 			io->scsiio.tag_num,
13346 		        io->io_hdr.flags,
13347 			io->io_hdr.status);
13348 	} else
13349 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13350 #endif
13351 
13352 	/*
13353 	 * This is an internal copy of an I/O, and should not go through
13354 	 * the normal done processing logic.
13355 	 */
13356 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13357 		return;
13358 
13359 #ifdef CTL_IO_DELAY
13360 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13361 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13362 	} else {
13363 		struct ctl_lun *lun = CTL_LUN(io);
13364 
13365 		if ((lun != NULL)
13366 		 && (lun->delay_info.done_delay > 0)) {
13367 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13368 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13369 			callout_reset(&io->io_hdr.delay_callout,
13370 				      lun->delay_info.done_delay * hz,
13371 				      ctl_done_timer_wakeup, io);
13372 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13373 				lun->delay_info.done_delay = 0;
13374 			return;
13375 		}
13376 	}
13377 #endif /* CTL_IO_DELAY */
13378 
13379 	ctl_enqueue_done(io);
13380 }
13381 
13382 static void
13383 ctl_work_thread(void *arg)
13384 {
13385 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13386 	struct ctl_softc *softc = thr->ctl_softc;
13387 	union ctl_io *io;
13388 	int retval;
13389 
13390 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13391 	thread_lock(curthread);
13392 	sched_prio(curthread, PUSER - 1);
13393 	thread_unlock(curthread);
13394 
13395 	while (!softc->shutdown) {
13396 		/*
13397 		 * We handle the queues in this order:
13398 		 * - ISC
13399 		 * - done queue (to free up resources, unblock other commands)
13400 		 * - incoming queue
13401 		 * - RtR queue
13402 		 *
13403 		 * If those queues are empty, we break out of the loop and
13404 		 * go to sleep.
13405 		 */
13406 		mtx_lock(&thr->queue_lock);
13407 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13408 		if (io != NULL) {
13409 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13410 			mtx_unlock(&thr->queue_lock);
13411 			ctl_handle_isc(io);
13412 			continue;
13413 		}
13414 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13415 		if (io != NULL) {
13416 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13417 			/* clear any blocked commands, call fe_done */
13418 			mtx_unlock(&thr->queue_lock);
13419 			ctl_process_done(io);
13420 			continue;
13421 		}
13422 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13423 		if (io != NULL) {
13424 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13425 			mtx_unlock(&thr->queue_lock);
13426 			if (io->io_hdr.io_type == CTL_IO_TASK)
13427 				ctl_run_task(io);
13428 			else
13429 				ctl_scsiio_precheck(&io->scsiio);
13430 			continue;
13431 		}
13432 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13433 		if (io != NULL) {
13434 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13435 			mtx_unlock(&thr->queue_lock);
13436 			retval = ctl_scsiio(&io->scsiio);
13437 			if (retval != CTL_RETVAL_COMPLETE)
13438 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13439 			continue;
13440 		}
13441 
13442 		/* Sleep until we have something to do. */
13443 		mtx_sleep(thr, &thr->queue_lock, PDROP, "-", 0);
13444 	}
13445 	thr->thread = NULL;
13446 	kthread_exit();
13447 }
13448 
13449 static void
13450 ctl_thresh_thread(void *arg)
13451 {
13452 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13453 	struct ctl_lun *lun;
13454 	struct ctl_logical_block_provisioning_page *page;
13455 	const char *attr;
13456 	union ctl_ha_msg msg;
13457 	uint64_t thres, val;
13458 	int i, e, set;
13459 
13460 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13461 	thread_lock(curthread);
13462 	sched_prio(curthread, PUSER - 1);
13463 	thread_unlock(curthread);
13464 
13465 	while (!softc->shutdown) {
13466 		mtx_lock(&softc->ctl_lock);
13467 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13468 			if ((lun->flags & CTL_LUN_DISABLED) ||
13469 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13470 			    lun->backend->lun_attr == NULL)
13471 				continue;
13472 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13473 			    softc->ha_mode == CTL_HA_MODE_XFER)
13474 				continue;
13475 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13476 				continue;
13477 			e = 0;
13478 			page = &lun->MODE_LBP;
13479 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13480 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13481 					continue;
13482 				thres = scsi_4btoul(page->descr[i].count);
13483 				thres <<= CTL_LBP_EXPONENT;
13484 				switch (page->descr[i].resource) {
13485 				case 0x01:
13486 					attr = "blocksavail";
13487 					break;
13488 				case 0x02:
13489 					attr = "blocksused";
13490 					break;
13491 				case 0xf1:
13492 					attr = "poolblocksavail";
13493 					break;
13494 				case 0xf2:
13495 					attr = "poolblocksused";
13496 					break;
13497 				default:
13498 					continue;
13499 				}
13500 				mtx_unlock(&softc->ctl_lock); // XXX
13501 				val = lun->backend->lun_attr(lun->be_lun, attr);
13502 				mtx_lock(&softc->ctl_lock);
13503 				if (val == UINT64_MAX)
13504 					continue;
13505 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13506 				    == SLBPPD_ARMING_INC)
13507 					e = (val >= thres);
13508 				else
13509 					e = (val <= thres);
13510 				if (e)
13511 					break;
13512 			}
13513 			mtx_lock(&lun->lun_lock);
13514 			if (e) {
13515 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13516 				    (uint8_t *)page, lun->ua_tpt_info);
13517 				if (lun->lasttpt == 0 ||
13518 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13519 					lun->lasttpt = time_uptime;
13520 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13521 					set = 1;
13522 				} else
13523 					set = 0;
13524 			} else {
13525 				lun->lasttpt = 0;
13526 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13527 				set = -1;
13528 			}
13529 			mtx_unlock(&lun->lun_lock);
13530 			if (set != 0 &&
13531 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13532 				/* Send msg to other side. */
13533 				bzero(&msg.ua, sizeof(msg.ua));
13534 				msg.hdr.msg_type = CTL_MSG_UA;
13535 				msg.hdr.nexus.initid = -1;
13536 				msg.hdr.nexus.targ_port = -1;
13537 				msg.hdr.nexus.targ_lun = lun->lun;
13538 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13539 				msg.ua.ua_all = 1;
13540 				msg.ua.ua_set = (set > 0);
13541 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13542 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13543 				mtx_unlock(&softc->ctl_lock); // XXX
13544 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13545 				    sizeof(msg.ua), M_WAITOK);
13546 				mtx_lock(&softc->ctl_lock);
13547 			}
13548 		}
13549 		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13550 		    PDROP, "-", CTL_LBP_PERIOD * hz);
13551 	}
13552 	softc->thresh_thread = NULL;
13553 	kthread_exit();
13554 }
13555 
13556 static void
13557 ctl_enqueue_incoming(union ctl_io *io)
13558 {
13559 	struct ctl_softc *softc = CTL_SOFTC(io);
13560 	struct ctl_thread *thr;
13561 	u_int idx;
13562 
13563 	idx = (io->io_hdr.nexus.targ_port * 127 +
13564 	       io->io_hdr.nexus.initid) % worker_threads;
13565 	thr = &softc->threads[idx];
13566 	mtx_lock(&thr->queue_lock);
13567 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13568 	mtx_unlock(&thr->queue_lock);
13569 	wakeup(thr);
13570 }
13571 
13572 static void
13573 ctl_enqueue_rtr(union ctl_io *io)
13574 {
13575 	struct ctl_softc *softc = CTL_SOFTC(io);
13576 	struct ctl_thread *thr;
13577 
13578 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13579 	mtx_lock(&thr->queue_lock);
13580 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13581 	mtx_unlock(&thr->queue_lock);
13582 	wakeup(thr);
13583 }
13584 
13585 static void
13586 ctl_enqueue_done(union ctl_io *io)
13587 {
13588 	struct ctl_softc *softc = CTL_SOFTC(io);
13589 	struct ctl_thread *thr;
13590 
13591 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13592 	mtx_lock(&thr->queue_lock);
13593 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13594 	mtx_unlock(&thr->queue_lock);
13595 	wakeup(thr);
13596 }
13597 
13598 static void
13599 ctl_enqueue_isc(union ctl_io *io)
13600 {
13601 	struct ctl_softc *softc = CTL_SOFTC(io);
13602 	struct ctl_thread *thr;
13603 
13604 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13605 	mtx_lock(&thr->queue_lock);
13606 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13607 	mtx_unlock(&thr->queue_lock);
13608 	wakeup(thr);
13609 }
13610 
13611 /*
13612  *  vim: ts=8
13613  */
13614