xref: /freebsd/sys/cam/ctl/ctl.c (revision 38a52bd3b5cac3da6f7f6eef3dd050e6aa08ebb3)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
5  * Copyright (c) 2012 The FreeBSD Foundation
6  * Copyright (c) 2014-2017 Alexander Motin <mav@FreeBSD.org>
7  * Copyright (c) 2017 Jakub Wojciech Klama <jceel@FreeBSD.org>
8  * Copyright (c) 2018 Marcelo Araujo <araujo@FreeBSD.org>
9  * All rights reserved.
10  *
11  * Portions of this software were developed by Edward Tomasz Napierala
12  * under sponsorship from the FreeBSD Foundation.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions, and the following disclaimer,
19  *    without modification.
20  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
21  *    substantially similar to the "NO WARRANTY" disclaimer below
22  *    ("Disclaimer") and any redistribution must be conditioned upon
23  *    including a substantially similar Disclaimer requirement for further
24  *    binary redistribution.
25  *
26  * NO WARRANTY
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
35  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
36  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGES.
38  *
39  * $Id$
40  */
41 /*
42  * CAM Target Layer, a SCSI device emulation subsystem.
43  *
44  * Author: Ken Merry <ken@FreeBSD.org>
45  */
46 
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/ctype.h>
53 #include <sys/kernel.h>
54 #include <sys/types.h>
55 #include <sys/kthread.h>
56 #include <sys/bio.h>
57 #include <sys/fcntl.h>
58 #include <sys/lock.h>
59 #include <sys/module.h>
60 #include <sys/mutex.h>
61 #include <sys/condvar.h>
62 #include <sys/malloc.h>
63 #include <sys/conf.h>
64 #include <sys/ioccom.h>
65 #include <sys/queue.h>
66 #include <sys/sbuf.h>
67 #include <sys/smp.h>
68 #include <sys/endian.h>
69 #include <sys/proc.h>
70 #include <sys/sched.h>
71 #include <sys/sysctl.h>
72 #include <sys/nv.h>
73 #include <sys/dnv.h>
74 #include <vm/uma.h>
75 
76 #include <cam/cam.h>
77 #include <cam/scsi/scsi_all.h>
78 #include <cam/scsi/scsi_cd.h>
79 #include <cam/scsi/scsi_da.h>
80 #include <cam/ctl/ctl_io.h>
81 #include <cam/ctl/ctl.h>
82 #include <cam/ctl/ctl_frontend.h>
83 #include <cam/ctl/ctl_util.h>
84 #include <cam/ctl/ctl_backend.h>
85 #include <cam/ctl/ctl_ioctl.h>
86 #include <cam/ctl/ctl_ha.h>
87 #include <cam/ctl/ctl_private.h>
88 #include <cam/ctl/ctl_debug.h>
89 #include <cam/ctl/ctl_scsi_all.h>
90 #include <cam/ctl/ctl_error.h>
91 
92 struct ctl_softc *control_softc = NULL;
93 
94 /*
95  * Template mode pages.
96  */
97 
98 /*
99  * Note that these are default values only.  The actual values will be
100  * filled in when the user does a mode sense.
101  */
102 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
103 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
104 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
105 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
106 	/*read_retry_count*/0,
107 	/*correction_span*/0,
108 	/*head_offset_count*/0,
109 	/*data_strobe_offset_cnt*/0,
110 	/*byte8*/SMS_RWER_LBPERE,
111 	/*write_retry_count*/0,
112 	/*reserved2*/0,
113 	/*recovery_time_limit*/{0, 0},
114 };
115 
116 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
117 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
118 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
119 	/*byte3*/SMS_RWER_PER,
120 	/*read_retry_count*/0,
121 	/*correction_span*/0,
122 	/*head_offset_count*/0,
123 	/*data_strobe_offset_cnt*/0,
124 	/*byte8*/SMS_RWER_LBPERE,
125 	/*write_retry_count*/0,
126 	/*reserved2*/0,
127 	/*recovery_time_limit*/{0, 0},
128 };
129 
130 const static struct scsi_format_page format_page_default = {
131 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
132 	/*page_length*/sizeof(struct scsi_format_page) - 2,
133 	/*tracks_per_zone*/ {0, 0},
134 	/*alt_sectors_per_zone*/ {0, 0},
135 	/*alt_tracks_per_zone*/ {0, 0},
136 	/*alt_tracks_per_lun*/ {0, 0},
137 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
138 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
139 	/*bytes_per_sector*/ {0, 0},
140 	/*interleave*/ {0, 0},
141 	/*track_skew*/ {0, 0},
142 	/*cylinder_skew*/ {0, 0},
143 	/*flags*/ SFP_HSEC,
144 	/*reserved*/ {0, 0, 0}
145 };
146 
147 const static struct scsi_format_page format_page_changeable = {
148 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
149 	/*page_length*/sizeof(struct scsi_format_page) - 2,
150 	/*tracks_per_zone*/ {0, 0},
151 	/*alt_sectors_per_zone*/ {0, 0},
152 	/*alt_tracks_per_zone*/ {0, 0},
153 	/*alt_tracks_per_lun*/ {0, 0},
154 	/*sectors_per_track*/ {0, 0},
155 	/*bytes_per_sector*/ {0, 0},
156 	/*interleave*/ {0, 0},
157 	/*track_skew*/ {0, 0},
158 	/*cylinder_skew*/ {0, 0},
159 	/*flags*/ 0,
160 	/*reserved*/ {0, 0, 0}
161 };
162 
163 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
164 	/*page_code*/SMS_RIGID_DISK_PAGE,
165 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
166 	/*cylinders*/ {0, 0, 0},
167 	/*heads*/ CTL_DEFAULT_HEADS,
168 	/*start_write_precomp*/ {0, 0, 0},
169 	/*start_reduced_current*/ {0, 0, 0},
170 	/*step_rate*/ {0, 0},
171 	/*landing_zone_cylinder*/ {0, 0, 0},
172 	/*rpl*/ SRDP_RPL_DISABLED,
173 	/*rotational_offset*/ 0,
174 	/*reserved1*/ 0,
175 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
176 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
177 	/*reserved2*/ {0, 0}
178 };
179 
180 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
181 	/*page_code*/SMS_RIGID_DISK_PAGE,
182 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
183 	/*cylinders*/ {0, 0, 0},
184 	/*heads*/ 0,
185 	/*start_write_precomp*/ {0, 0, 0},
186 	/*start_reduced_current*/ {0, 0, 0},
187 	/*step_rate*/ {0, 0},
188 	/*landing_zone_cylinder*/ {0, 0, 0},
189 	/*rpl*/ 0,
190 	/*rotational_offset*/ 0,
191 	/*reserved1*/ 0,
192 	/*rotation_rate*/ {0, 0},
193 	/*reserved2*/ {0, 0}
194 };
195 
196 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
197 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
198 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
199 	/*byte3*/0,
200 	/*read_retry_count*/0,
201 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
202 	/*recovery_time_limit*/{0, 0},
203 };
204 
205 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
206 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
207 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
208 	/*byte3*/SMS_VER_PER,
209 	/*read_retry_count*/0,
210 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
211 	/*recovery_time_limit*/{0, 0},
212 };
213 
214 const static struct scsi_caching_page caching_page_default = {
215 	/*page_code*/SMS_CACHING_PAGE,
216 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
217 	/*flags1*/ SCP_DISC | SCP_WCE,
218 	/*ret_priority*/ 0,
219 	/*disable_pf_transfer_len*/ {0xff, 0xff},
220 	/*min_prefetch*/ {0, 0},
221 	/*max_prefetch*/ {0xff, 0xff},
222 	/*max_pf_ceiling*/ {0xff, 0xff},
223 	/*flags2*/ 0,
224 	/*cache_segments*/ 0,
225 	/*cache_seg_size*/ {0, 0},
226 	/*reserved*/ 0,
227 	/*non_cache_seg_size*/ {0, 0, 0}
228 };
229 
230 const static struct scsi_caching_page caching_page_changeable = {
231 	/*page_code*/SMS_CACHING_PAGE,
232 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
233 	/*flags1*/ SCP_WCE | SCP_RCD,
234 	/*ret_priority*/ 0,
235 	/*disable_pf_transfer_len*/ {0, 0},
236 	/*min_prefetch*/ {0, 0},
237 	/*max_prefetch*/ {0, 0},
238 	/*max_pf_ceiling*/ {0, 0},
239 	/*flags2*/ 0,
240 	/*cache_segments*/ 0,
241 	/*cache_seg_size*/ {0, 0},
242 	/*reserved*/ 0,
243 	/*non_cache_seg_size*/ {0, 0, 0}
244 };
245 
246 const static struct scsi_control_page control_page_default = {
247 	/*page_code*/SMS_CONTROL_MODE_PAGE,
248 	/*page_length*/sizeof(struct scsi_control_page) - 2,
249 	/*rlec*/0,
250 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
251 	/*eca_and_aen*/0,
252 	/*flags4*/SCP_TAS,
253 	/*aen_holdoff_period*/{0, 0},
254 	/*busy_timeout_period*/{0, 0},
255 	/*extended_selftest_completion_time*/{0, 0}
256 };
257 
258 const static struct scsi_control_page control_page_changeable = {
259 	/*page_code*/SMS_CONTROL_MODE_PAGE,
260 	/*page_length*/sizeof(struct scsi_control_page) - 2,
261 	/*rlec*/SCP_DSENSE,
262 	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
263 	/*eca_and_aen*/SCP_SWP,
264 	/*flags4*/0,
265 	/*aen_holdoff_period*/{0, 0},
266 	/*busy_timeout_period*/{0, 0},
267 	/*extended_selftest_completion_time*/{0, 0}
268 };
269 
270 #define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
271 
272 const static struct scsi_control_ext_page control_ext_page_default = {
273 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
274 	/*subpage_code*/0x01,
275 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
276 	/*flags*/0,
277 	/*prio*/0,
278 	/*max_sense*/0
279 };
280 
281 const static struct scsi_control_ext_page control_ext_page_changeable = {
282 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
283 	/*subpage_code*/0x01,
284 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
285 	/*flags*/0,
286 	/*prio*/0,
287 	/*max_sense*/0xff
288 };
289 
290 const static struct scsi_info_exceptions_page ie_page_default = {
291 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
292 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
293 	/*info_flags*/SIEP_FLAGS_EWASC,
294 	/*mrie*/SIEP_MRIE_NO,
295 	/*interval_timer*/{0, 0, 0, 0},
296 	/*report_count*/{0, 0, 0, 1}
297 };
298 
299 const static struct scsi_info_exceptions_page ie_page_changeable = {
300 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
301 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
302 	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
303 	    SIEP_FLAGS_LOGERR,
304 	/*mrie*/0x0f,
305 	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
306 	/*report_count*/{0xff, 0xff, 0xff, 0xff}
307 };
308 
309 #define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
310 
311 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
312 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
313 	/*subpage_code*/0x02,
314 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
315 	/*flags*/0,
316 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
317 	/*descr*/{}},
318 	{{/*flags*/0,
319 	  /*resource*/0x01,
320 	  /*reserved*/{0, 0},
321 	  /*count*/{0, 0, 0, 0}},
322 	 {/*flags*/0,
323 	  /*resource*/0x02,
324 	  /*reserved*/{0, 0},
325 	  /*count*/{0, 0, 0, 0}},
326 	 {/*flags*/0,
327 	  /*resource*/0xf1,
328 	  /*reserved*/{0, 0},
329 	  /*count*/{0, 0, 0, 0}},
330 	 {/*flags*/0,
331 	  /*resource*/0xf2,
332 	  /*reserved*/{0, 0},
333 	  /*count*/{0, 0, 0, 0}}
334 	}
335 };
336 
337 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
338 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
339 	/*subpage_code*/0x02,
340 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
341 	/*flags*/SLBPP_SITUA,
342 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
343 	/*descr*/{}},
344 	{{/*flags*/0,
345 	  /*resource*/0,
346 	  /*reserved*/{0, 0},
347 	  /*count*/{0, 0, 0, 0}},
348 	 {/*flags*/0,
349 	  /*resource*/0,
350 	  /*reserved*/{0, 0},
351 	  /*count*/{0, 0, 0, 0}},
352 	 {/*flags*/0,
353 	  /*resource*/0,
354 	  /*reserved*/{0, 0},
355 	  /*count*/{0, 0, 0, 0}},
356 	 {/*flags*/0,
357 	  /*resource*/0,
358 	  /*reserved*/{0, 0},
359 	  /*count*/{0, 0, 0, 0}}
360 	}
361 };
362 
363 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
364 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
365 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
366 	/*caps1*/0x3f,
367 	/*caps2*/0x00,
368 	/*caps3*/0xf0,
369 	/*caps4*/0x00,
370 	/*caps5*/0x29,
371 	/*caps6*/0x00,
372 	/*obsolete*/{0, 0},
373 	/*nvol_levels*/{0, 0},
374 	/*buffer_size*/{8, 0},
375 	/*obsolete2*/{0, 0},
376 	/*reserved*/0,
377 	/*digital*/0,
378 	/*obsolete3*/0,
379 	/*copy_management*/0,
380 	/*reserved2*/0,
381 	/*rotation_control*/0,
382 	/*cur_write_speed*/0,
383 	/*num_speed_descr*/0,
384 };
385 
386 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
387 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
388 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
389 	/*caps1*/0,
390 	/*caps2*/0,
391 	/*caps3*/0,
392 	/*caps4*/0,
393 	/*caps5*/0,
394 	/*caps6*/0,
395 	/*obsolete*/{0, 0},
396 	/*nvol_levels*/{0, 0},
397 	/*buffer_size*/{0, 0},
398 	/*obsolete2*/{0, 0},
399 	/*reserved*/0,
400 	/*digital*/0,
401 	/*obsolete3*/0,
402 	/*copy_management*/0,
403 	/*reserved2*/0,
404 	/*rotation_control*/0,
405 	/*cur_write_speed*/0,
406 	/*num_speed_descr*/0,
407 };
408 
409 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
410     "CAM Target Layer");
411 static int worker_threads = -1;
412 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
413     &worker_threads, 1, "Number of worker threads");
414 static int ctl_debug = CTL_DEBUG_NONE;
415 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
416     &ctl_debug, 0, "Enabled debug flags");
417 static int ctl_lun_map_size = 1024;
418 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
419     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
420 #ifdef  CTL_TIME_IO
421 static int ctl_time_io_secs = CTL_TIME_IO_DEFAULT_SECS;
422 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, time_io_secs, CTLFLAG_RWTUN,
423     &ctl_time_io_secs, 0, "Log requests taking more seconds");
424 #endif
425 
426 /*
427  * Maximum number of LUNs we support.  MUST be a power of 2.
428  */
429 #define	CTL_DEFAULT_MAX_LUNS	1024
430 static int ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
431 TUNABLE_INT("kern.cam.ctl.max_luns", &ctl_max_luns);
432 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_luns, CTLFLAG_RDTUN,
433     &ctl_max_luns, CTL_DEFAULT_MAX_LUNS, "Maximum number of LUNs");
434 
435 /*
436  * Maximum number of ports registered at one time.
437  */
438 #define	CTL_DEFAULT_MAX_PORTS		256
439 static int ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
440 TUNABLE_INT("kern.cam.ctl.max_ports", &ctl_max_ports);
441 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_ports, CTLFLAG_RDTUN,
442     &ctl_max_ports, CTL_DEFAULT_MAX_LUNS, "Maximum number of ports");
443 
444 /*
445  * Maximum number of initiators we support.
446  */
447 #define	CTL_MAX_INITIATORS	(CTL_MAX_INIT_PER_PORT * ctl_max_ports)
448 
449 /*
450  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
451  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
452  * SCSI Ports (0x88), Third-party Copy (0x8F), SCSI Feature Sets (0x92),
453  * Block limits (0xB0), Block Device Characteristics (0xB1) and
454  * Logical Block Provisioning (0xB2)
455  */
456 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	11
457 
458 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
459 				  int param);
460 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
461 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
462 static int ctl_init(void);
463 static int ctl_shutdown(void);
464 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
465 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
466 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
467 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
468 			      struct ctl_ooa *ooa_hdr,
469 			      struct ctl_ooa_entry *kern_entries);
470 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
471 		     struct thread *td);
472 static int ctl_enable_lun(struct ctl_lun *lun);
473 static int ctl_disable_lun(struct ctl_lun *lun);
474 static int ctl_free_lun(struct ctl_lun *lun);
475 
476 static int ctl_do_mode_select(union ctl_io *io);
477 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
478 			   uint64_t res_key, uint64_t sa_res_key,
479 			   uint8_t type, uint32_t residx,
480 			   struct ctl_scsiio *ctsio,
481 			   struct scsi_per_res_out *cdb,
482 			   struct scsi_per_res_out_parms* param);
483 static void ctl_pro_preempt_other(struct ctl_lun *lun,
484 				  union ctl_ha_msg *msg);
485 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
486 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
487 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
488 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
489 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
490 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
491 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
492 					 int alloc_len);
493 static int ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len);
494 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
495 					 int alloc_len);
496 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
497 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
498 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
499 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
500 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
501 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
502     bool seq);
503 static ctl_action ctl_seq_check(union ctl_io *io1, union ctl_io *io2);
504 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
505     union ctl_io *pending_io, const uint8_t *serialize_row,
506     union ctl_io *ooa_io);
507 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
508 				union ctl_io **starting_io);
509 static void ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io,
510     bool skip);
511 static void ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *io,
512     bool skip);
513 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
514 				const struct ctl_cmd_entry *entry,
515 				struct ctl_scsiio *ctsio);
516 static void ctl_failover_lun(union ctl_io *io);
517 static void ctl_scsiio_precheck(struct ctl_scsiio *ctsio);
518 static int ctl_scsiio(struct ctl_scsiio *ctsio);
519 
520 static int ctl_target_reset(union ctl_io *io);
521 static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
522 			 ctl_ua_type ua_type);
523 static int ctl_lun_reset(union ctl_io *io);
524 static int ctl_abort_task(union ctl_io *io);
525 static int ctl_abort_task_set(union ctl_io *io);
526 static int ctl_query_task(union ctl_io *io, int task_set);
527 static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
528 			      ctl_ua_type ua_type);
529 static int ctl_i_t_nexus_reset(union ctl_io *io);
530 static int ctl_query_async_event(union ctl_io *io);
531 static void ctl_run_task(union ctl_io *io);
532 #ifdef CTL_IO_DELAY
533 static void ctl_datamove_timer_wakeup(void *arg);
534 static void ctl_done_timer_wakeup(void *arg);
535 #endif /* CTL_IO_DELAY */
536 
537 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
538 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
539 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io, bool samethr);
540 static void ctl_datamove_remote_write(union ctl_io *io);
541 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io, bool samethr);
542 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
543 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
544 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
545 				    ctl_ha_dt_cb callback);
546 static void ctl_datamove_remote_read(union ctl_io *io);
547 static void ctl_datamove_remote(union ctl_io *io);
548 static void ctl_process_done(union ctl_io *io);
549 static void ctl_thresh_thread(void *arg);
550 static void ctl_work_thread(void *arg);
551 static void ctl_enqueue_incoming(union ctl_io *io);
552 static void ctl_enqueue_rtr(union ctl_io *io);
553 static void ctl_enqueue_done(union ctl_io *io);
554 static void ctl_enqueue_isc(union ctl_io *io);
555 static const struct ctl_cmd_entry *
556     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
557 static const struct ctl_cmd_entry *
558     ctl_validate_command(struct ctl_scsiio *ctsio);
559 static int ctl_cmd_applicable(uint8_t lun_type,
560     const struct ctl_cmd_entry *entry);
561 static int ctl_ha_init(void);
562 static int ctl_ha_shutdown(void);
563 
564 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
565 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
566 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
567 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
568 
569 /*
570  * Load the serialization table.  This isn't very pretty, but is probably
571  * the easiest way to do it.
572  */
573 #include "ctl_ser_table.c"
574 
575 /*
576  * We only need to define open, close and ioctl routines for this driver.
577  */
578 static struct cdevsw ctl_cdevsw = {
579 	.d_version =	D_VERSION,
580 	.d_flags =	0,
581 	.d_open =	ctl_open,
582 	.d_close =	ctl_close,
583 	.d_ioctl =	ctl_ioctl,
584 	.d_name =	"ctl",
585 };
586 
587 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
588 
589 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
590 
591 static moduledata_t ctl_moduledata = {
592 	"ctl",
593 	ctl_module_event_handler,
594 	NULL
595 };
596 
597 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
598 MODULE_VERSION(ctl, 1);
599 
600 static struct ctl_frontend ha_frontend =
601 {
602 	.name = "ha",
603 	.init = ctl_ha_init,
604 	.shutdown = ctl_ha_shutdown,
605 };
606 
607 static int
608 ctl_ha_init(void)
609 {
610 	struct ctl_softc *softc = control_softc;
611 
612 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
613 	                    &softc->othersc_pool) != 0)
614 		return (ENOMEM);
615 	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
616 		ctl_pool_free(softc->othersc_pool);
617 		return (EIO);
618 	}
619 	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
620 	    != CTL_HA_STATUS_SUCCESS) {
621 		ctl_ha_msg_destroy(softc);
622 		ctl_pool_free(softc->othersc_pool);
623 		return (EIO);
624 	}
625 	return (0);
626 };
627 
628 static int
629 ctl_ha_shutdown(void)
630 {
631 	struct ctl_softc *softc = control_softc;
632 	struct ctl_port *port;
633 
634 	ctl_ha_msg_shutdown(softc);
635 	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
636 		return (EIO);
637 	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
638 		return (EIO);
639 	ctl_pool_free(softc->othersc_pool);
640 	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
641 		ctl_port_deregister(port);
642 		free(port->port_name, M_CTL);
643 		free(port, M_CTL);
644 	}
645 	return (0);
646 };
647 
648 static void
649 ctl_ha_datamove(union ctl_io *io)
650 {
651 	struct ctl_lun *lun = CTL_LUN(io);
652 	struct ctl_sg_entry *sgl;
653 	union ctl_ha_msg msg;
654 	uint32_t sg_entries_sent;
655 	int do_sg_copy, i, j;
656 
657 	memset(&msg.dt, 0, sizeof(msg.dt));
658 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
659 	msg.hdr.original_sc = io->io_hdr.remote_io;
660 	msg.hdr.serializing_sc = io;
661 	msg.hdr.nexus = io->io_hdr.nexus;
662 	msg.hdr.status = io->io_hdr.status;
663 	msg.dt.flags = io->io_hdr.flags;
664 
665 	/*
666 	 * We convert everything into a S/G list here.  We can't
667 	 * pass by reference, only by value between controllers.
668 	 * So we can't pass a pointer to the S/G list, only as many
669 	 * S/G entries as we can fit in here.  If it's possible for
670 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
671 	 * then we need to break this up into multiple transfers.
672 	 */
673 	if (io->scsiio.kern_sg_entries == 0) {
674 		msg.dt.kern_sg_entries = 1;
675 #if 0
676 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
677 			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
678 		} else {
679 			/* XXX KDM use busdma here! */
680 			msg.dt.sg_list[0].addr =
681 			    (void *)vtophys(io->scsiio.kern_data_ptr);
682 		}
683 #else
684 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
685 		    ("HA does not support BUS_ADDR"));
686 		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
687 #endif
688 		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
689 		do_sg_copy = 0;
690 	} else {
691 		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
692 		do_sg_copy = 1;
693 	}
694 
695 	msg.dt.kern_data_len = io->scsiio.kern_data_len;
696 	msg.dt.kern_total_len = io->scsiio.kern_total_len;
697 	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
698 	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
699 	msg.dt.sg_sequence = 0;
700 
701 	/*
702 	 * Loop until we've sent all of the S/G entries.  On the
703 	 * other end, we'll recompose these S/G entries into one
704 	 * contiguous list before processing.
705 	 */
706 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
707 	    msg.dt.sg_sequence++) {
708 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
709 		    sizeof(msg.dt.sg_list[0])),
710 		    msg.dt.kern_sg_entries - sg_entries_sent);
711 		if (do_sg_copy != 0) {
712 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
713 			for (i = sg_entries_sent, j = 0;
714 			     i < msg.dt.cur_sg_entries; i++, j++) {
715 #if 0
716 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
717 					msg.dt.sg_list[j].addr = sgl[i].addr;
718 				} else {
719 					/* XXX KDM use busdma here! */
720 					msg.dt.sg_list[j].addr =
721 					    (void *)vtophys(sgl[i].addr);
722 				}
723 #else
724 				KASSERT((io->io_hdr.flags &
725 				    CTL_FLAG_BUS_ADDR) == 0,
726 				    ("HA does not support BUS_ADDR"));
727 				msg.dt.sg_list[j].addr = sgl[i].addr;
728 #endif
729 				msg.dt.sg_list[j].len = sgl[i].len;
730 			}
731 		}
732 
733 		sg_entries_sent += msg.dt.cur_sg_entries;
734 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
735 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
736 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
737 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
738 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
739 			io->io_hdr.port_status = 31341;
740 			ctl_datamove_done(io, true);
741 			return;
742 		}
743 		msg.dt.sent_sg_entries = sg_entries_sent;
744 	}
745 
746 	/*
747 	 * Officially handover the request from us to peer.
748 	 * If failover has just happened, then we must return error.
749 	 * If failover happen just after, then it is not our problem.
750 	 */
751 	if (lun)
752 		mtx_lock(&lun->lun_lock);
753 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
754 		if (lun)
755 			mtx_unlock(&lun->lun_lock);
756 		io->io_hdr.port_status = 31342;
757 		ctl_datamove_done(io, true);
758 		return;
759 	}
760 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
761 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
762 	if (lun)
763 		mtx_unlock(&lun->lun_lock);
764 }
765 
766 static void
767 ctl_ha_done(union ctl_io *io)
768 {
769 	union ctl_ha_msg msg;
770 
771 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
772 		memset(&msg, 0, sizeof(msg));
773 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
774 		msg.hdr.original_sc = io->io_hdr.remote_io;
775 		msg.hdr.nexus = io->io_hdr.nexus;
776 		msg.hdr.status = io->io_hdr.status;
777 		msg.scsi.scsi_status = io->scsiio.scsi_status;
778 		msg.scsi.tag_num = io->scsiio.tag_num;
779 		msg.scsi.tag_type = io->scsiio.tag_type;
780 		msg.scsi.sense_len = io->scsiio.sense_len;
781 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
782 		    io->scsiio.sense_len);
783 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
784 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
785 		    msg.scsi.sense_len, M_WAITOK);
786 	}
787 	ctl_free_io(io);
788 }
789 
790 static void
791 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
792 			    union ctl_ha_msg *msg_info)
793 {
794 	struct ctl_scsiio *ctsio;
795 
796 	if (msg_info->hdr.original_sc == NULL) {
797 		printf("%s: original_sc == NULL!\n", __func__);
798 		/* XXX KDM now what? */
799 		return;
800 	}
801 
802 	ctsio = &msg_info->hdr.original_sc->scsiio;
803 	ctsio->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
804 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
805 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
806 	ctsio->io_hdr.status = msg_info->hdr.status;
807 	ctsio->scsi_status = msg_info->scsi.scsi_status;
808 	ctsio->sense_len = msg_info->scsi.sense_len;
809 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
810 	       msg_info->scsi.sense_len);
811 	ctl_enqueue_isc((union ctl_io *)ctsio);
812 }
813 
814 static void
815 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
816 				union ctl_ha_msg *msg_info)
817 {
818 	struct ctl_scsiio *ctsio;
819 
820 	if (msg_info->hdr.serializing_sc == NULL) {
821 		printf("%s: serializing_sc == NULL!\n", __func__);
822 		/* XXX KDM now what? */
823 		return;
824 	}
825 
826 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
827 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
828 	ctl_enqueue_isc((union ctl_io *)ctsio);
829 }
830 
831 void
832 ctl_isc_announce_lun(struct ctl_lun *lun)
833 {
834 	struct ctl_softc *softc = lun->ctl_softc;
835 	union ctl_ha_msg *msg;
836 	struct ctl_ha_msg_lun_pr_key pr_key;
837 	int i, k;
838 
839 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
840 		return;
841 	mtx_lock(&lun->lun_lock);
842 	i = sizeof(msg->lun);
843 	if (lun->lun_devid)
844 		i += lun->lun_devid->len;
845 	i += sizeof(pr_key) * lun->pr_key_count;
846 alloc:
847 	mtx_unlock(&lun->lun_lock);
848 	msg = malloc(i, M_CTL, M_WAITOK);
849 	mtx_lock(&lun->lun_lock);
850 	k = sizeof(msg->lun);
851 	if (lun->lun_devid)
852 		k += lun->lun_devid->len;
853 	k += sizeof(pr_key) * lun->pr_key_count;
854 	if (i < k) {
855 		free(msg, M_CTL);
856 		i = k;
857 		goto alloc;
858 	}
859 	bzero(&msg->lun, sizeof(msg->lun));
860 	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
861 	msg->hdr.nexus.targ_lun = lun->lun;
862 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
863 	msg->lun.flags = lun->flags;
864 	msg->lun.pr_generation = lun->pr_generation;
865 	msg->lun.pr_res_idx = lun->pr_res_idx;
866 	msg->lun.pr_res_type = lun->pr_res_type;
867 	msg->lun.pr_key_count = lun->pr_key_count;
868 	i = 0;
869 	if (lun->lun_devid) {
870 		msg->lun.lun_devid_len = lun->lun_devid->len;
871 		memcpy(&msg->lun.data[i], lun->lun_devid->data,
872 		    msg->lun.lun_devid_len);
873 		i += msg->lun.lun_devid_len;
874 	}
875 	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
876 		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
877 			continue;
878 		pr_key.pr_iid = k;
879 		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
880 		i += sizeof(pr_key);
881 	}
882 	mtx_unlock(&lun->lun_lock);
883 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->lun, sizeof(msg->lun) + i,
884 	    M_WAITOK);
885 	free(msg, M_CTL);
886 
887 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
888 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
889 			ctl_isc_announce_mode(lun, -1,
890 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
891 			    lun->mode_pages.index[i].subpage);
892 		}
893 	}
894 }
895 
896 void
897 ctl_isc_announce_port(struct ctl_port *port)
898 {
899 	struct ctl_softc *softc = port->ctl_softc;
900 	union ctl_ha_msg *msg;
901 	int i;
902 
903 	if (port->targ_port < softc->port_min ||
904 	    port->targ_port >= softc->port_max ||
905 	    softc->ha_link != CTL_HA_LINK_ONLINE)
906 		return;
907 	i = sizeof(msg->port) + strlen(port->port_name) + 1;
908 	if (port->lun_map)
909 		i += port->lun_map_size * sizeof(uint32_t);
910 	if (port->port_devid)
911 		i += port->port_devid->len;
912 	if (port->target_devid)
913 		i += port->target_devid->len;
914 	if (port->init_devid)
915 		i += port->init_devid->len;
916 	msg = malloc(i, M_CTL, M_WAITOK);
917 	bzero(&msg->port, sizeof(msg->port));
918 	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
919 	msg->hdr.nexus.targ_port = port->targ_port;
920 	msg->port.port_type = port->port_type;
921 	msg->port.physical_port = port->physical_port;
922 	msg->port.virtual_port = port->virtual_port;
923 	msg->port.status = port->status;
924 	i = 0;
925 	msg->port.name_len = sprintf(&msg->port.data[i],
926 	    "%d:%s", softc->ha_id, port->port_name) + 1;
927 	i += msg->port.name_len;
928 	if (port->lun_map) {
929 		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
930 		memcpy(&msg->port.data[i], port->lun_map,
931 		    msg->port.lun_map_len);
932 		i += msg->port.lun_map_len;
933 	}
934 	if (port->port_devid) {
935 		msg->port.port_devid_len = port->port_devid->len;
936 		memcpy(&msg->port.data[i], port->port_devid->data,
937 		    msg->port.port_devid_len);
938 		i += msg->port.port_devid_len;
939 	}
940 	if (port->target_devid) {
941 		msg->port.target_devid_len = port->target_devid->len;
942 		memcpy(&msg->port.data[i], port->target_devid->data,
943 		    msg->port.target_devid_len);
944 		i += msg->port.target_devid_len;
945 	}
946 	if (port->init_devid) {
947 		msg->port.init_devid_len = port->init_devid->len;
948 		memcpy(&msg->port.data[i], port->init_devid->data,
949 		    msg->port.init_devid_len);
950 		i += msg->port.init_devid_len;
951 	}
952 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
953 	    M_WAITOK);
954 	free(msg, M_CTL);
955 }
956 
957 void
958 ctl_isc_announce_iid(struct ctl_port *port, int iid)
959 {
960 	struct ctl_softc *softc = port->ctl_softc;
961 	union ctl_ha_msg *msg;
962 	int i, l;
963 
964 	if (port->targ_port < softc->port_min ||
965 	    port->targ_port >= softc->port_max ||
966 	    softc->ha_link != CTL_HA_LINK_ONLINE)
967 		return;
968 	mtx_lock(&softc->ctl_lock);
969 	i = sizeof(msg->iid);
970 	l = 0;
971 	if (port->wwpn_iid[iid].name)
972 		l = strlen(port->wwpn_iid[iid].name) + 1;
973 	i += l;
974 	msg = malloc(i, M_CTL, M_NOWAIT);
975 	if (msg == NULL) {
976 		mtx_unlock(&softc->ctl_lock);
977 		return;
978 	}
979 	bzero(&msg->iid, sizeof(msg->iid));
980 	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
981 	msg->hdr.nexus.targ_port = port->targ_port;
982 	msg->hdr.nexus.initid = iid;
983 	msg->iid.in_use = port->wwpn_iid[iid].in_use;
984 	msg->iid.name_len = l;
985 	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
986 	if (port->wwpn_iid[iid].name)
987 		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
988 	mtx_unlock(&softc->ctl_lock);
989 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
990 	free(msg, M_CTL);
991 }
992 
993 void
994 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
995     uint8_t page, uint8_t subpage)
996 {
997 	struct ctl_softc *softc = lun->ctl_softc;
998 	union ctl_ha_msg *msg;
999 	u_int i, l;
1000 
1001 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
1002 		return;
1003 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1004 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1005 		    page && lun->mode_pages.index[i].subpage == subpage)
1006 			break;
1007 	}
1008 	if (i == CTL_NUM_MODE_PAGES)
1009 		return;
1010 
1011 	/* Don't try to replicate pages not present on this device. */
1012 	if (lun->mode_pages.index[i].page_data == NULL)
1013 		return;
1014 
1015 	l = sizeof(msg->mode) + lun->mode_pages.index[i].page_len;
1016 	msg = malloc(l, M_CTL, M_WAITOK | M_ZERO);
1017 	msg->hdr.msg_type = CTL_MSG_MODE_SYNC;
1018 	msg->hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
1019 	msg->hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
1020 	msg->hdr.nexus.targ_lun = lun->lun;
1021 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
1022 	msg->mode.page_code = page;
1023 	msg->mode.subpage = subpage;
1024 	msg->mode.page_len = lun->mode_pages.index[i].page_len;
1025 	memcpy(msg->mode.data, lun->mode_pages.index[i].page_data,
1026 	    msg->mode.page_len);
1027 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->mode, l, M_WAITOK);
1028 	free(msg, M_CTL);
1029 }
1030 
1031 static void
1032 ctl_isc_ha_link_up(struct ctl_softc *softc)
1033 {
1034 	struct ctl_port *port;
1035 	struct ctl_lun *lun;
1036 	union ctl_ha_msg msg;
1037 	int i;
1038 
1039 	/* Announce this node parameters to peer for validation. */
1040 	msg.login.msg_type = CTL_MSG_LOGIN;
1041 	msg.login.version = CTL_HA_VERSION;
1042 	msg.login.ha_mode = softc->ha_mode;
1043 	msg.login.ha_id = softc->ha_id;
1044 	msg.login.max_luns = ctl_max_luns;
1045 	msg.login.max_ports = ctl_max_ports;
1046 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1047 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1048 	    M_WAITOK);
1049 
1050 	STAILQ_FOREACH(port, &softc->port_list, links) {
1051 		ctl_isc_announce_port(port);
1052 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1053 			if (port->wwpn_iid[i].in_use)
1054 				ctl_isc_announce_iid(port, i);
1055 		}
1056 	}
1057 	STAILQ_FOREACH(lun, &softc->lun_list, links)
1058 		ctl_isc_announce_lun(lun);
1059 }
1060 
1061 static void
1062 ctl_isc_ha_link_down(struct ctl_softc *softc)
1063 {
1064 	struct ctl_port *port;
1065 	struct ctl_lun *lun;
1066 	union ctl_io *io;
1067 	int i;
1068 
1069 	mtx_lock(&softc->ctl_lock);
1070 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1071 		mtx_lock(&lun->lun_lock);
1072 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1073 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1074 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1075 		}
1076 		mtx_unlock(&lun->lun_lock);
1077 
1078 		mtx_unlock(&softc->ctl_lock);
1079 		io = ctl_alloc_io(softc->othersc_pool);
1080 		mtx_lock(&softc->ctl_lock);
1081 		ctl_zero_io(io);
1082 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1083 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1084 		ctl_enqueue_isc(io);
1085 	}
1086 
1087 	STAILQ_FOREACH(port, &softc->port_list, links) {
1088 		if (port->targ_port >= softc->port_min &&
1089 		    port->targ_port < softc->port_max)
1090 			continue;
1091 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1092 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1093 			port->wwpn_iid[i].in_use = 0;
1094 			free(port->wwpn_iid[i].name, M_CTL);
1095 			port->wwpn_iid[i].name = NULL;
1096 		}
1097 	}
1098 	mtx_unlock(&softc->ctl_lock);
1099 }
1100 
1101 static void
1102 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1103 {
1104 	struct ctl_lun *lun;
1105 	uint32_t iid;
1106 
1107 	if (len < sizeof(msg->ua)) {
1108 		printf("%s: Received truncated message %d < %zu\n",
1109 		    __func__, len, sizeof(msg->ua));
1110 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1111 		return;
1112 	}
1113 
1114 	mtx_lock(&softc->ctl_lock);
1115 	if (msg->hdr.nexus.targ_mapped_lun >= ctl_max_luns ||
1116 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1117 		mtx_unlock(&softc->ctl_lock);
1118 		return;
1119 	}
1120 	mtx_lock(&lun->lun_lock);
1121 	mtx_unlock(&softc->ctl_lock);
1122 	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1123 		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1124 	iid = ctl_get_initindex(&msg->hdr.nexus);
1125 	if (msg->ua.ua_all) {
1126 		if (msg->ua.ua_set)
1127 			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1128 		else
1129 			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1130 	} else {
1131 		if (msg->ua.ua_set)
1132 			ctl_est_ua(lun, iid, msg->ua.ua_type);
1133 		else
1134 			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1135 	}
1136 	mtx_unlock(&lun->lun_lock);
1137 }
1138 
1139 static void
1140 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1141 {
1142 	struct ctl_lun *lun;
1143 	struct ctl_ha_msg_lun_pr_key pr_key;
1144 	int i, k;
1145 	ctl_lun_flags oflags;
1146 	uint32_t targ_lun;
1147 
1148 	if (len < offsetof(struct ctl_ha_msg_lun, data[0])) {
1149 		printf("%s: Received truncated message %d < %zu\n",
1150 		    __func__, len, offsetof(struct ctl_ha_msg_lun, data[0]));
1151 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1152 		return;
1153 	}
1154 	i = msg->lun.lun_devid_len + msg->lun.pr_key_count * sizeof(pr_key);
1155 	if (len < offsetof(struct ctl_ha_msg_lun, data[i])) {
1156 		printf("%s: Received truncated message data %d < %zu\n",
1157 		    __func__, len, offsetof(struct ctl_ha_msg_lun, data[i]));
1158 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1159 		return;
1160 	}
1161 
1162 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1163 	mtx_lock(&softc->ctl_lock);
1164 	if (targ_lun >= ctl_max_luns ||
1165 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1166 		mtx_unlock(&softc->ctl_lock);
1167 		return;
1168 	}
1169 	mtx_lock(&lun->lun_lock);
1170 	mtx_unlock(&softc->ctl_lock);
1171 	if (lun->flags & CTL_LUN_DISABLED) {
1172 		mtx_unlock(&lun->lun_lock);
1173 		return;
1174 	}
1175 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1176 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1177 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1178 		mtx_unlock(&lun->lun_lock);
1179 		printf("%s: Received conflicting HA LUN %d\n",
1180 		    __func__, targ_lun);
1181 		return;
1182 	} else {
1183 		/* Record whether peer is primary. */
1184 		oflags = lun->flags;
1185 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1186 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1187 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1188 		else
1189 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1190 		if (oflags != lun->flags)
1191 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1192 
1193 		/* If peer is primary and we are not -- use data */
1194 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1195 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1196 			lun->pr_generation = msg->lun.pr_generation;
1197 			lun->pr_res_idx = msg->lun.pr_res_idx;
1198 			lun->pr_res_type = msg->lun.pr_res_type;
1199 			lun->pr_key_count = msg->lun.pr_key_count;
1200 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1201 				ctl_clr_prkey(lun, k);
1202 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1203 				memcpy(&pr_key, &msg->lun.data[i],
1204 				    sizeof(pr_key));
1205 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1206 				ctl_set_prkey(lun, pr_key.pr_iid,
1207 				    pr_key.pr_key);
1208 				i += sizeof(pr_key);
1209 			}
1210 		}
1211 
1212 		mtx_unlock(&lun->lun_lock);
1213 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1214 		    __func__, targ_lun,
1215 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1216 		    "primary" : "secondary"));
1217 
1218 		/* If we are primary but peer doesn't know -- notify */
1219 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1220 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1221 			ctl_isc_announce_lun(lun);
1222 	}
1223 }
1224 
1225 static void
1226 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1227 {
1228 	struct ctl_port *port;
1229 	struct ctl_lun *lun;
1230 	int i, new;
1231 
1232 	if (len < offsetof(struct ctl_ha_msg_port, data[0])) {
1233 		printf("%s: Received truncated message %d < %zu\n",
1234 		    __func__, len, offsetof(struct ctl_ha_msg_port, data[0]));
1235 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1236 		return;
1237 	}
1238 	i = msg->port.name_len + msg->port.lun_map_len +
1239 	    msg->port.port_devid_len + msg->port.target_devid_len +
1240 	    msg->port.init_devid_len;
1241 	if (len < offsetof(struct ctl_ha_msg_port, data[i])) {
1242 		printf("%s: Received truncated message data %d < %zu\n",
1243 		    __func__, len, offsetof(struct ctl_ha_msg_port, data[i]));
1244 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1245 		return;
1246 	}
1247 
1248 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1249 	if (port == NULL) {
1250 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1251 		    msg->hdr.nexus.targ_port));
1252 		new = 1;
1253 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1254 		port->frontend = &ha_frontend;
1255 		port->targ_port = msg->hdr.nexus.targ_port;
1256 		port->fe_datamove = ctl_ha_datamove;
1257 		port->fe_done = ctl_ha_done;
1258 	} else if (port->frontend == &ha_frontend) {
1259 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1260 		    msg->hdr.nexus.targ_port));
1261 		new = 0;
1262 	} else {
1263 		printf("%s: Received conflicting HA port %d\n",
1264 		    __func__, msg->hdr.nexus.targ_port);
1265 		return;
1266 	}
1267 	port->port_type = msg->port.port_type;
1268 	port->physical_port = msg->port.physical_port;
1269 	port->virtual_port = msg->port.virtual_port;
1270 	port->status = msg->port.status;
1271 	i = 0;
1272 	free(port->port_name, M_CTL);
1273 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1274 	    M_CTL);
1275 	i += msg->port.name_len;
1276 	if (msg->port.lun_map_len != 0) {
1277 		if (port->lun_map == NULL ||
1278 		    port->lun_map_size * sizeof(uint32_t) <
1279 		    msg->port.lun_map_len) {
1280 			port->lun_map_size = 0;
1281 			free(port->lun_map, M_CTL);
1282 			port->lun_map = malloc(msg->port.lun_map_len,
1283 			    M_CTL, M_WAITOK);
1284 		}
1285 		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1286 		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1287 		i += msg->port.lun_map_len;
1288 	} else {
1289 		port->lun_map_size = 0;
1290 		free(port->lun_map, M_CTL);
1291 		port->lun_map = NULL;
1292 	}
1293 	if (msg->port.port_devid_len != 0) {
1294 		if (port->port_devid == NULL ||
1295 		    port->port_devid->len < msg->port.port_devid_len) {
1296 			free(port->port_devid, M_CTL);
1297 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1298 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1299 		}
1300 		memcpy(port->port_devid->data, &msg->port.data[i],
1301 		    msg->port.port_devid_len);
1302 		port->port_devid->len = msg->port.port_devid_len;
1303 		i += msg->port.port_devid_len;
1304 	} else {
1305 		free(port->port_devid, M_CTL);
1306 		port->port_devid = NULL;
1307 	}
1308 	if (msg->port.target_devid_len != 0) {
1309 		if (port->target_devid == NULL ||
1310 		    port->target_devid->len < msg->port.target_devid_len) {
1311 			free(port->target_devid, M_CTL);
1312 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1313 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1314 		}
1315 		memcpy(port->target_devid->data, &msg->port.data[i],
1316 		    msg->port.target_devid_len);
1317 		port->target_devid->len = msg->port.target_devid_len;
1318 		i += msg->port.target_devid_len;
1319 	} else {
1320 		free(port->target_devid, M_CTL);
1321 		port->target_devid = NULL;
1322 	}
1323 	if (msg->port.init_devid_len != 0) {
1324 		if (port->init_devid == NULL ||
1325 		    port->init_devid->len < msg->port.init_devid_len) {
1326 			free(port->init_devid, M_CTL);
1327 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1328 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1329 		}
1330 		memcpy(port->init_devid->data, &msg->port.data[i],
1331 		    msg->port.init_devid_len);
1332 		port->init_devid->len = msg->port.init_devid_len;
1333 		i += msg->port.init_devid_len;
1334 	} else {
1335 		free(port->init_devid, M_CTL);
1336 		port->init_devid = NULL;
1337 	}
1338 	if (new) {
1339 		if (ctl_port_register(port) != 0) {
1340 			printf("%s: ctl_port_register() failed with error\n",
1341 			    __func__);
1342 		}
1343 	}
1344 	mtx_lock(&softc->ctl_lock);
1345 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1346 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1347 			continue;
1348 		mtx_lock(&lun->lun_lock);
1349 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1350 		mtx_unlock(&lun->lun_lock);
1351 	}
1352 	mtx_unlock(&softc->ctl_lock);
1353 }
1354 
1355 static void
1356 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1357 {
1358 	struct ctl_port *port;
1359 	int i, iid;
1360 
1361 	if (len < offsetof(struct ctl_ha_msg_iid, data[0])) {
1362 		printf("%s: Received truncated message %d < %zu\n",
1363 		    __func__, len, offsetof(struct ctl_ha_msg_iid, data[0]));
1364 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1365 		return;
1366 	}
1367 	i = msg->iid.name_len;
1368 	if (len < offsetof(struct ctl_ha_msg_iid, data[i])) {
1369 		printf("%s: Received truncated message data %d < %zu\n",
1370 		    __func__, len, offsetof(struct ctl_ha_msg_iid, data[i]));
1371 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1372 		return;
1373 	}
1374 
1375 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1376 	if (port == NULL) {
1377 		printf("%s: Received IID for unknown port %d\n",
1378 		    __func__, msg->hdr.nexus.targ_port);
1379 		return;
1380 	}
1381 	iid = msg->hdr.nexus.initid;
1382 	if (port->wwpn_iid[iid].in_use != 0 &&
1383 	    msg->iid.in_use == 0)
1384 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1385 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1386 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1387 	free(port->wwpn_iid[iid].name, M_CTL);
1388 	if (msg->iid.name_len) {
1389 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1390 		    msg->iid.name_len, M_CTL);
1391 	} else
1392 		port->wwpn_iid[iid].name = NULL;
1393 }
1394 
1395 static void
1396 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1397 {
1398 
1399 	if (len < sizeof(msg->login)) {
1400 		printf("%s: Received truncated message %d < %zu\n",
1401 		    __func__, len, sizeof(msg->login));
1402 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1403 		return;
1404 	}
1405 
1406 	if (msg->login.version != CTL_HA_VERSION) {
1407 		printf("CTL HA peers have different versions %d != %d\n",
1408 		    msg->login.version, CTL_HA_VERSION);
1409 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1410 		return;
1411 	}
1412 	if (msg->login.ha_mode != softc->ha_mode) {
1413 		printf("CTL HA peers have different ha_mode %d != %d\n",
1414 		    msg->login.ha_mode, softc->ha_mode);
1415 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1416 		return;
1417 	}
1418 	if (msg->login.ha_id == softc->ha_id) {
1419 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1420 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1421 		return;
1422 	}
1423 	if (msg->login.max_luns != ctl_max_luns ||
1424 	    msg->login.max_ports != ctl_max_ports ||
1425 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1426 		printf("CTL HA peers have different limits\n");
1427 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1428 		return;
1429 	}
1430 }
1431 
1432 static void
1433 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1434 {
1435 	struct ctl_lun *lun;
1436 	u_int i;
1437 	uint32_t initidx, targ_lun;
1438 
1439 	if (len < offsetof(struct ctl_ha_msg_mode, data[0])) {
1440 		printf("%s: Received truncated message %d < %zu\n",
1441 		    __func__, len, offsetof(struct ctl_ha_msg_mode, data[0]));
1442 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1443 		return;
1444 	}
1445 	i = msg->mode.page_len;
1446 	if (len < offsetof(struct ctl_ha_msg_mode, data[i])) {
1447 		printf("%s: Received truncated message data %d < %zu\n",
1448 		    __func__, len, offsetof(struct ctl_ha_msg_mode, data[i]));
1449 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1450 		return;
1451 	}
1452 
1453 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1454 	mtx_lock(&softc->ctl_lock);
1455 	if (targ_lun >= ctl_max_luns ||
1456 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1457 		mtx_unlock(&softc->ctl_lock);
1458 		return;
1459 	}
1460 	mtx_lock(&lun->lun_lock);
1461 	mtx_unlock(&softc->ctl_lock);
1462 	if (lun->flags & CTL_LUN_DISABLED) {
1463 		mtx_unlock(&lun->lun_lock);
1464 		return;
1465 	}
1466 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1467 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1468 		    msg->mode.page_code &&
1469 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1470 			break;
1471 	}
1472 	if (i == CTL_NUM_MODE_PAGES) {
1473 		mtx_unlock(&lun->lun_lock);
1474 		return;
1475 	}
1476 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1477 	    min(lun->mode_pages.index[i].page_len, msg->mode.page_len));
1478 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1479 	if (initidx != -1)
1480 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1481 	mtx_unlock(&lun->lun_lock);
1482 }
1483 
1484 /*
1485  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1486  * subsystem come in here.
1487  */
1488 static void
1489 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1490 {
1491 	struct ctl_softc *softc = control_softc;
1492 	union ctl_io *io;
1493 	struct ctl_prio *presio;
1494 	ctl_ha_status isc_status;
1495 
1496 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1497 	if (event == CTL_HA_EVT_MSG_RECV) {
1498 		union ctl_ha_msg *msg, msgbuf;
1499 
1500 		if (param > sizeof(msgbuf))
1501 			msg = malloc(param, M_CTL, M_WAITOK);
1502 		else
1503 			msg = &msgbuf;
1504 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1505 		    M_WAITOK);
1506 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1507 			printf("%s: Error receiving message: %d\n",
1508 			    __func__, isc_status);
1509 			if (msg != &msgbuf)
1510 				free(msg, M_CTL);
1511 			return;
1512 		}
1513 
1514 		CTL_DEBUG_PRINT(("CTL: msg_type %d len %d\n",
1515 		    msg->hdr.msg_type, param));
1516 		switch (msg->hdr.msg_type) {
1517 		case CTL_MSG_SERIALIZE:
1518 			io = ctl_alloc_io(softc->othersc_pool);
1519 			ctl_zero_io(io);
1520 			// populate ctsio from msg
1521 			io->io_hdr.io_type = CTL_IO_SCSI;
1522 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1523 			io->io_hdr.remote_io = msg->hdr.original_sc;
1524 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1525 					    CTL_FLAG_IO_ACTIVE;
1526 			/*
1527 			 * If we're in serialization-only mode, we don't
1528 			 * want to go through full done processing.  Thus
1529 			 * the COPY flag.
1530 			 *
1531 			 * XXX KDM add another flag that is more specific.
1532 			 */
1533 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1534 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1535 			io->io_hdr.nexus = msg->hdr.nexus;
1536 			io->scsiio.priority = msg->scsi.priority;
1537 			io->scsiio.tag_num = msg->scsi.tag_num;
1538 			io->scsiio.tag_type = msg->scsi.tag_type;
1539 #ifdef CTL_TIME_IO
1540 			io->io_hdr.start_time = time_uptime;
1541 			getbinuptime(&io->io_hdr.start_bt);
1542 #endif /* CTL_TIME_IO */
1543 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1544 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1545 			       CTL_MAX_CDBLEN);
1546 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1547 				const struct ctl_cmd_entry *entry;
1548 
1549 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1550 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1551 				io->io_hdr.flags |=
1552 					entry->flags & CTL_FLAG_DATA_MASK;
1553 			}
1554 			ctl_enqueue_isc(io);
1555 			break;
1556 
1557 		/* Performed on the Originating SC, XFER mode only */
1558 		case CTL_MSG_DATAMOVE: {
1559 			struct ctl_sg_entry *sgl;
1560 			int i, j;
1561 
1562 			io = msg->hdr.original_sc;
1563 			if (io == NULL) {
1564 				printf("%s: original_sc == NULL!\n", __func__);
1565 				/* XXX KDM do something here */
1566 				break;
1567 			}
1568 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1569 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1570 			/*
1571 			 * Keep track of this, we need to send it back over
1572 			 * when the datamove is complete.
1573 			 */
1574 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1575 			if (msg->hdr.status == CTL_SUCCESS)
1576 				io->io_hdr.status = msg->hdr.status;
1577 
1578 			if (msg->dt.sg_sequence == 0) {
1579 #ifdef CTL_TIME_IO
1580 				getbinuptime(&io->io_hdr.dma_start_bt);
1581 #endif
1582 				i = msg->dt.kern_sg_entries +
1583 				    msg->dt.kern_data_len /
1584 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1585 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1586 				    M_WAITOK | M_ZERO);
1587 				CTL_RSGL(io) = sgl;
1588 				CTL_LSGL(io) = &sgl[msg->dt.kern_sg_entries];
1589 
1590 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1591 
1592 				io->scsiio.kern_sg_entries =
1593 					msg->dt.kern_sg_entries;
1594 				io->scsiio.rem_sg_entries =
1595 					msg->dt.kern_sg_entries;
1596 				io->scsiio.kern_data_len =
1597 					msg->dt.kern_data_len;
1598 				io->scsiio.kern_total_len =
1599 					msg->dt.kern_total_len;
1600 				io->scsiio.kern_data_resid =
1601 					msg->dt.kern_data_resid;
1602 				io->scsiio.kern_rel_offset =
1603 					msg->dt.kern_rel_offset;
1604 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1605 				io->io_hdr.flags |= msg->dt.flags &
1606 				    CTL_FLAG_BUS_ADDR;
1607 			} else
1608 				sgl = (struct ctl_sg_entry *)
1609 					io->scsiio.kern_data_ptr;
1610 
1611 			for (i = msg->dt.sent_sg_entries, j = 0;
1612 			     i < (msg->dt.sent_sg_entries +
1613 			     msg->dt.cur_sg_entries); i++, j++) {
1614 				sgl[i].addr = msg->dt.sg_list[j].addr;
1615 				sgl[i].len = msg->dt.sg_list[j].len;
1616 			}
1617 
1618 			/*
1619 			 * If this is the last piece of the I/O, we've got
1620 			 * the full S/G list.  Queue processing in the thread.
1621 			 * Otherwise wait for the next piece.
1622 			 */
1623 			if (msg->dt.sg_last != 0)
1624 				ctl_enqueue_isc(io);
1625 			break;
1626 		}
1627 		/* Performed on the Serializing (primary) SC, XFER mode only */
1628 		case CTL_MSG_DATAMOVE_DONE: {
1629 			if (msg->hdr.serializing_sc == NULL) {
1630 				printf("%s: serializing_sc == NULL!\n",
1631 				       __func__);
1632 				/* XXX KDM now what? */
1633 				break;
1634 			}
1635 			/*
1636 			 * We grab the sense information here in case
1637 			 * there was a failure, so we can return status
1638 			 * back to the initiator.
1639 			 */
1640 			io = msg->hdr.serializing_sc;
1641 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1642 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1643 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1644 			io->io_hdr.port_status = msg->scsi.port_status;
1645 			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1646 			if (msg->hdr.status != CTL_STATUS_NONE) {
1647 				io->io_hdr.status = msg->hdr.status;
1648 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1649 				io->scsiio.sense_len = msg->scsi.sense_len;
1650 				memcpy(&io->scsiio.sense_data,
1651 				    &msg->scsi.sense_data,
1652 				    msg->scsi.sense_len);
1653 				if (msg->hdr.status == CTL_SUCCESS)
1654 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1655 			}
1656 			ctl_enqueue_isc(io);
1657 			break;
1658 		}
1659 
1660 		/* Preformed on Originating SC, SER_ONLY mode */
1661 		case CTL_MSG_R2R:
1662 			io = msg->hdr.original_sc;
1663 			if (io == NULL) {
1664 				printf("%s: original_sc == NULL!\n",
1665 				    __func__);
1666 				break;
1667 			}
1668 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1669 			io->io_hdr.msg_type = CTL_MSG_R2R;
1670 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1671 			ctl_enqueue_isc(io);
1672 			break;
1673 
1674 		/*
1675 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1676 		 * mode.
1677 		 * Performed on the Originating (i.e. secondary) SC in XFER
1678 		 * mode
1679 		 */
1680 		case CTL_MSG_FINISH_IO:
1681 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1682 				ctl_isc_handler_finish_xfer(softc, msg);
1683 			else
1684 				ctl_isc_handler_finish_ser_only(softc, msg);
1685 			break;
1686 
1687 		/* Preformed on Originating SC */
1688 		case CTL_MSG_BAD_JUJU:
1689 			io = msg->hdr.original_sc;
1690 			if (io == NULL) {
1691 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1692 				       __func__);
1693 				break;
1694 			}
1695 			ctl_copy_sense_data(msg, io);
1696 			/*
1697 			 * IO should have already been cleaned up on other
1698 			 * SC so clear this flag so we won't send a message
1699 			 * back to finish the IO there.
1700 			 */
1701 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1702 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1703 
1704 			/* io = msg->hdr.serializing_sc; */
1705 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1706 			ctl_enqueue_isc(io);
1707 			break;
1708 
1709 		/* Handle resets sent from the other side */
1710 		case CTL_MSG_MANAGE_TASKS: {
1711 			struct ctl_taskio *taskio;
1712 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1713 			    softc->othersc_pool);
1714 			ctl_zero_io((union ctl_io *)taskio);
1715 			taskio->io_hdr.io_type = CTL_IO_TASK;
1716 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1717 			taskio->io_hdr.nexus = msg->hdr.nexus;
1718 			taskio->task_action = msg->task.task_action;
1719 			taskio->tag_num = msg->task.tag_num;
1720 			taskio->tag_type = msg->task.tag_type;
1721 #ifdef CTL_TIME_IO
1722 			taskio->io_hdr.start_time = time_uptime;
1723 			getbinuptime(&taskio->io_hdr.start_bt);
1724 #endif /* CTL_TIME_IO */
1725 			ctl_run_task((union ctl_io *)taskio);
1726 			break;
1727 		}
1728 		/* Persistent Reserve action which needs attention */
1729 		case CTL_MSG_PERS_ACTION:
1730 			presio = (struct ctl_prio *)ctl_alloc_io(
1731 			    softc->othersc_pool);
1732 			ctl_zero_io((union ctl_io *)presio);
1733 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1734 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1735 			presio->io_hdr.nexus = msg->hdr.nexus;
1736 			presio->pr_msg = msg->pr;
1737 			ctl_enqueue_isc((union ctl_io *)presio);
1738 			break;
1739 		case CTL_MSG_UA:
1740 			ctl_isc_ua(softc, msg, param);
1741 			break;
1742 		case CTL_MSG_PORT_SYNC:
1743 			ctl_isc_port_sync(softc, msg, param);
1744 			break;
1745 		case CTL_MSG_LUN_SYNC:
1746 			ctl_isc_lun_sync(softc, msg, param);
1747 			break;
1748 		case CTL_MSG_IID_SYNC:
1749 			ctl_isc_iid_sync(softc, msg, param);
1750 			break;
1751 		case CTL_MSG_LOGIN:
1752 			ctl_isc_login(softc, msg, param);
1753 			break;
1754 		case CTL_MSG_MODE_SYNC:
1755 			ctl_isc_mode_sync(softc, msg, param);
1756 			break;
1757 		default:
1758 			printf("Received HA message of unknown type %d\n",
1759 			    msg->hdr.msg_type);
1760 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1761 			break;
1762 		}
1763 		if (msg != &msgbuf)
1764 			free(msg, M_CTL);
1765 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1766 		printf("CTL: HA link status changed from %d to %d\n",
1767 		    softc->ha_link, param);
1768 		if (param == softc->ha_link)
1769 			return;
1770 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1771 			softc->ha_link = param;
1772 			ctl_isc_ha_link_down(softc);
1773 		} else {
1774 			softc->ha_link = param;
1775 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1776 				ctl_isc_ha_link_up(softc);
1777 		}
1778 		return;
1779 	} else {
1780 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1781 		return;
1782 	}
1783 }
1784 
1785 static void
1786 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1787 {
1788 
1789 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1790 	    src->scsi.sense_len);
1791 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1792 	dest->scsiio.sense_len = src->scsi.sense_len;
1793 	dest->io_hdr.status = src->hdr.status;
1794 }
1795 
1796 static void
1797 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1798 {
1799 
1800 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1801 	    src->scsiio.sense_len);
1802 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1803 	dest->scsi.sense_len = src->scsiio.sense_len;
1804 	dest->hdr.status = src->io_hdr.status;
1805 }
1806 
1807 void
1808 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1809 {
1810 	struct ctl_softc *softc = lun->ctl_softc;
1811 	ctl_ua_type *pu;
1812 
1813 	if (initidx < softc->init_min || initidx >= softc->init_max)
1814 		return;
1815 	mtx_assert(&lun->lun_lock, MA_OWNED);
1816 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1817 	if (pu == NULL)
1818 		return;
1819 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1820 }
1821 
1822 void
1823 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1824 {
1825 	int i;
1826 
1827 	mtx_assert(&lun->lun_lock, MA_OWNED);
1828 	if (lun->pending_ua[port] == NULL)
1829 		return;
1830 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1831 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1832 			continue;
1833 		lun->pending_ua[port][i] |= ua;
1834 	}
1835 }
1836 
1837 void
1838 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1839 {
1840 	struct ctl_softc *softc = lun->ctl_softc;
1841 	int i;
1842 
1843 	mtx_assert(&lun->lun_lock, MA_OWNED);
1844 	for (i = softc->port_min; i < softc->port_max; i++)
1845 		ctl_est_ua_port(lun, i, except, ua);
1846 }
1847 
1848 void
1849 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1850 {
1851 	struct ctl_softc *softc = lun->ctl_softc;
1852 	ctl_ua_type *pu;
1853 
1854 	if (initidx < softc->init_min || initidx >= softc->init_max)
1855 		return;
1856 	mtx_assert(&lun->lun_lock, MA_OWNED);
1857 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1858 	if (pu == NULL)
1859 		return;
1860 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1861 }
1862 
1863 void
1864 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1865 {
1866 	struct ctl_softc *softc = lun->ctl_softc;
1867 	int i, j;
1868 
1869 	mtx_assert(&lun->lun_lock, MA_OWNED);
1870 	for (i = softc->port_min; i < softc->port_max; i++) {
1871 		if (lun->pending_ua[i] == NULL)
1872 			continue;
1873 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1874 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1875 				continue;
1876 			lun->pending_ua[i][j] &= ~ua;
1877 		}
1878 	}
1879 }
1880 
1881 void
1882 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1883     ctl_ua_type ua_type)
1884 {
1885 	struct ctl_lun *lun;
1886 
1887 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1888 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1889 		mtx_lock(&lun->lun_lock);
1890 		ctl_clr_ua(lun, initidx, ua_type);
1891 		mtx_unlock(&lun->lun_lock);
1892 	}
1893 }
1894 
1895 static int
1896 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1897 {
1898 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1899 	struct ctl_lun *lun;
1900 	struct ctl_lun_req ireq;
1901 	int error, value;
1902 
1903 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1904 	error = sysctl_handle_int(oidp, &value, 0, req);
1905 	if ((error != 0) || (req->newptr == NULL))
1906 		return (error);
1907 
1908 	mtx_lock(&softc->ctl_lock);
1909 	if (value == 0)
1910 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1911 	else
1912 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1913 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1914 		mtx_unlock(&softc->ctl_lock);
1915 		bzero(&ireq, sizeof(ireq));
1916 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1917 		ireq.reqdata.modify.lun_id = lun->lun;
1918 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1919 		    curthread);
1920 		if (ireq.status != CTL_LUN_OK) {
1921 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1922 			    __func__, ireq.status, ireq.error_str);
1923 		}
1924 		mtx_lock(&softc->ctl_lock);
1925 	}
1926 	mtx_unlock(&softc->ctl_lock);
1927 	return (0);
1928 }
1929 
1930 static int
1931 ctl_init(void)
1932 {
1933 	struct make_dev_args args;
1934 	struct ctl_softc *softc;
1935 	int i, error;
1936 
1937 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1938 			       M_WAITOK | M_ZERO);
1939 
1940 	make_dev_args_init(&args);
1941 	args.mda_devsw = &ctl_cdevsw;
1942 	args.mda_uid = UID_ROOT;
1943 	args.mda_gid = GID_OPERATOR;
1944 	args.mda_mode = 0600;
1945 	args.mda_si_drv1 = softc;
1946 	args.mda_si_drv2 = NULL;
1947 	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1948 	if (error != 0) {
1949 		free(softc, M_DEVBUF);
1950 		control_softc = NULL;
1951 		return (error);
1952 	}
1953 
1954 	sysctl_ctx_init(&softc->sysctl_ctx);
1955 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1956 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1957 		CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "CAM Target Layer");
1958 
1959 	if (softc->sysctl_tree == NULL) {
1960 		printf("%s: unable to allocate sysctl tree\n", __func__);
1961 		destroy_dev(softc->dev);
1962 		free(softc, M_DEVBUF);
1963 		control_softc = NULL;
1964 		return (ENOMEM);
1965 	}
1966 
1967 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1968 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1969 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1970 	softc->flags = 0;
1971 
1972 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1973 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1974 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1975 
1976 	if (ctl_max_luns <= 0 || powerof2(ctl_max_luns) == 0) {
1977 		printf("Bad value %d for kern.cam.ctl.max_luns, must be a power of two, using %d\n",
1978 		    ctl_max_luns, CTL_DEFAULT_MAX_LUNS);
1979 		ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
1980 	}
1981 	softc->ctl_luns = malloc(sizeof(struct ctl_lun *) * ctl_max_luns,
1982 	    M_DEVBUF, M_WAITOK | M_ZERO);
1983 	softc->ctl_lun_mask = malloc(sizeof(uint32_t) *
1984 	    ((ctl_max_luns + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1985 	if (ctl_max_ports <= 0 || powerof2(ctl_max_ports) == 0) {
1986 		printf("Bad value %d for kern.cam.ctl.max_ports, must be a power of two, using %d\n",
1987 		    ctl_max_ports, CTL_DEFAULT_MAX_PORTS);
1988 		ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
1989 	}
1990 	softc->ctl_port_mask = malloc(sizeof(uint32_t) *
1991 	  ((ctl_max_ports + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1992 	softc->ctl_ports = malloc(sizeof(struct ctl_port *) * ctl_max_ports,
1993 	     M_DEVBUF, M_WAITOK | M_ZERO);
1994 
1995 	/*
1996 	 * In Copan's HA scheme, the "master" and "slave" roles are
1997 	 * figured out through the slot the controller is in.  Although it
1998 	 * is an active/active system, someone has to be in charge.
1999 	 */
2000 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2001 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
2002 	    "HA head ID (0 - no HA)");
2003 	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
2004 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
2005 		softc->is_single = 1;
2006 		softc->port_cnt = ctl_max_ports;
2007 		softc->port_min = 0;
2008 	} else {
2009 		softc->port_cnt = ctl_max_ports / NUM_HA_SHELVES;
2010 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
2011 	}
2012 	softc->port_max = softc->port_min + softc->port_cnt;
2013 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
2014 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
2015 
2016 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
2017 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
2018 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
2019 
2020 	STAILQ_INIT(&softc->lun_list);
2021 	STAILQ_INIT(&softc->fe_list);
2022 	STAILQ_INIT(&softc->port_list);
2023 	STAILQ_INIT(&softc->be_list);
2024 	ctl_tpc_init(softc);
2025 
2026 	if (worker_threads <= 0)
2027 		worker_threads = max(1, mp_ncpus / 4);
2028 	if (worker_threads > CTL_MAX_THREADS)
2029 		worker_threads = CTL_MAX_THREADS;
2030 
2031 	for (i = 0; i < worker_threads; i++) {
2032 		struct ctl_thread *thr = &softc->threads[i];
2033 
2034 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
2035 		thr->ctl_softc = softc;
2036 		STAILQ_INIT(&thr->incoming_queue);
2037 		STAILQ_INIT(&thr->rtr_queue);
2038 		STAILQ_INIT(&thr->done_queue);
2039 		STAILQ_INIT(&thr->isc_queue);
2040 
2041 		error = kproc_kthread_add(ctl_work_thread, thr,
2042 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
2043 		if (error != 0) {
2044 			printf("error creating CTL work thread!\n");
2045 			return (error);
2046 		}
2047 	}
2048 	error = kproc_kthread_add(ctl_thresh_thread, softc,
2049 	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
2050 	if (error != 0) {
2051 		printf("error creating CTL threshold thread!\n");
2052 		return (error);
2053 	}
2054 
2055 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
2056 	    OID_AUTO, "ha_role",
2057 	    CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
2058 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
2059 
2060 	if (softc->is_single == 0) {
2061 		if (ctl_frontend_register(&ha_frontend) != 0)
2062 			softc->is_single = 1;
2063 	}
2064 	return (0);
2065 }
2066 
2067 static int
2068 ctl_shutdown(void)
2069 {
2070 	struct ctl_softc *softc = control_softc;
2071 	int i;
2072 
2073 	if (softc->is_single == 0)
2074 		ctl_frontend_deregister(&ha_frontend);
2075 
2076 	destroy_dev(softc->dev);
2077 
2078 	/* Shutdown CTL threads. */
2079 	softc->shutdown = 1;
2080 	for (i = 0; i < worker_threads; i++) {
2081 		struct ctl_thread *thr = &softc->threads[i];
2082 		while (thr->thread != NULL) {
2083 			wakeup(thr);
2084 			if (thr->thread != NULL)
2085 				pause("CTL thr shutdown", 1);
2086 		}
2087 		mtx_destroy(&thr->queue_lock);
2088 	}
2089 	while (softc->thresh_thread != NULL) {
2090 		wakeup(softc->thresh_thread);
2091 		if (softc->thresh_thread != NULL)
2092 			pause("CTL thr shutdown", 1);
2093 	}
2094 
2095 	ctl_tpc_shutdown(softc);
2096 	uma_zdestroy(softc->io_zone);
2097 	mtx_destroy(&softc->ctl_lock);
2098 
2099 	free(softc->ctl_luns, M_DEVBUF);
2100 	free(softc->ctl_lun_mask, M_DEVBUF);
2101 	free(softc->ctl_port_mask, M_DEVBUF);
2102 	free(softc->ctl_ports, M_DEVBUF);
2103 
2104 	sysctl_ctx_free(&softc->sysctl_ctx);
2105 
2106 	free(softc, M_DEVBUF);
2107 	control_softc = NULL;
2108 	return (0);
2109 }
2110 
2111 static int
2112 ctl_module_event_handler(module_t mod, int what, void *arg)
2113 {
2114 
2115 	switch (what) {
2116 	case MOD_LOAD:
2117 		return (ctl_init());
2118 	case MOD_UNLOAD:
2119 		return (ctl_shutdown());
2120 	default:
2121 		return (EOPNOTSUPP);
2122 	}
2123 }
2124 
2125 /*
2126  * XXX KDM should we do some access checks here?  Bump a reference count to
2127  * prevent a CTL module from being unloaded while someone has it open?
2128  */
2129 static int
2130 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2131 {
2132 	return (0);
2133 }
2134 
2135 static int
2136 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2137 {
2138 	return (0);
2139 }
2140 
2141 /*
2142  * Remove an initiator by port number and initiator ID.
2143  * Returns 0 for success, -1 for failure.
2144  */
2145 int
2146 ctl_remove_initiator(struct ctl_port *port, int iid)
2147 {
2148 	struct ctl_softc *softc = port->ctl_softc;
2149 	int last;
2150 
2151 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2152 
2153 	if (iid > CTL_MAX_INIT_PER_PORT) {
2154 		printf("%s: initiator ID %u > maximun %u!\n",
2155 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2156 		return (-1);
2157 	}
2158 
2159 	mtx_lock(&softc->ctl_lock);
2160 	last = (--port->wwpn_iid[iid].in_use == 0);
2161 	port->wwpn_iid[iid].last_use = time_uptime;
2162 	mtx_unlock(&softc->ctl_lock);
2163 	if (last)
2164 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2165 	ctl_isc_announce_iid(port, iid);
2166 
2167 	return (0);
2168 }
2169 
2170 /*
2171  * Add an initiator to the initiator map.
2172  * Returns iid for success, < 0 for failure.
2173  */
2174 int
2175 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2176 {
2177 	struct ctl_softc *softc = port->ctl_softc;
2178 	time_t best_time;
2179 	int i, best;
2180 
2181 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2182 
2183 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2184 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2185 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2186 		free(name, M_CTL);
2187 		return (-1);
2188 	}
2189 
2190 	mtx_lock(&softc->ctl_lock);
2191 
2192 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2193 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2194 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2195 				iid = i;
2196 				break;
2197 			}
2198 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2199 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2200 				iid = i;
2201 				break;
2202 			}
2203 		}
2204 	}
2205 
2206 	if (iid < 0) {
2207 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2208 			if (port->wwpn_iid[i].in_use == 0 &&
2209 			    port->wwpn_iid[i].wwpn == 0 &&
2210 			    port->wwpn_iid[i].name == NULL) {
2211 				iid = i;
2212 				break;
2213 			}
2214 		}
2215 	}
2216 
2217 	if (iid < 0) {
2218 		best = -1;
2219 		best_time = INT32_MAX;
2220 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2221 			if (port->wwpn_iid[i].in_use == 0) {
2222 				if (port->wwpn_iid[i].last_use < best_time) {
2223 					best = i;
2224 					best_time = port->wwpn_iid[i].last_use;
2225 				}
2226 			}
2227 		}
2228 		iid = best;
2229 	}
2230 
2231 	if (iid < 0) {
2232 		mtx_unlock(&softc->ctl_lock);
2233 		free(name, M_CTL);
2234 		return (-2);
2235 	}
2236 
2237 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2238 		/*
2239 		 * This is not an error yet.
2240 		 */
2241 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2242 #if 0
2243 			printf("%s: port %d iid %u WWPN %#jx arrived"
2244 			    " again\n", __func__, port->targ_port,
2245 			    iid, (uintmax_t)wwpn);
2246 #endif
2247 			goto take;
2248 		}
2249 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2250 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2251 #if 0
2252 			printf("%s: port %d iid %u name '%s' arrived"
2253 			    " again\n", __func__, port->targ_port,
2254 			    iid, name);
2255 #endif
2256 			goto take;
2257 		}
2258 
2259 		/*
2260 		 * This is an error, but what do we do about it?  The
2261 		 * driver is telling us we have a new WWPN for this
2262 		 * initiator ID, so we pretty much need to use it.
2263 		 */
2264 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2265 		    " but WWPN %#jx '%s' is still at that address\n",
2266 		    __func__, port->targ_port, iid, wwpn, name,
2267 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2268 		    port->wwpn_iid[iid].name);
2269 	}
2270 take:
2271 	free(port->wwpn_iid[iid].name, M_CTL);
2272 	port->wwpn_iid[iid].name = name;
2273 	port->wwpn_iid[iid].wwpn = wwpn;
2274 	port->wwpn_iid[iid].in_use++;
2275 	mtx_unlock(&softc->ctl_lock);
2276 	ctl_isc_announce_iid(port, iid);
2277 
2278 	return (iid);
2279 }
2280 
2281 static int
2282 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2283 {
2284 	int len;
2285 
2286 	switch (port->port_type) {
2287 	case CTL_PORT_FC:
2288 	{
2289 		struct scsi_transportid_fcp *id =
2290 		    (struct scsi_transportid_fcp *)buf;
2291 		if (port->wwpn_iid[iid].wwpn == 0)
2292 			return (0);
2293 		memset(id, 0, sizeof(*id));
2294 		id->format_protocol = SCSI_PROTO_FC;
2295 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2296 		return (sizeof(*id));
2297 	}
2298 	case CTL_PORT_ISCSI:
2299 	{
2300 		struct scsi_transportid_iscsi_port *id =
2301 		    (struct scsi_transportid_iscsi_port *)buf;
2302 		if (port->wwpn_iid[iid].name == NULL)
2303 			return (0);
2304 		memset(id, 0, 256);
2305 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2306 		    SCSI_PROTO_ISCSI;
2307 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2308 		len = roundup2(min(len, 252), 4);
2309 		scsi_ulto2b(len, id->additional_length);
2310 		return (sizeof(*id) + len);
2311 	}
2312 	case CTL_PORT_SAS:
2313 	{
2314 		struct scsi_transportid_sas *id =
2315 		    (struct scsi_transportid_sas *)buf;
2316 		if (port->wwpn_iid[iid].wwpn == 0)
2317 			return (0);
2318 		memset(id, 0, sizeof(*id));
2319 		id->format_protocol = SCSI_PROTO_SAS;
2320 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2321 		return (sizeof(*id));
2322 	}
2323 	default:
2324 	{
2325 		struct scsi_transportid_spi *id =
2326 		    (struct scsi_transportid_spi *)buf;
2327 		memset(id, 0, sizeof(*id));
2328 		id->format_protocol = SCSI_PROTO_SPI;
2329 		scsi_ulto2b(iid, id->scsi_addr);
2330 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2331 		return (sizeof(*id));
2332 	}
2333 	}
2334 }
2335 
2336 /*
2337  * Serialize a command that went down the "wrong" side, and so was sent to
2338  * this controller for execution.  The logic is a little different than the
2339  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2340  * sent back to the other side, but in the success case, we execute the
2341  * command on this side (XFER mode) or tell the other side to execute it
2342  * (SER_ONLY mode).
2343  */
2344 static void
2345 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2346 {
2347 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2348 	struct ctl_port *port = CTL_PORT(ctsio);
2349 	union ctl_ha_msg msg_info;
2350 	struct ctl_lun *lun;
2351 	const struct ctl_cmd_entry *entry;
2352 	union ctl_io *bio;
2353 	uint32_t targ_lun;
2354 
2355 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2356 
2357 	/* Make sure that we know about this port. */
2358 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2359 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2360 					 /*retry_count*/ 1);
2361 		goto badjuju;
2362 	}
2363 
2364 	/* Make sure that we know about this LUN. */
2365 	mtx_lock(&softc->ctl_lock);
2366 	if (targ_lun >= ctl_max_luns ||
2367 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2368 		mtx_unlock(&softc->ctl_lock);
2369 
2370 		/*
2371 		 * The other node would not send this request to us unless
2372 		 * received announce that we are primary node for this LUN.
2373 		 * If this LUN does not exist now, it is probably result of
2374 		 * a race, so respond to initiator in the most opaque way.
2375 		 */
2376 		ctl_set_busy(ctsio);
2377 		goto badjuju;
2378 	}
2379 	mtx_lock(&lun->lun_lock);
2380 	mtx_unlock(&softc->ctl_lock);
2381 
2382 	/*
2383 	 * If the LUN is invalid, pretend that it doesn't exist.
2384 	 * It will go away as soon as all pending I/Os completed.
2385 	 */
2386 	if (lun->flags & CTL_LUN_DISABLED) {
2387 		mtx_unlock(&lun->lun_lock);
2388 		ctl_set_busy(ctsio);
2389 		goto badjuju;
2390 	}
2391 
2392 	entry = ctl_get_cmd_entry(ctsio, NULL);
2393 	ctsio->seridx = entry->seridx;
2394 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2395 		mtx_unlock(&lun->lun_lock);
2396 		goto badjuju;
2397 	}
2398 
2399 	CTL_LUN(ctsio) = lun;
2400 	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2401 
2402 	/*
2403 	 * Every I/O goes into the OOA queue for a
2404 	 * particular LUN, and stays there until completion.
2405 	 */
2406 #ifdef CTL_TIME_IO
2407 	if (LIST_EMPTY(&lun->ooa_queue))
2408 		lun->idle_time += getsbinuptime() - lun->last_busy;
2409 #endif
2410 	LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2411 
2412 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
2413 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
2414 	case CTL_ACTION_PASS:
2415 	case CTL_ACTION_SKIP:
2416 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2417 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2418 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2419 			mtx_unlock(&lun->lun_lock);
2420 		} else {
2421 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2422 			mtx_unlock(&lun->lun_lock);
2423 
2424 			/* send msg back to other side */
2425 			msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2426 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2427 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2428 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2429 			    sizeof(msg_info.hdr), M_WAITOK);
2430 		}
2431 		break;
2432 	case CTL_ACTION_BLOCK:
2433 		ctsio->io_hdr.blocker = bio;
2434 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
2435 				  blocked_links);
2436 		mtx_unlock(&lun->lun_lock);
2437 		break;
2438 	case CTL_ACTION_OVERLAP:
2439 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2440 		mtx_unlock(&lun->lun_lock);
2441 		ctl_set_overlapped_cmd(ctsio);
2442 		goto badjuju;
2443 	case CTL_ACTION_OVERLAP_TAG:
2444 		LIST_REMOVE(&ctsio->io_hdr, ooa_links);
2445 		mtx_unlock(&lun->lun_lock);
2446 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2447 badjuju:
2448 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2449 		msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2450 		msg_info.hdr.serializing_sc = NULL;
2451 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2452 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2453 		    sizeof(msg_info.scsi), M_WAITOK);
2454 		ctl_free_io((union ctl_io *)ctsio);
2455 		break;
2456 	default:
2457 		__assert_unreachable();
2458 	}
2459 }
2460 
2461 /*
2462  * Returns 0 for success, errno for failure.
2463  */
2464 static void
2465 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2466 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2467 {
2468 	struct ctl_io_hdr *ioh;
2469 
2470 	mtx_lock(&lun->lun_lock);
2471 	ioh = LIST_FIRST(&lun->ooa_queue);
2472 	if (ioh == NULL) {
2473 		mtx_unlock(&lun->lun_lock);
2474 		return;
2475 	}
2476 	while (LIST_NEXT(ioh, ooa_links) != NULL)
2477 		ioh = LIST_NEXT(ioh, ooa_links);
2478 	for ( ; ioh; ioh = LIST_PREV(ioh, &lun->ooa_queue, ctl_io_hdr, ooa_links)) {
2479 		union ctl_io *io = (union ctl_io *)ioh;
2480 		struct ctl_ooa_entry *entry;
2481 
2482 		/*
2483 		 * If we've got more than we can fit, just count the
2484 		 * remaining entries.
2485 		 */
2486 		if (*cur_fill_num >= ooa_hdr->alloc_num) {
2487 			(*cur_fill_num)++;
2488 			continue;
2489 		}
2490 
2491 		entry = &kern_entries[*cur_fill_num];
2492 
2493 		entry->tag_num = io->scsiio.tag_num;
2494 		entry->lun_num = lun->lun;
2495 #ifdef CTL_TIME_IO
2496 		entry->start_bt = io->io_hdr.start_bt;
2497 #endif
2498 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2499 		entry->cdb_len = io->scsiio.cdb_len;
2500 		if (io->io_hdr.blocker != NULL)
2501 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2502 
2503 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2504 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2505 
2506 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2507 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2508 
2509 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2510 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2511 
2512 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2513 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2514 
2515 		if (io->io_hdr.flags & CTL_FLAG_STATUS_QUEUED)
2516 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_QUEUED;
2517 
2518 		if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT)
2519 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_SENT;
2520 		(*cur_fill_num)++;
2521 	}
2522 	mtx_unlock(&lun->lun_lock);
2523 }
2524 
2525 /*
2526  * Escape characters that are illegal or not recommended in XML.
2527  */
2528 int
2529 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2530 {
2531 	char *end = str + size;
2532 	int retval;
2533 
2534 	retval = 0;
2535 
2536 	for (; *str && str < end; str++) {
2537 		switch (*str) {
2538 		case '&':
2539 			retval = sbuf_printf(sb, "&amp;");
2540 			break;
2541 		case '>':
2542 			retval = sbuf_printf(sb, "&gt;");
2543 			break;
2544 		case '<':
2545 			retval = sbuf_printf(sb, "&lt;");
2546 			break;
2547 		default:
2548 			retval = sbuf_putc(sb, *str);
2549 			break;
2550 		}
2551 
2552 		if (retval != 0)
2553 			break;
2554 	}
2555 
2556 	return (retval);
2557 }
2558 
2559 static void
2560 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2561 {
2562 	struct scsi_vpd_id_descriptor *desc;
2563 	int i;
2564 
2565 	if (id == NULL || id->len < 4)
2566 		return;
2567 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2568 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2569 	case SVPD_ID_TYPE_T10:
2570 		sbuf_printf(sb, "t10.");
2571 		break;
2572 	case SVPD_ID_TYPE_EUI64:
2573 		sbuf_printf(sb, "eui.");
2574 		break;
2575 	case SVPD_ID_TYPE_NAA:
2576 		sbuf_printf(sb, "naa.");
2577 		break;
2578 	case SVPD_ID_TYPE_SCSI_NAME:
2579 		break;
2580 	}
2581 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2582 	case SVPD_ID_CODESET_BINARY:
2583 		for (i = 0; i < desc->length; i++)
2584 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2585 		break;
2586 	case SVPD_ID_CODESET_ASCII:
2587 		sbuf_printf(sb, "%.*s", (int)desc->length,
2588 		    (char *)desc->identifier);
2589 		break;
2590 	case SVPD_ID_CODESET_UTF8:
2591 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2592 		break;
2593 	}
2594 }
2595 
2596 static int
2597 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2598 	  struct thread *td)
2599 {
2600 	struct ctl_softc *softc = dev->si_drv1;
2601 	struct ctl_port *port;
2602 	struct ctl_lun *lun;
2603 	int retval;
2604 
2605 	retval = 0;
2606 
2607 	switch (cmd) {
2608 	case CTL_IO:
2609 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2610 		break;
2611 	case CTL_ENABLE_PORT:
2612 	case CTL_DISABLE_PORT:
2613 	case CTL_SET_PORT_WWNS: {
2614 		struct ctl_port *port;
2615 		struct ctl_port_entry *entry;
2616 
2617 		entry = (struct ctl_port_entry *)addr;
2618 
2619 		mtx_lock(&softc->ctl_lock);
2620 		STAILQ_FOREACH(port, &softc->port_list, links) {
2621 			int action, done;
2622 
2623 			if (port->targ_port < softc->port_min ||
2624 			    port->targ_port >= softc->port_max)
2625 				continue;
2626 
2627 			action = 0;
2628 			done = 0;
2629 			if ((entry->port_type == CTL_PORT_NONE)
2630 			 && (entry->targ_port == port->targ_port)) {
2631 				/*
2632 				 * If the user only wants to enable or
2633 				 * disable or set WWNs on a specific port,
2634 				 * do the operation and we're done.
2635 				 */
2636 				action = 1;
2637 				done = 1;
2638 			} else if (entry->port_type & port->port_type) {
2639 				/*
2640 				 * Compare the user's type mask with the
2641 				 * particular frontend type to see if we
2642 				 * have a match.
2643 				 */
2644 				action = 1;
2645 				done = 0;
2646 
2647 				/*
2648 				 * Make sure the user isn't trying to set
2649 				 * WWNs on multiple ports at the same time.
2650 				 */
2651 				if (cmd == CTL_SET_PORT_WWNS) {
2652 					printf("%s: Can't set WWNs on "
2653 					       "multiple ports\n", __func__);
2654 					retval = EINVAL;
2655 					break;
2656 				}
2657 			}
2658 			if (action == 0)
2659 				continue;
2660 
2661 			/*
2662 			 * XXX KDM we have to drop the lock here, because
2663 			 * the online/offline operations can potentially
2664 			 * block.  We need to reference count the frontends
2665 			 * so they can't go away,
2666 			 */
2667 			if (cmd == CTL_ENABLE_PORT) {
2668 				mtx_unlock(&softc->ctl_lock);
2669 				ctl_port_online(port);
2670 				mtx_lock(&softc->ctl_lock);
2671 			} else if (cmd == CTL_DISABLE_PORT) {
2672 				mtx_unlock(&softc->ctl_lock);
2673 				ctl_port_offline(port);
2674 				mtx_lock(&softc->ctl_lock);
2675 			} else if (cmd == CTL_SET_PORT_WWNS) {
2676 				ctl_port_set_wwns(port,
2677 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2678 				    1 : 0, entry->wwnn,
2679 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2680 				    1 : 0, entry->wwpn);
2681 			}
2682 			if (done != 0)
2683 				break;
2684 		}
2685 		mtx_unlock(&softc->ctl_lock);
2686 		break;
2687 	}
2688 	case CTL_GET_OOA: {
2689 		struct ctl_ooa *ooa_hdr;
2690 		struct ctl_ooa_entry *entries;
2691 		uint32_t cur_fill_num;
2692 
2693 		ooa_hdr = (struct ctl_ooa *)addr;
2694 
2695 		if ((ooa_hdr->alloc_len == 0)
2696 		 || (ooa_hdr->alloc_num == 0)) {
2697 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2698 			       "must be non-zero\n", __func__,
2699 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2700 			retval = EINVAL;
2701 			break;
2702 		}
2703 
2704 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2705 		    sizeof(struct ctl_ooa_entry))) {
2706 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2707 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2708 			       __func__, ooa_hdr->alloc_len,
2709 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2710 			retval = EINVAL;
2711 			break;
2712 		}
2713 
2714 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2715 		if (entries == NULL) {
2716 			printf("%s: could not allocate %d bytes for OOA "
2717 			       "dump\n", __func__, ooa_hdr->alloc_len);
2718 			retval = ENOMEM;
2719 			break;
2720 		}
2721 
2722 		mtx_lock(&softc->ctl_lock);
2723 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2724 		    (ooa_hdr->lun_num >= ctl_max_luns ||
2725 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2726 			mtx_unlock(&softc->ctl_lock);
2727 			free(entries, M_CTL);
2728 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2729 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2730 			retval = EINVAL;
2731 			break;
2732 		}
2733 
2734 		cur_fill_num = 0;
2735 
2736 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2737 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2738 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2739 				    ooa_hdr, entries);
2740 			}
2741 		} else {
2742 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2743 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2744 			    entries);
2745 		}
2746 		mtx_unlock(&softc->ctl_lock);
2747 
2748 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2749 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2750 			sizeof(struct ctl_ooa_entry);
2751 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2752 		if (retval != 0) {
2753 			printf("%s: error copying out %d bytes for OOA dump\n",
2754 			       __func__, ooa_hdr->fill_len);
2755 		}
2756 
2757 		getbinuptime(&ooa_hdr->cur_bt);
2758 
2759 		if (cur_fill_num > ooa_hdr->alloc_num) {
2760 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2761 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2762 		} else {
2763 			ooa_hdr->dropped_num = 0;
2764 			ooa_hdr->status = CTL_OOA_OK;
2765 		}
2766 
2767 		free(entries, M_CTL);
2768 		break;
2769 	}
2770 	case CTL_DELAY_IO: {
2771 		struct ctl_io_delay_info *delay_info;
2772 
2773 		delay_info = (struct ctl_io_delay_info *)addr;
2774 
2775 #ifdef CTL_IO_DELAY
2776 		mtx_lock(&softc->ctl_lock);
2777 		if (delay_info->lun_id >= ctl_max_luns ||
2778 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2779 			mtx_unlock(&softc->ctl_lock);
2780 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2781 			break;
2782 		}
2783 		mtx_lock(&lun->lun_lock);
2784 		mtx_unlock(&softc->ctl_lock);
2785 		delay_info->status = CTL_DELAY_STATUS_OK;
2786 		switch (delay_info->delay_type) {
2787 		case CTL_DELAY_TYPE_CONT:
2788 		case CTL_DELAY_TYPE_ONESHOT:
2789 			break;
2790 		default:
2791 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2792 			break;
2793 		}
2794 		switch (delay_info->delay_loc) {
2795 		case CTL_DELAY_LOC_DATAMOVE:
2796 			lun->delay_info.datamove_type = delay_info->delay_type;
2797 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2798 			break;
2799 		case CTL_DELAY_LOC_DONE:
2800 			lun->delay_info.done_type = delay_info->delay_type;
2801 			lun->delay_info.done_delay = delay_info->delay_secs;
2802 			break;
2803 		default:
2804 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2805 			break;
2806 		}
2807 		mtx_unlock(&lun->lun_lock);
2808 #else
2809 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2810 #endif /* CTL_IO_DELAY */
2811 		break;
2812 	}
2813 	case CTL_ERROR_INJECT: {
2814 		struct ctl_error_desc *err_desc, *new_err_desc;
2815 
2816 		err_desc = (struct ctl_error_desc *)addr;
2817 
2818 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2819 				      M_WAITOK | M_ZERO);
2820 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2821 
2822 		mtx_lock(&softc->ctl_lock);
2823 		if (err_desc->lun_id >= ctl_max_luns ||
2824 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2825 			mtx_unlock(&softc->ctl_lock);
2826 			free(new_err_desc, M_CTL);
2827 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2828 			       __func__, (uintmax_t)err_desc->lun_id);
2829 			retval = EINVAL;
2830 			break;
2831 		}
2832 		mtx_lock(&lun->lun_lock);
2833 		mtx_unlock(&softc->ctl_lock);
2834 
2835 		/*
2836 		 * We could do some checking here to verify the validity
2837 		 * of the request, but given the complexity of error
2838 		 * injection requests, the checking logic would be fairly
2839 		 * complex.
2840 		 *
2841 		 * For now, if the request is invalid, it just won't get
2842 		 * executed and might get deleted.
2843 		 */
2844 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2845 
2846 		/*
2847 		 * XXX KDM check to make sure the serial number is unique,
2848 		 * in case we somehow manage to wrap.  That shouldn't
2849 		 * happen for a very long time, but it's the right thing to
2850 		 * do.
2851 		 */
2852 		new_err_desc->serial = lun->error_serial;
2853 		err_desc->serial = lun->error_serial;
2854 		lun->error_serial++;
2855 
2856 		mtx_unlock(&lun->lun_lock);
2857 		break;
2858 	}
2859 	case CTL_ERROR_INJECT_DELETE: {
2860 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2861 		int delete_done;
2862 
2863 		delete_desc = (struct ctl_error_desc *)addr;
2864 		delete_done = 0;
2865 
2866 		mtx_lock(&softc->ctl_lock);
2867 		if (delete_desc->lun_id >= ctl_max_luns ||
2868 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2869 			mtx_unlock(&softc->ctl_lock);
2870 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2871 			       __func__, (uintmax_t)delete_desc->lun_id);
2872 			retval = EINVAL;
2873 			break;
2874 		}
2875 		mtx_lock(&lun->lun_lock);
2876 		mtx_unlock(&softc->ctl_lock);
2877 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2878 			if (desc->serial != delete_desc->serial)
2879 				continue;
2880 
2881 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2882 				      links);
2883 			free(desc, M_CTL);
2884 			delete_done = 1;
2885 		}
2886 		mtx_unlock(&lun->lun_lock);
2887 		if (delete_done == 0) {
2888 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2889 			       "error serial %ju on LUN %u\n", __func__,
2890 			       delete_desc->serial, delete_desc->lun_id);
2891 			retval = EINVAL;
2892 			break;
2893 		}
2894 		break;
2895 	}
2896 	case CTL_DUMP_STRUCTS: {
2897 		int j, k;
2898 		struct ctl_port *port;
2899 		struct ctl_frontend *fe;
2900 
2901 		mtx_lock(&softc->ctl_lock);
2902 		printf("CTL Persistent Reservation information start:\n");
2903 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2904 			mtx_lock(&lun->lun_lock);
2905 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2906 				mtx_unlock(&lun->lun_lock);
2907 				continue;
2908 			}
2909 
2910 			for (j = 0; j < ctl_max_ports; j++) {
2911 				if (lun->pr_keys[j] == NULL)
2912 					continue;
2913 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2914 					if (lun->pr_keys[j][k] == 0)
2915 						continue;
2916 					printf("  LUN %ju port %d iid %d key "
2917 					       "%#jx\n", lun->lun, j, k,
2918 					       (uintmax_t)lun->pr_keys[j][k]);
2919 				}
2920 			}
2921 			mtx_unlock(&lun->lun_lock);
2922 		}
2923 		printf("CTL Persistent Reservation information end\n");
2924 		printf("CTL Ports:\n");
2925 		STAILQ_FOREACH(port, &softc->port_list, links) {
2926 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2927 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2928 			       port->frontend->name, port->port_type,
2929 			       port->physical_port, port->virtual_port,
2930 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2931 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2932 				if (port->wwpn_iid[j].in_use == 0 &&
2933 				    port->wwpn_iid[j].wwpn == 0 &&
2934 				    port->wwpn_iid[j].name == NULL)
2935 					continue;
2936 
2937 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2938 				    j, port->wwpn_iid[j].in_use,
2939 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2940 				    port->wwpn_iid[j].name);
2941 			}
2942 		}
2943 		printf("CTL Port information end\n");
2944 		mtx_unlock(&softc->ctl_lock);
2945 		/*
2946 		 * XXX KDM calling this without a lock.  We'd likely want
2947 		 * to drop the lock before calling the frontend's dump
2948 		 * routine anyway.
2949 		 */
2950 		printf("CTL Frontends:\n");
2951 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2952 			printf("  Frontend '%s'\n", fe->name);
2953 			if (fe->fe_dump != NULL)
2954 				fe->fe_dump();
2955 		}
2956 		printf("CTL Frontend information end\n");
2957 		break;
2958 	}
2959 	case CTL_LUN_REQ: {
2960 		struct ctl_lun_req *lun_req;
2961 		struct ctl_backend_driver *backend;
2962 		void *packed;
2963 		nvlist_t *tmp_args_nvl;
2964 		size_t packed_len;
2965 
2966 		lun_req = (struct ctl_lun_req *)addr;
2967 		tmp_args_nvl = lun_req->args_nvl;
2968 
2969 		backend = ctl_backend_find(lun_req->backend);
2970 		if (backend == NULL) {
2971 			lun_req->status = CTL_LUN_ERROR;
2972 			snprintf(lun_req->error_str,
2973 				 sizeof(lun_req->error_str),
2974 				 "Backend \"%s\" not found.",
2975 				 lun_req->backend);
2976 			break;
2977 		}
2978 
2979 		if (lun_req->args != NULL) {
2980 			if (lun_req->args_len > CTL_MAX_ARGS_LEN) {
2981 				lun_req->status = CTL_LUN_ERROR;
2982 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2983 				    "Too big args.");
2984 				break;
2985 			}
2986 			packed = malloc(lun_req->args_len, M_CTL, M_WAITOK);
2987 			if (copyin(lun_req->args, packed, lun_req->args_len) != 0) {
2988 				free(packed, M_CTL);
2989 				lun_req->status = CTL_LUN_ERROR;
2990 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2991 				    "Cannot copyin args.");
2992 				break;
2993 			}
2994 			lun_req->args_nvl = nvlist_unpack(packed,
2995 			    lun_req->args_len, 0);
2996 			free(packed, M_CTL);
2997 
2998 			if (lun_req->args_nvl == NULL) {
2999 				lun_req->status = CTL_LUN_ERROR;
3000 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
3001 				    "Cannot unpack args nvlist.");
3002 				break;
3003 			}
3004 		} else
3005 			lun_req->args_nvl = nvlist_create(0);
3006 
3007 		lun_req->result_nvl = NULL;
3008 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3009 		nvlist_destroy(lun_req->args_nvl);
3010 		lun_req->args_nvl = tmp_args_nvl;
3011 
3012 		if (lun_req->result_nvl != NULL) {
3013 			if (lun_req->result != NULL) {
3014 				packed = nvlist_pack(lun_req->result_nvl,
3015 				    &packed_len);
3016 				if (packed == NULL) {
3017 					lun_req->status = CTL_LUN_ERROR;
3018 					snprintf(lun_req->error_str,
3019 					    sizeof(lun_req->error_str),
3020 					    "Cannot pack result nvlist.");
3021 					break;
3022 				}
3023 
3024 				if (packed_len > lun_req->result_len) {
3025 					lun_req->status = CTL_LUN_ERROR;
3026 					snprintf(lun_req->error_str,
3027 					    sizeof(lun_req->error_str),
3028 					    "Result nvlist too large.");
3029 					free(packed, M_NVLIST);
3030 					break;
3031 				}
3032 
3033 				if (copyout(packed, lun_req->result, packed_len)) {
3034 					lun_req->status = CTL_LUN_ERROR;
3035 					snprintf(lun_req->error_str,
3036 					    sizeof(lun_req->error_str),
3037 					    "Cannot copyout() the result.");
3038 					free(packed, M_NVLIST);
3039 					break;
3040 				}
3041 
3042 				lun_req->result_len = packed_len;
3043 				free(packed, M_NVLIST);
3044 			}
3045 
3046 			nvlist_destroy(lun_req->result_nvl);
3047 		}
3048 		break;
3049 	}
3050 	case CTL_LUN_LIST: {
3051 		struct sbuf *sb;
3052 		struct ctl_lun_list *list;
3053 		const char *name, *value;
3054 		void *cookie;
3055 		int type;
3056 
3057 		list = (struct ctl_lun_list *)addr;
3058 
3059 		/*
3060 		 * Allocate a fixed length sbuf here, based on the length
3061 		 * of the user's buffer.  We could allocate an auto-extending
3062 		 * buffer, and then tell the user how much larger our
3063 		 * amount of data is than his buffer, but that presents
3064 		 * some problems:
3065 		 *
3066 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3067 		 *     we can't hold a lock while calling them with an
3068 		 *     auto-extending buffer.
3069  		 *
3070 		 * 2.  There is not currently a LUN reference counting
3071 		 *     mechanism, outside of outstanding transactions on
3072 		 *     the LUN's OOA queue.  So a LUN could go away on us
3073 		 *     while we're getting the LUN number, backend-specific
3074 		 *     information, etc.  Thus, given the way things
3075 		 *     currently work, we need to hold the CTL lock while
3076 		 *     grabbing LUN information.
3077 		 *
3078 		 * So, from the user's standpoint, the best thing to do is
3079 		 * allocate what he thinks is a reasonable buffer length,
3080 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3081 		 * double the buffer length and try again.  (And repeat
3082 		 * that until he succeeds.)
3083 		 */
3084 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3085 		if (sb == NULL) {
3086 			list->status = CTL_LUN_LIST_ERROR;
3087 			snprintf(list->error_str, sizeof(list->error_str),
3088 				 "Unable to allocate %d bytes for LUN list",
3089 				 list->alloc_len);
3090 			break;
3091 		}
3092 
3093 		sbuf_printf(sb, "<ctllunlist>\n");
3094 
3095 		mtx_lock(&softc->ctl_lock);
3096 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3097 			mtx_lock(&lun->lun_lock);
3098 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3099 					     (uintmax_t)lun->lun);
3100 
3101 			/*
3102 			 * Bail out as soon as we see that we've overfilled
3103 			 * the buffer.
3104 			 */
3105 			if (retval != 0)
3106 				break;
3107 
3108 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3109 					     "</backend_type>\n",
3110 					     (lun->backend == NULL) ?  "none" :
3111 					     lun->backend->name);
3112 
3113 			if (retval != 0)
3114 				break;
3115 
3116 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3117 					     lun->be_lun->lun_type);
3118 
3119 			if (retval != 0)
3120 				break;
3121 
3122 			if (lun->backend == NULL) {
3123 				retval = sbuf_printf(sb, "</lun>\n");
3124 				if (retval != 0)
3125 					break;
3126 				continue;
3127 			}
3128 
3129 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3130 					     (lun->be_lun->maxlba > 0) ?
3131 					     lun->be_lun->maxlba + 1 : 0);
3132 
3133 			if (retval != 0)
3134 				break;
3135 
3136 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3137 					     lun->be_lun->blocksize);
3138 
3139 			if (retval != 0)
3140 				break;
3141 
3142 			retval = sbuf_printf(sb, "\t<serial_number>");
3143 
3144 			if (retval != 0)
3145 				break;
3146 
3147 			retval = ctl_sbuf_printf_esc(sb,
3148 			    lun->be_lun->serial_num,
3149 			    sizeof(lun->be_lun->serial_num));
3150 
3151 			if (retval != 0)
3152 				break;
3153 
3154 			retval = sbuf_printf(sb, "</serial_number>\n");
3155 
3156 			if (retval != 0)
3157 				break;
3158 
3159 			retval = sbuf_printf(sb, "\t<device_id>");
3160 
3161 			if (retval != 0)
3162 				break;
3163 
3164 			retval = ctl_sbuf_printf_esc(sb,
3165 			    lun->be_lun->device_id,
3166 			    sizeof(lun->be_lun->device_id));
3167 
3168 			if (retval != 0)
3169 				break;
3170 
3171 			retval = sbuf_printf(sb, "</device_id>\n");
3172 
3173 			if (retval != 0)
3174 				break;
3175 
3176 			if (lun->backend->lun_info != NULL) {
3177 				retval = lun->backend->lun_info(lun->be_lun, sb);
3178 				if (retval != 0)
3179 					break;
3180 			}
3181 
3182 			cookie = NULL;
3183 			while ((name = nvlist_next(lun->be_lun->options, &type,
3184 			    &cookie)) != NULL) {
3185 				sbuf_printf(sb, "\t<%s>", name);
3186 
3187 				if (type == NV_TYPE_STRING) {
3188 					value = dnvlist_get_string(
3189 					    lun->be_lun->options, name, NULL);
3190 					if (value != NULL)
3191 						sbuf_printf(sb, "%s", value);
3192 				}
3193 
3194 				sbuf_printf(sb, "</%s>\n", name);
3195 			}
3196 
3197 			retval = sbuf_printf(sb, "</lun>\n");
3198 
3199 			if (retval != 0)
3200 				break;
3201 			mtx_unlock(&lun->lun_lock);
3202 		}
3203 		if (lun != NULL)
3204 			mtx_unlock(&lun->lun_lock);
3205 		mtx_unlock(&softc->ctl_lock);
3206 
3207 		if ((retval != 0)
3208 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3209 			retval = 0;
3210 			sbuf_delete(sb);
3211 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3212 			snprintf(list->error_str, sizeof(list->error_str),
3213 				 "Out of space, %d bytes is too small",
3214 				 list->alloc_len);
3215 			break;
3216 		}
3217 
3218 		sbuf_finish(sb);
3219 
3220 		retval = copyout(sbuf_data(sb), list->lun_xml,
3221 				 sbuf_len(sb) + 1);
3222 
3223 		list->fill_len = sbuf_len(sb) + 1;
3224 		list->status = CTL_LUN_LIST_OK;
3225 		sbuf_delete(sb);
3226 		break;
3227 	}
3228 	case CTL_ISCSI: {
3229 		struct ctl_iscsi *ci;
3230 		struct ctl_frontend *fe;
3231 
3232 		ci = (struct ctl_iscsi *)addr;
3233 
3234 		fe = ctl_frontend_find("iscsi");
3235 		if (fe == NULL) {
3236 			ci->status = CTL_ISCSI_ERROR;
3237 			snprintf(ci->error_str, sizeof(ci->error_str),
3238 			    "Frontend \"iscsi\" not found.");
3239 			break;
3240 		}
3241 
3242 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3243 		break;
3244 	}
3245 	case CTL_PORT_REQ: {
3246 		struct ctl_req *req;
3247 		struct ctl_frontend *fe;
3248 		void *packed;
3249 		nvlist_t *tmp_args_nvl;
3250 		size_t packed_len;
3251 
3252 		req = (struct ctl_req *)addr;
3253 		tmp_args_nvl = req->args_nvl;
3254 
3255 		fe = ctl_frontend_find(req->driver);
3256 		if (fe == NULL) {
3257 			req->status = CTL_LUN_ERROR;
3258 			snprintf(req->error_str, sizeof(req->error_str),
3259 			    "Frontend \"%s\" not found.", req->driver);
3260 			break;
3261 		}
3262 
3263 		if (req->args != NULL) {
3264 			if (req->args_len > CTL_MAX_ARGS_LEN) {
3265 				req->status = CTL_LUN_ERROR;
3266 				snprintf(req->error_str, sizeof(req->error_str),
3267 				    "Too big args.");
3268 				break;
3269 			}
3270 			packed = malloc(req->args_len, M_CTL, M_WAITOK);
3271 			if (copyin(req->args, packed, req->args_len) != 0) {
3272 				free(packed, M_CTL);
3273 				req->status = CTL_LUN_ERROR;
3274 				snprintf(req->error_str, sizeof(req->error_str),
3275 				    "Cannot copyin args.");
3276 				break;
3277 			}
3278 			req->args_nvl = nvlist_unpack(packed,
3279 			    req->args_len, 0);
3280 			free(packed, M_CTL);
3281 
3282 			if (req->args_nvl == NULL) {
3283 				req->status = CTL_LUN_ERROR;
3284 				snprintf(req->error_str, sizeof(req->error_str),
3285 				    "Cannot unpack args nvlist.");
3286 				break;
3287 			}
3288 		} else
3289 			req->args_nvl = nvlist_create(0);
3290 
3291 		req->result_nvl = NULL;
3292 		if (fe->ioctl)
3293 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3294 		else
3295 			retval = ENODEV;
3296 
3297 		nvlist_destroy(req->args_nvl);
3298 		req->args_nvl = tmp_args_nvl;
3299 
3300 		if (req->result_nvl != NULL) {
3301 			if (req->result != NULL) {
3302 				packed = nvlist_pack(req->result_nvl,
3303 				    &packed_len);
3304 				if (packed == NULL) {
3305 					req->status = CTL_LUN_ERROR;
3306 					snprintf(req->error_str,
3307 					    sizeof(req->error_str),
3308 					    "Cannot pack result nvlist.");
3309 					break;
3310 				}
3311 
3312 				if (packed_len > req->result_len) {
3313 					req->status = CTL_LUN_ERROR;
3314 					snprintf(req->error_str,
3315 					    sizeof(req->error_str),
3316 					    "Result nvlist too large.");
3317 					free(packed, M_NVLIST);
3318 					break;
3319 				}
3320 
3321 				if (copyout(packed, req->result, packed_len)) {
3322 					req->status = CTL_LUN_ERROR;
3323 					snprintf(req->error_str,
3324 					    sizeof(req->error_str),
3325 					    "Cannot copyout() the result.");
3326 					free(packed, M_NVLIST);
3327 					break;
3328 				}
3329 
3330 				req->result_len = packed_len;
3331 				free(packed, M_NVLIST);
3332 			}
3333 
3334 			nvlist_destroy(req->result_nvl);
3335 		}
3336 		break;
3337 	}
3338 	case CTL_PORT_LIST: {
3339 		struct sbuf *sb;
3340 		struct ctl_port *port;
3341 		struct ctl_lun_list *list;
3342 		const char *name, *value;
3343 		void *cookie;
3344 		int j, type;
3345 		uint32_t plun;
3346 
3347 		list = (struct ctl_lun_list *)addr;
3348 
3349 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3350 		if (sb == NULL) {
3351 			list->status = CTL_LUN_LIST_ERROR;
3352 			snprintf(list->error_str, sizeof(list->error_str),
3353 				 "Unable to allocate %d bytes for LUN list",
3354 				 list->alloc_len);
3355 			break;
3356 		}
3357 
3358 		sbuf_printf(sb, "<ctlportlist>\n");
3359 
3360 		mtx_lock(&softc->ctl_lock);
3361 		STAILQ_FOREACH(port, &softc->port_list, links) {
3362 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3363 					     (uintmax_t)port->targ_port);
3364 
3365 			/*
3366 			 * Bail out as soon as we see that we've overfilled
3367 			 * the buffer.
3368 			 */
3369 			if (retval != 0)
3370 				break;
3371 
3372 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3373 			    "</frontend_type>\n", port->frontend->name);
3374 			if (retval != 0)
3375 				break;
3376 
3377 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3378 					     port->port_type);
3379 			if (retval != 0)
3380 				break;
3381 
3382 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3383 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3384 			if (retval != 0)
3385 				break;
3386 
3387 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3388 			    port->port_name);
3389 			if (retval != 0)
3390 				break;
3391 
3392 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3393 			    port->physical_port);
3394 			if (retval != 0)
3395 				break;
3396 
3397 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3398 			    port->virtual_port);
3399 			if (retval != 0)
3400 				break;
3401 
3402 			if (port->target_devid != NULL) {
3403 				sbuf_printf(sb, "\t<target>");
3404 				ctl_id_sbuf(port->target_devid, sb);
3405 				sbuf_printf(sb, "</target>\n");
3406 			}
3407 
3408 			if (port->port_devid != NULL) {
3409 				sbuf_printf(sb, "\t<port>");
3410 				ctl_id_sbuf(port->port_devid, sb);
3411 				sbuf_printf(sb, "</port>\n");
3412 			}
3413 
3414 			if (port->port_info != NULL) {
3415 				retval = port->port_info(port->onoff_arg, sb);
3416 				if (retval != 0)
3417 					break;
3418 			}
3419 
3420 			cookie = NULL;
3421 			while ((name = nvlist_next(port->options, &type,
3422 			    &cookie)) != NULL) {
3423 				sbuf_printf(sb, "\t<%s>", name);
3424 
3425 				if (type == NV_TYPE_STRING) {
3426 					value = dnvlist_get_string(port->options,
3427 					    name, NULL);
3428 					if (value != NULL)
3429 						sbuf_printf(sb, "%s", value);
3430 				}
3431 
3432 				sbuf_printf(sb, "</%s>\n", name);
3433 			}
3434 
3435 			if (port->lun_map != NULL) {
3436 				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3437 				for (j = 0; j < port->lun_map_size; j++) {
3438 					plun = ctl_lun_map_from_port(port, j);
3439 					if (plun == UINT32_MAX)
3440 						continue;
3441 					sbuf_printf(sb,
3442 					    "\t<lun id=\"%u\">%u</lun>\n",
3443 					    j, plun);
3444 				}
3445 			}
3446 
3447 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3448 				if (port->wwpn_iid[j].in_use == 0 ||
3449 				    (port->wwpn_iid[j].wwpn == 0 &&
3450 				     port->wwpn_iid[j].name == NULL))
3451 					continue;
3452 
3453 				if (port->wwpn_iid[j].name != NULL)
3454 					retval = sbuf_printf(sb,
3455 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3456 					    j, port->wwpn_iid[j].name);
3457 				else
3458 					retval = sbuf_printf(sb,
3459 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3460 					    j, port->wwpn_iid[j].wwpn);
3461 				if (retval != 0)
3462 					break;
3463 			}
3464 			if (retval != 0)
3465 				break;
3466 
3467 			retval = sbuf_printf(sb, "</targ_port>\n");
3468 			if (retval != 0)
3469 				break;
3470 		}
3471 		mtx_unlock(&softc->ctl_lock);
3472 
3473 		if ((retval != 0)
3474 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3475 			retval = 0;
3476 			sbuf_delete(sb);
3477 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3478 			snprintf(list->error_str, sizeof(list->error_str),
3479 				 "Out of space, %d bytes is too small",
3480 				 list->alloc_len);
3481 			break;
3482 		}
3483 
3484 		sbuf_finish(sb);
3485 
3486 		retval = copyout(sbuf_data(sb), list->lun_xml,
3487 				 sbuf_len(sb) + 1);
3488 
3489 		list->fill_len = sbuf_len(sb) + 1;
3490 		list->status = CTL_LUN_LIST_OK;
3491 		sbuf_delete(sb);
3492 		break;
3493 	}
3494 	case CTL_LUN_MAP: {
3495 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3496 		struct ctl_port *port;
3497 
3498 		mtx_lock(&softc->ctl_lock);
3499 		if (lm->port < softc->port_min ||
3500 		    lm->port >= softc->port_max ||
3501 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3502 			mtx_unlock(&softc->ctl_lock);
3503 			return (ENXIO);
3504 		}
3505 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3506 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3507 				if (ctl_lun_map_to_port(port, lun->lun) ==
3508 				    UINT32_MAX)
3509 					continue;
3510 				mtx_lock(&lun->lun_lock);
3511 				ctl_est_ua_port(lun, lm->port, -1,
3512 				    CTL_UA_LUN_CHANGE);
3513 				mtx_unlock(&lun->lun_lock);
3514 			}
3515 		}
3516 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3517 		if (lm->plun != UINT32_MAX) {
3518 			if (lm->lun == UINT32_MAX)
3519 				retval = ctl_lun_map_unset(port, lm->plun);
3520 			else if (lm->lun < ctl_max_luns &&
3521 			    softc->ctl_luns[lm->lun] != NULL)
3522 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3523 			else
3524 				return (ENXIO);
3525 		} else {
3526 			if (lm->lun == UINT32_MAX)
3527 				retval = ctl_lun_map_deinit(port);
3528 			else
3529 				retval = ctl_lun_map_init(port);
3530 		}
3531 		if (port->status & CTL_PORT_STATUS_ONLINE)
3532 			ctl_isc_announce_port(port);
3533 		break;
3534 	}
3535 	case CTL_GET_LUN_STATS: {
3536 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3537 		int i;
3538 
3539 		/*
3540 		 * XXX KDM no locking here.  If the LUN list changes,
3541 		 * things can blow up.
3542 		 */
3543 		i = 0;
3544 		stats->status = CTL_SS_OK;
3545 		stats->fill_len = 0;
3546 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3547 			if (lun->lun < stats->first_item)
3548 				continue;
3549 			if (stats->fill_len + sizeof(lun->stats) >
3550 			    stats->alloc_len) {
3551 				stats->status = CTL_SS_NEED_MORE_SPACE;
3552 				break;
3553 			}
3554 			retval = copyout(&lun->stats, &stats->stats[i++],
3555 					 sizeof(lun->stats));
3556 			if (retval != 0)
3557 				break;
3558 			stats->fill_len += sizeof(lun->stats);
3559 		}
3560 		stats->num_items = softc->num_luns;
3561 		stats->flags = CTL_STATS_FLAG_NONE;
3562 #ifdef CTL_TIME_IO
3563 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3564 #endif
3565 		getnanouptime(&stats->timestamp);
3566 		break;
3567 	}
3568 	case CTL_GET_PORT_STATS: {
3569 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3570 		int i;
3571 
3572 		/*
3573 		 * XXX KDM no locking here.  If the LUN list changes,
3574 		 * things can blow up.
3575 		 */
3576 		i = 0;
3577 		stats->status = CTL_SS_OK;
3578 		stats->fill_len = 0;
3579 		STAILQ_FOREACH(port, &softc->port_list, links) {
3580 			if (port->targ_port < stats->first_item)
3581 				continue;
3582 			if (stats->fill_len + sizeof(port->stats) >
3583 			    stats->alloc_len) {
3584 				stats->status = CTL_SS_NEED_MORE_SPACE;
3585 				break;
3586 			}
3587 			retval = copyout(&port->stats, &stats->stats[i++],
3588 					 sizeof(port->stats));
3589 			if (retval != 0)
3590 				break;
3591 			stats->fill_len += sizeof(port->stats);
3592 		}
3593 		stats->num_items = softc->num_ports;
3594 		stats->flags = CTL_STATS_FLAG_NONE;
3595 #ifdef CTL_TIME_IO
3596 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3597 #endif
3598 		getnanouptime(&stats->timestamp);
3599 		break;
3600 	}
3601 	default: {
3602 		/* XXX KDM should we fix this? */
3603 #if 0
3604 		struct ctl_backend_driver *backend;
3605 		unsigned int type;
3606 		int found;
3607 
3608 		found = 0;
3609 
3610 		/*
3611 		 * We encode the backend type as the ioctl type for backend
3612 		 * ioctls.  So parse it out here, and then search for a
3613 		 * backend of this type.
3614 		 */
3615 		type = _IOC_TYPE(cmd);
3616 
3617 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3618 			if (backend->type == type) {
3619 				found = 1;
3620 				break;
3621 			}
3622 		}
3623 		if (found == 0) {
3624 			printf("ctl: unknown ioctl command %#lx or backend "
3625 			       "%d\n", cmd, type);
3626 			retval = EINVAL;
3627 			break;
3628 		}
3629 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3630 #endif
3631 		retval = ENOTTY;
3632 		break;
3633 	}
3634 	}
3635 	return (retval);
3636 }
3637 
3638 uint32_t
3639 ctl_get_initindex(struct ctl_nexus *nexus)
3640 {
3641 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3642 }
3643 
3644 int
3645 ctl_lun_map_init(struct ctl_port *port)
3646 {
3647 	struct ctl_softc *softc = port->ctl_softc;
3648 	struct ctl_lun *lun;
3649 	int size = ctl_lun_map_size;
3650 	uint32_t i;
3651 
3652 	if (port->lun_map == NULL || port->lun_map_size < size) {
3653 		port->lun_map_size = 0;
3654 		free(port->lun_map, M_CTL);
3655 		port->lun_map = malloc(size * sizeof(uint32_t),
3656 		    M_CTL, M_NOWAIT);
3657 	}
3658 	if (port->lun_map == NULL)
3659 		return (ENOMEM);
3660 	for (i = 0; i < size; i++)
3661 		port->lun_map[i] = UINT32_MAX;
3662 	port->lun_map_size = size;
3663 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3664 		if (port->lun_disable != NULL) {
3665 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3666 				port->lun_disable(port->targ_lun_arg, lun->lun);
3667 		}
3668 		ctl_isc_announce_port(port);
3669 	}
3670 	return (0);
3671 }
3672 
3673 int
3674 ctl_lun_map_deinit(struct ctl_port *port)
3675 {
3676 	struct ctl_softc *softc = port->ctl_softc;
3677 	struct ctl_lun *lun;
3678 
3679 	if (port->lun_map == NULL)
3680 		return (0);
3681 	port->lun_map_size = 0;
3682 	free(port->lun_map, M_CTL);
3683 	port->lun_map = NULL;
3684 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3685 		if (port->lun_enable != NULL) {
3686 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3687 				port->lun_enable(port->targ_lun_arg, lun->lun);
3688 		}
3689 		ctl_isc_announce_port(port);
3690 	}
3691 	return (0);
3692 }
3693 
3694 int
3695 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3696 {
3697 	int status;
3698 	uint32_t old;
3699 
3700 	if (port->lun_map == NULL) {
3701 		status = ctl_lun_map_init(port);
3702 		if (status != 0)
3703 			return (status);
3704 	}
3705 	if (plun >= port->lun_map_size)
3706 		return (EINVAL);
3707 	old = port->lun_map[plun];
3708 	port->lun_map[plun] = glun;
3709 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3710 		if (port->lun_enable != NULL)
3711 			port->lun_enable(port->targ_lun_arg, plun);
3712 		ctl_isc_announce_port(port);
3713 	}
3714 	return (0);
3715 }
3716 
3717 int
3718 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3719 {
3720 	uint32_t old;
3721 
3722 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3723 		return (0);
3724 	old = port->lun_map[plun];
3725 	port->lun_map[plun] = UINT32_MAX;
3726 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3727 		if (port->lun_disable != NULL)
3728 			port->lun_disable(port->targ_lun_arg, plun);
3729 		ctl_isc_announce_port(port);
3730 	}
3731 	return (0);
3732 }
3733 
3734 uint32_t
3735 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3736 {
3737 
3738 	if (port == NULL)
3739 		return (UINT32_MAX);
3740 	if (port->lun_map == NULL)
3741 		return (lun_id);
3742 	if (lun_id > port->lun_map_size)
3743 		return (UINT32_MAX);
3744 	return (port->lun_map[lun_id]);
3745 }
3746 
3747 uint32_t
3748 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3749 {
3750 	uint32_t i;
3751 
3752 	if (port == NULL)
3753 		return (UINT32_MAX);
3754 	if (port->lun_map == NULL)
3755 		return (lun_id);
3756 	for (i = 0; i < port->lun_map_size; i++) {
3757 		if (port->lun_map[i] == lun_id)
3758 			return (i);
3759 	}
3760 	return (UINT32_MAX);
3761 }
3762 
3763 uint32_t
3764 ctl_decode_lun(uint64_t encoded)
3765 {
3766 	uint8_t lun[8];
3767 	uint32_t result = 0xffffffff;
3768 
3769 	be64enc(lun, encoded);
3770 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3771 	case RPL_LUNDATA_ATYP_PERIPH:
3772 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3773 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3774 			result = lun[1];
3775 		break;
3776 	case RPL_LUNDATA_ATYP_FLAT:
3777 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3778 		    lun[6] == 0 && lun[7] == 0)
3779 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3780 		break;
3781 	case RPL_LUNDATA_ATYP_EXTLUN:
3782 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3783 		case 0x02:
3784 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3785 			case 0x00:
3786 				result = lun[1];
3787 				break;
3788 			case 0x10:
3789 				result = (lun[1] << 16) + (lun[2] << 8) +
3790 				    lun[3];
3791 				break;
3792 			case 0x20:
3793 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3794 					result = (lun[2] << 24) +
3795 					    (lun[3] << 16) + (lun[4] << 8) +
3796 					    lun[5];
3797 				break;
3798 			}
3799 			break;
3800 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3801 			result = 0xffffffff;
3802 			break;
3803 		}
3804 		break;
3805 	}
3806 	return (result);
3807 }
3808 
3809 uint64_t
3810 ctl_encode_lun(uint32_t decoded)
3811 {
3812 	uint64_t l = decoded;
3813 
3814 	if (l <= 0xff)
3815 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3816 	if (l <= 0x3fff)
3817 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3818 	if (l <= 0xffffff)
3819 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3820 		    (l << 32));
3821 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3822 }
3823 
3824 int
3825 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3826 {
3827 	int i;
3828 
3829 	for (i = first; i < last; i++) {
3830 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3831 			return (i);
3832 	}
3833 	return (-1);
3834 }
3835 
3836 int
3837 ctl_set_mask(uint32_t *mask, uint32_t bit)
3838 {
3839 	uint32_t chunk, piece;
3840 
3841 	chunk = bit >> 5;
3842 	piece = bit % (sizeof(uint32_t) * 8);
3843 
3844 	if ((mask[chunk] & (1 << piece)) != 0)
3845 		return (-1);
3846 	else
3847 		mask[chunk] |= (1 << piece);
3848 
3849 	return (0);
3850 }
3851 
3852 int
3853 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3854 {
3855 	uint32_t chunk, piece;
3856 
3857 	chunk = bit >> 5;
3858 	piece = bit % (sizeof(uint32_t) * 8);
3859 
3860 	if ((mask[chunk] & (1 << piece)) == 0)
3861 		return (-1);
3862 	else
3863 		mask[chunk] &= ~(1 << piece);
3864 
3865 	return (0);
3866 }
3867 
3868 int
3869 ctl_is_set(uint32_t *mask, uint32_t bit)
3870 {
3871 	uint32_t chunk, piece;
3872 
3873 	chunk = bit >> 5;
3874 	piece = bit % (sizeof(uint32_t) * 8);
3875 
3876 	if ((mask[chunk] & (1 << piece)) == 0)
3877 		return (0);
3878 	else
3879 		return (1);
3880 }
3881 
3882 static uint64_t
3883 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3884 {
3885 	uint64_t *t;
3886 
3887 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3888 	if (t == NULL)
3889 		return (0);
3890 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3891 }
3892 
3893 static void
3894 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3895 {
3896 	uint64_t *t;
3897 
3898 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3899 	if (t == NULL)
3900 		return;
3901 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3902 }
3903 
3904 static void
3905 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3906 {
3907 	uint64_t *p;
3908 	u_int i;
3909 
3910 	i = residx/CTL_MAX_INIT_PER_PORT;
3911 	if (lun->pr_keys[i] != NULL)
3912 		return;
3913 	mtx_unlock(&lun->lun_lock);
3914 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3915 	    M_WAITOK | M_ZERO);
3916 	mtx_lock(&lun->lun_lock);
3917 	if (lun->pr_keys[i] == NULL)
3918 		lun->pr_keys[i] = p;
3919 	else
3920 		free(p, M_CTL);
3921 }
3922 
3923 static void
3924 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3925 {
3926 	uint64_t *t;
3927 
3928 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3929 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3930 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3931 }
3932 
3933 /*
3934  * ctl_softc, pool_name, total_ctl_io are passed in.
3935  * npool is passed out.
3936  */
3937 int
3938 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3939 		uint32_t total_ctl_io, void **npool)
3940 {
3941 	struct ctl_io_pool *pool;
3942 
3943 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3944 					    M_NOWAIT | M_ZERO);
3945 	if (pool == NULL)
3946 		return (ENOMEM);
3947 
3948 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3949 	pool->ctl_softc = ctl_softc;
3950 #ifdef IO_POOLS
3951 	pool->zone = uma_zsecond_create(pool->name, NULL,
3952 	    NULL, NULL, NULL, ctl_softc->io_zone);
3953 	/* uma_prealloc(pool->zone, total_ctl_io); */
3954 #else
3955 	pool->zone = ctl_softc->io_zone;
3956 #endif
3957 
3958 	*npool = pool;
3959 	return (0);
3960 }
3961 
3962 void
3963 ctl_pool_free(struct ctl_io_pool *pool)
3964 {
3965 
3966 	if (pool == NULL)
3967 		return;
3968 
3969 #ifdef IO_POOLS
3970 	uma_zdestroy(pool->zone);
3971 #endif
3972 	free(pool, M_CTL);
3973 }
3974 
3975 union ctl_io *
3976 ctl_alloc_io(void *pool_ref)
3977 {
3978 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3979 	union ctl_io *io;
3980 
3981 	io = uma_zalloc(pool->zone, M_WAITOK);
3982 	if (io != NULL) {
3983 		io->io_hdr.pool = pool_ref;
3984 		CTL_SOFTC(io) = pool->ctl_softc;
3985 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3986 	}
3987 	return (io);
3988 }
3989 
3990 union ctl_io *
3991 ctl_alloc_io_nowait(void *pool_ref)
3992 {
3993 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3994 	union ctl_io *io;
3995 
3996 	io = uma_zalloc(pool->zone, M_NOWAIT);
3997 	if (io != NULL) {
3998 		io->io_hdr.pool = pool_ref;
3999 		CTL_SOFTC(io) = pool->ctl_softc;
4000 		TAILQ_INIT(&io->io_hdr.blocked_queue);
4001 	}
4002 	return (io);
4003 }
4004 
4005 void
4006 ctl_free_io(union ctl_io *io)
4007 {
4008 	struct ctl_io_pool *pool;
4009 
4010 	if (io == NULL)
4011 		return;
4012 
4013 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
4014 	uma_zfree(pool->zone, io);
4015 }
4016 
4017 void
4018 ctl_zero_io(union ctl_io *io)
4019 {
4020 	struct ctl_io_pool *pool;
4021 
4022 	if (io == NULL)
4023 		return;
4024 
4025 	/*
4026 	 * May need to preserve linked list pointers at some point too.
4027 	 */
4028 	pool = io->io_hdr.pool;
4029 	memset(io, 0, sizeof(*io));
4030 	io->io_hdr.pool = pool;
4031 	CTL_SOFTC(io) = pool->ctl_softc;
4032 	TAILQ_INIT(&io->io_hdr.blocked_queue);
4033 }
4034 
4035 int
4036 ctl_expand_number(const char *buf, uint64_t *num)
4037 {
4038 	char *endptr;
4039 	uint64_t number;
4040 	unsigned shift;
4041 
4042 	number = strtoq(buf, &endptr, 0);
4043 
4044 	switch (tolower((unsigned char)*endptr)) {
4045 	case 'e':
4046 		shift = 60;
4047 		break;
4048 	case 'p':
4049 		shift = 50;
4050 		break;
4051 	case 't':
4052 		shift = 40;
4053 		break;
4054 	case 'g':
4055 		shift = 30;
4056 		break;
4057 	case 'm':
4058 		shift = 20;
4059 		break;
4060 	case 'k':
4061 		shift = 10;
4062 		break;
4063 	case 'b':
4064 	case '\0': /* No unit. */
4065 		*num = number;
4066 		return (0);
4067 	default:
4068 		/* Unrecognized unit. */
4069 		return (-1);
4070 	}
4071 
4072 	if ((number << shift) >> shift != number) {
4073 		/* Overflow */
4074 		return (-1);
4075 	}
4076 	*num = number << shift;
4077 	return (0);
4078 }
4079 
4080 /*
4081  * This routine could be used in the future to load default and/or saved
4082  * mode page parameters for a particuar lun.
4083  */
4084 static int
4085 ctl_init_page_index(struct ctl_lun *lun)
4086 {
4087 	int i, page_code;
4088 	struct ctl_page_index *page_index;
4089 	const char *value;
4090 	uint64_t ival;
4091 
4092 	memcpy(&lun->mode_pages.index, page_index_template,
4093 	       sizeof(page_index_template));
4094 
4095 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4096 		page_index = &lun->mode_pages.index[i];
4097 		if (lun->be_lun->lun_type == T_DIRECT &&
4098 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4099 			continue;
4100 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4101 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4102 			continue;
4103 		if (lun->be_lun->lun_type == T_CDROM &&
4104 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4105 			continue;
4106 
4107 		page_code = page_index->page_code & SMPH_PC_MASK;
4108 		switch (page_code) {
4109 		case SMS_RW_ERROR_RECOVERY_PAGE: {
4110 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4111 			    ("subpage %#x for page %#x is incorrect!",
4112 			    page_index->subpage, page_code));
4113 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4114 			       &rw_er_page_default,
4115 			       sizeof(rw_er_page_default));
4116 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4117 			       &rw_er_page_changeable,
4118 			       sizeof(rw_er_page_changeable));
4119 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4120 			       &rw_er_page_default,
4121 			       sizeof(rw_er_page_default));
4122 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4123 			       &rw_er_page_default,
4124 			       sizeof(rw_er_page_default));
4125 			page_index->page_data =
4126 				(uint8_t *)lun->mode_pages.rw_er_page;
4127 			break;
4128 		}
4129 		case SMS_FORMAT_DEVICE_PAGE: {
4130 			struct scsi_format_page *format_page;
4131 
4132 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4133 			    ("subpage %#x for page %#x is incorrect!",
4134 			    page_index->subpage, page_code));
4135 
4136 			/*
4137 			 * Sectors per track are set above.  Bytes per
4138 			 * sector need to be set here on a per-LUN basis.
4139 			 */
4140 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4141 			       &format_page_default,
4142 			       sizeof(format_page_default));
4143 			memcpy(&lun->mode_pages.format_page[
4144 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4145 			       sizeof(format_page_changeable));
4146 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4147 			       &format_page_default,
4148 			       sizeof(format_page_default));
4149 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4150 			       &format_page_default,
4151 			       sizeof(format_page_default));
4152 
4153 			format_page = &lun->mode_pages.format_page[
4154 				CTL_PAGE_CURRENT];
4155 			scsi_ulto2b(lun->be_lun->blocksize,
4156 				    format_page->bytes_per_sector);
4157 
4158 			format_page = &lun->mode_pages.format_page[
4159 				CTL_PAGE_DEFAULT];
4160 			scsi_ulto2b(lun->be_lun->blocksize,
4161 				    format_page->bytes_per_sector);
4162 
4163 			format_page = &lun->mode_pages.format_page[
4164 				CTL_PAGE_SAVED];
4165 			scsi_ulto2b(lun->be_lun->blocksize,
4166 				    format_page->bytes_per_sector);
4167 
4168 			page_index->page_data =
4169 				(uint8_t *)lun->mode_pages.format_page;
4170 			break;
4171 		}
4172 		case SMS_RIGID_DISK_PAGE: {
4173 			struct scsi_rigid_disk_page *rigid_disk_page;
4174 			uint32_t sectors_per_cylinder;
4175 			uint64_t cylinders;
4176 #ifndef	__XSCALE__
4177 			int shift;
4178 #endif /* !__XSCALE__ */
4179 
4180 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4181 			    ("subpage %#x for page %#x is incorrect!",
4182 			    page_index->subpage, page_code));
4183 
4184 			/*
4185 			 * Rotation rate and sectors per track are set
4186 			 * above.  We calculate the cylinders here based on
4187 			 * capacity.  Due to the number of heads and
4188 			 * sectors per track we're using, smaller arrays
4189 			 * may turn out to have 0 cylinders.  Linux and
4190 			 * FreeBSD don't pay attention to these mode pages
4191 			 * to figure out capacity, but Solaris does.  It
4192 			 * seems to deal with 0 cylinders just fine, and
4193 			 * works out a fake geometry based on the capacity.
4194 			 */
4195 			memcpy(&lun->mode_pages.rigid_disk_page[
4196 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4197 			       sizeof(rigid_disk_page_default));
4198 			memcpy(&lun->mode_pages.rigid_disk_page[
4199 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4200 			       sizeof(rigid_disk_page_changeable));
4201 
4202 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4203 				CTL_DEFAULT_HEADS;
4204 
4205 			/*
4206 			 * The divide method here will be more accurate,
4207 			 * probably, but results in floating point being
4208 			 * used in the kernel on i386 (__udivdi3()).  On the
4209 			 * XScale, though, __udivdi3() is implemented in
4210 			 * software.
4211 			 *
4212 			 * The shift method for cylinder calculation is
4213 			 * accurate if sectors_per_cylinder is a power of
4214 			 * 2.  Otherwise it might be slightly off -- you
4215 			 * might have a bit of a truncation problem.
4216 			 */
4217 #ifdef	__XSCALE__
4218 			cylinders = (lun->be_lun->maxlba + 1) /
4219 				sectors_per_cylinder;
4220 #else
4221 			for (shift = 31; shift > 0; shift--) {
4222 				if (sectors_per_cylinder & (1 << shift))
4223 					break;
4224 			}
4225 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4226 #endif
4227 
4228 			/*
4229 			 * We've basically got 3 bytes, or 24 bits for the
4230 			 * cylinder size in the mode page.  If we're over,
4231 			 * just round down to 2^24.
4232 			 */
4233 			if (cylinders > 0xffffff)
4234 				cylinders = 0xffffff;
4235 
4236 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4237 				CTL_PAGE_DEFAULT];
4238 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4239 
4240 			if ((value = dnvlist_get_string(lun->be_lun->options,
4241 			    "rpm", NULL)) != NULL) {
4242 				scsi_ulto2b(strtol(value, NULL, 0),
4243 				     rigid_disk_page->rotation_rate);
4244 			}
4245 
4246 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4247 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4248 			       sizeof(rigid_disk_page_default));
4249 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4250 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4251 			       sizeof(rigid_disk_page_default));
4252 
4253 			page_index->page_data =
4254 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4255 			break;
4256 		}
4257 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4258 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4259 			    ("subpage %#x for page %#x is incorrect!",
4260 			    page_index->subpage, page_code));
4261 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4262 			       &verify_er_page_default,
4263 			       sizeof(verify_er_page_default));
4264 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4265 			       &verify_er_page_changeable,
4266 			       sizeof(verify_er_page_changeable));
4267 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4268 			       &verify_er_page_default,
4269 			       sizeof(verify_er_page_default));
4270 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4271 			       &verify_er_page_default,
4272 			       sizeof(verify_er_page_default));
4273 			page_index->page_data =
4274 				(uint8_t *)lun->mode_pages.verify_er_page;
4275 			break;
4276 		}
4277 		case SMS_CACHING_PAGE: {
4278 			struct scsi_caching_page *caching_page;
4279 
4280 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4281 			    ("subpage %#x for page %#x is incorrect!",
4282 			    page_index->subpage, page_code));
4283 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4284 			       &caching_page_default,
4285 			       sizeof(caching_page_default));
4286 			memcpy(&lun->mode_pages.caching_page[
4287 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4288 			       sizeof(caching_page_changeable));
4289 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4290 			       &caching_page_default,
4291 			       sizeof(caching_page_default));
4292 			caching_page = &lun->mode_pages.caching_page[
4293 			    CTL_PAGE_SAVED];
4294 			value = dnvlist_get_string(lun->be_lun->options,
4295 			    "writecache", NULL);
4296 			if (value != NULL && strcmp(value, "off") == 0)
4297 				caching_page->flags1 &= ~SCP_WCE;
4298 			value = dnvlist_get_string(lun->be_lun->options,
4299 			    "readcache", NULL);
4300 			if (value != NULL && strcmp(value, "off") == 0)
4301 				caching_page->flags1 |= SCP_RCD;
4302 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4303 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4304 			       sizeof(caching_page_default));
4305 			page_index->page_data =
4306 				(uint8_t *)lun->mode_pages.caching_page;
4307 			break;
4308 		}
4309 		case SMS_CONTROL_MODE_PAGE: {
4310 			switch (page_index->subpage) {
4311 			case SMS_SUBPAGE_PAGE_0: {
4312 				struct scsi_control_page *control_page;
4313 
4314 				memcpy(&lun->mode_pages.control_page[
4315 				    CTL_PAGE_DEFAULT],
4316 				       &control_page_default,
4317 				       sizeof(control_page_default));
4318 				memcpy(&lun->mode_pages.control_page[
4319 				    CTL_PAGE_CHANGEABLE],
4320 				       &control_page_changeable,
4321 				       sizeof(control_page_changeable));
4322 				memcpy(&lun->mode_pages.control_page[
4323 				    CTL_PAGE_SAVED],
4324 				       &control_page_default,
4325 				       sizeof(control_page_default));
4326 				control_page = &lun->mode_pages.control_page[
4327 				    CTL_PAGE_SAVED];
4328 				value = dnvlist_get_string(lun->be_lun->options,
4329 				    "reordering", NULL);
4330 				if (value != NULL &&
4331 				    strcmp(value, "unrestricted") == 0) {
4332 					control_page->queue_flags &=
4333 					    ~SCP_QUEUE_ALG_MASK;
4334 					control_page->queue_flags |=
4335 					    SCP_QUEUE_ALG_UNRESTRICTED;
4336 				}
4337 				memcpy(&lun->mode_pages.control_page[
4338 				    CTL_PAGE_CURRENT],
4339 				       &lun->mode_pages.control_page[
4340 				    CTL_PAGE_SAVED],
4341 				       sizeof(control_page_default));
4342 				page_index->page_data =
4343 				    (uint8_t *)lun->mode_pages.control_page;
4344 				break;
4345 			}
4346 			case 0x01:
4347 				memcpy(&lun->mode_pages.control_ext_page[
4348 				    CTL_PAGE_DEFAULT],
4349 				       &control_ext_page_default,
4350 				       sizeof(control_ext_page_default));
4351 				memcpy(&lun->mode_pages.control_ext_page[
4352 				    CTL_PAGE_CHANGEABLE],
4353 				       &control_ext_page_changeable,
4354 				       sizeof(control_ext_page_changeable));
4355 				memcpy(&lun->mode_pages.control_ext_page[
4356 				    CTL_PAGE_SAVED],
4357 				       &control_ext_page_default,
4358 				       sizeof(control_ext_page_default));
4359 				memcpy(&lun->mode_pages.control_ext_page[
4360 				    CTL_PAGE_CURRENT],
4361 				       &lun->mode_pages.control_ext_page[
4362 				    CTL_PAGE_SAVED],
4363 				       sizeof(control_ext_page_default));
4364 				page_index->page_data =
4365 				    (uint8_t *)lun->mode_pages.control_ext_page;
4366 				break;
4367 			default:
4368 				panic("subpage %#x for page %#x is incorrect!",
4369 				      page_index->subpage, page_code);
4370 			}
4371 			break;
4372 		}
4373 		case SMS_INFO_EXCEPTIONS_PAGE: {
4374 			switch (page_index->subpage) {
4375 			case SMS_SUBPAGE_PAGE_0:
4376 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4377 				       &ie_page_default,
4378 				       sizeof(ie_page_default));
4379 				memcpy(&lun->mode_pages.ie_page[
4380 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4381 				       sizeof(ie_page_changeable));
4382 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4383 				       &ie_page_default,
4384 				       sizeof(ie_page_default));
4385 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4386 				       &ie_page_default,
4387 				       sizeof(ie_page_default));
4388 				page_index->page_data =
4389 					(uint8_t *)lun->mode_pages.ie_page;
4390 				break;
4391 			case 0x02: {
4392 				struct ctl_logical_block_provisioning_page *page;
4393 
4394 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4395 				       &lbp_page_default,
4396 				       sizeof(lbp_page_default));
4397 				memcpy(&lun->mode_pages.lbp_page[
4398 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4399 				       sizeof(lbp_page_changeable));
4400 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4401 				       &lbp_page_default,
4402 				       sizeof(lbp_page_default));
4403 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4404 				value = dnvlist_get_string(lun->be_lun->options,
4405 				    "avail-threshold", NULL);
4406 				if (value != NULL &&
4407 				    ctl_expand_number(value, &ival) == 0) {
4408 					page->descr[0].flags |= SLBPPD_ENABLED |
4409 					    SLBPPD_ARMING_DEC;
4410 					if (lun->be_lun->blocksize)
4411 						ival /= lun->be_lun->blocksize;
4412 					else
4413 						ival /= 512;
4414 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4415 					    page->descr[0].count);
4416 				}
4417 				value = dnvlist_get_string(lun->be_lun->options,
4418 				    "used-threshold", NULL);
4419 				if (value != NULL &&
4420 				    ctl_expand_number(value, &ival) == 0) {
4421 					page->descr[1].flags |= SLBPPD_ENABLED |
4422 					    SLBPPD_ARMING_INC;
4423 					if (lun->be_lun->blocksize)
4424 						ival /= lun->be_lun->blocksize;
4425 					else
4426 						ival /= 512;
4427 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4428 					    page->descr[1].count);
4429 				}
4430 				value = dnvlist_get_string(lun->be_lun->options,
4431 				    "pool-avail-threshold", NULL);
4432 				if (value != NULL &&
4433 				    ctl_expand_number(value, &ival) == 0) {
4434 					page->descr[2].flags |= SLBPPD_ENABLED |
4435 					    SLBPPD_ARMING_DEC;
4436 					if (lun->be_lun->blocksize)
4437 						ival /= lun->be_lun->blocksize;
4438 					else
4439 						ival /= 512;
4440 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4441 					    page->descr[2].count);
4442 				}
4443 				value = dnvlist_get_string(lun->be_lun->options,
4444 				    "pool-used-threshold", NULL);
4445 				if (value != NULL &&
4446 				    ctl_expand_number(value, &ival) == 0) {
4447 					page->descr[3].flags |= SLBPPD_ENABLED |
4448 					    SLBPPD_ARMING_INC;
4449 					if (lun->be_lun->blocksize)
4450 						ival /= lun->be_lun->blocksize;
4451 					else
4452 						ival /= 512;
4453 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4454 					    page->descr[3].count);
4455 				}
4456 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4457 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4458 				       sizeof(lbp_page_default));
4459 				page_index->page_data =
4460 					(uint8_t *)lun->mode_pages.lbp_page;
4461 				break;
4462 			}
4463 			default:
4464 				panic("subpage %#x for page %#x is incorrect!",
4465 				      page_index->subpage, page_code);
4466 			}
4467 			break;
4468 		}
4469 		case SMS_CDDVD_CAPS_PAGE:{
4470 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4471 			    ("subpage %#x for page %#x is incorrect!",
4472 			    page_index->subpage, page_code));
4473 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4474 			       &cddvd_page_default,
4475 			       sizeof(cddvd_page_default));
4476 			memcpy(&lun->mode_pages.cddvd_page[
4477 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4478 			       sizeof(cddvd_page_changeable));
4479 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4480 			       &cddvd_page_default,
4481 			       sizeof(cddvd_page_default));
4482 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4483 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4484 			       sizeof(cddvd_page_default));
4485 			page_index->page_data =
4486 				(uint8_t *)lun->mode_pages.cddvd_page;
4487 			break;
4488 		}
4489 		default:
4490 			panic("invalid page code value %#x", page_code);
4491 		}
4492 	}
4493 
4494 	return (CTL_RETVAL_COMPLETE);
4495 }
4496 
4497 static int
4498 ctl_init_log_page_index(struct ctl_lun *lun)
4499 {
4500 	struct ctl_page_index *page_index;
4501 	int i, j, k, prev;
4502 
4503 	memcpy(&lun->log_pages.index, log_page_index_template,
4504 	       sizeof(log_page_index_template));
4505 
4506 	prev = -1;
4507 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4508 		page_index = &lun->log_pages.index[i];
4509 		if (lun->be_lun->lun_type == T_DIRECT &&
4510 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4511 			continue;
4512 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4513 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4514 			continue;
4515 		if (lun->be_lun->lun_type == T_CDROM &&
4516 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4517 			continue;
4518 
4519 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4520 		    lun->backend->lun_attr == NULL)
4521 			continue;
4522 
4523 		if (page_index->page_code != prev) {
4524 			lun->log_pages.pages_page[j] = page_index->page_code;
4525 			prev = page_index->page_code;
4526 			j++;
4527 		}
4528 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4529 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4530 		k++;
4531 	}
4532 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4533 	lun->log_pages.index[0].page_len = j;
4534 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4535 	lun->log_pages.index[1].page_len = k * 2;
4536 	lun->log_pages.index[2].page_data = (uint8_t *)&lun->log_pages.temp_page;
4537 	lun->log_pages.index[2].page_len = sizeof(lun->log_pages.temp_page);
4538 	lun->log_pages.index[3].page_data = &lun->log_pages.lbp_page[0];
4539 	lun->log_pages.index[3].page_len = 12*CTL_NUM_LBP_PARAMS;
4540 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.stat_page;
4541 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.stat_page);
4542 	lun->log_pages.index[5].page_data = (uint8_t *)&lun->log_pages.ie_page;
4543 	lun->log_pages.index[5].page_len = sizeof(lun->log_pages.ie_page);
4544 
4545 	return (CTL_RETVAL_COMPLETE);
4546 }
4547 
4548 static int
4549 hex2bin(const char *str, uint8_t *buf, int buf_size)
4550 {
4551 	int i;
4552 	u_char c;
4553 
4554 	memset(buf, 0, buf_size);
4555 	while (isspace(str[0]))
4556 		str++;
4557 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4558 		str += 2;
4559 	buf_size *= 2;
4560 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4561 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4562 			str++;
4563 		c = str[i];
4564 		if (isdigit(c))
4565 			c -= '0';
4566 		else if (isalpha(c))
4567 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4568 		else
4569 			break;
4570 		if (c >= 16)
4571 			break;
4572 		if ((i & 1) == 0)
4573 			buf[i / 2] |= (c << 4);
4574 		else
4575 			buf[i / 2] |= c;
4576 	}
4577 	return ((i + 1) / 2);
4578 }
4579 
4580 /*
4581  * Add LUN.
4582  *
4583  * Returns 0 for success, non-zero (errno) for failure.
4584  */
4585 int
4586 ctl_add_lun(struct ctl_be_lun *be_lun)
4587 {
4588 	struct ctl_softc *ctl_softc = control_softc;
4589 	struct ctl_lun *nlun, *lun;
4590 	struct scsi_vpd_id_descriptor *desc;
4591 	struct scsi_vpd_id_t10 *t10id;
4592 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4593 	int lun_number;
4594 	int devidlen, idlen1, idlen2 = 0, len;
4595 
4596 	/*
4597 	 * We support only Direct Access, CD-ROM or Processor LUN types.
4598 	 */
4599 	switch (be_lun->lun_type) {
4600 	case T_DIRECT:
4601 	case T_PROCESSOR:
4602 	case T_CDROM:
4603 		break;
4604 	case T_SEQUENTIAL:
4605 	case T_CHANGER:
4606 	default:
4607 		return (EINVAL);
4608 	}
4609 	lun = malloc(sizeof(*lun), M_CTL, M_WAITOK | M_ZERO);
4610 
4611 	lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4612 	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4613 	lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4614 	    M_DEVBUF, M_WAITOK | M_ZERO);
4615 	lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4616 	    M_DEVBUF, M_WAITOK | M_ZERO);
4617 
4618 	/* Generate LUN ID. */
4619 	devidlen = max(CTL_DEVID_MIN_LEN,
4620 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4621 	idlen1 = sizeof(*t10id) + devidlen;
4622 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4623 	scsiname = dnvlist_get_string(be_lun->options, "scsiname", NULL);
4624 	if (scsiname != NULL) {
4625 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4626 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4627 	}
4628 	eui = dnvlist_get_string(be_lun->options, "eui", NULL);
4629 	if (eui != NULL) {
4630 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4631 	}
4632 	naa = dnvlist_get_string(be_lun->options, "naa", NULL);
4633 	if (naa != NULL) {
4634 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4635 	}
4636 	uuid = dnvlist_get_string(be_lun->options, "uuid", NULL);
4637 	if (uuid != NULL) {
4638 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4639 	}
4640 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4641 	    M_CTL, M_WAITOK | M_ZERO);
4642 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4643 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4644 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4645 	desc->length = idlen1;
4646 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4647 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4648 	if ((vendor = dnvlist_get_string(be_lun->options, "vendor", NULL)) == NULL) {
4649 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4650 	} else {
4651 		strncpy(t10id->vendor, vendor,
4652 		    min(sizeof(t10id->vendor), strlen(vendor)));
4653 	}
4654 	strncpy((char *)t10id->vendor_spec_id,
4655 	    (char *)be_lun->device_id, devidlen);
4656 	if (scsiname != NULL) {
4657 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4658 		    desc->length);
4659 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4660 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4661 		    SVPD_ID_TYPE_SCSI_NAME;
4662 		desc->length = idlen2;
4663 		strlcpy(desc->identifier, scsiname, idlen2);
4664 	}
4665 	if (eui != NULL) {
4666 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4667 		    desc->length);
4668 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4669 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4670 		    SVPD_ID_TYPE_EUI64;
4671 		desc->length = hex2bin(eui, desc->identifier, 16);
4672 		desc->length = desc->length > 12 ? 16 :
4673 		    (desc->length > 8 ? 12 : 8);
4674 		len -= 16 - desc->length;
4675 	}
4676 	if (naa != NULL) {
4677 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4678 		    desc->length);
4679 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4680 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4681 		    SVPD_ID_TYPE_NAA;
4682 		desc->length = hex2bin(naa, desc->identifier, 16);
4683 		desc->length = desc->length > 8 ? 16 : 8;
4684 		len -= 16 - desc->length;
4685 	}
4686 	if (uuid != NULL) {
4687 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4688 		    desc->length);
4689 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4690 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4691 		    SVPD_ID_TYPE_UUID;
4692 		desc->identifier[0] = 0x10;
4693 		hex2bin(uuid, &desc->identifier[2], 16);
4694 		desc->length = 18;
4695 	}
4696 	lun->lun_devid->len = len;
4697 
4698 	mtx_lock(&ctl_softc->ctl_lock);
4699 	/*
4700 	 * See if the caller requested a particular LUN number.  If so, see
4701 	 * if it is available.  Otherwise, allocate the first available LUN.
4702 	 */
4703 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4704 		if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4705 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4706 			mtx_unlock(&ctl_softc->ctl_lock);
4707 			if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4708 				printf("ctl: requested LUN ID %d is higher "
4709 				       "than ctl_max_luns - 1 (%d)\n",
4710 				       be_lun->req_lun_id, ctl_max_luns - 1);
4711 			} else {
4712 				/*
4713 				 * XXX KDM return an error, or just assign
4714 				 * another LUN ID in this case??
4715 				 */
4716 				printf("ctl: requested LUN ID %d is already "
4717 				       "in use\n", be_lun->req_lun_id);
4718 			}
4719 fail:
4720 			free(lun->lun_devid, M_CTL);
4721 			free(lun, M_CTL);
4722 			return (ENOSPC);
4723 		}
4724 		lun_number = be_lun->req_lun_id;
4725 	} else {
4726 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4727 		if (lun_number == -1) {
4728 			mtx_unlock(&ctl_softc->ctl_lock);
4729 			printf("ctl: can't allocate LUN, out of LUNs\n");
4730 			goto fail;
4731 		}
4732 	}
4733 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4734 	mtx_unlock(&ctl_softc->ctl_lock);
4735 
4736 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4737 	lun->lun = lun_number;
4738 	lun->be_lun = be_lun;
4739 	/*
4740 	 * The processor LUN is always enabled.  Disk LUNs come on line
4741 	 * disabled, and must be enabled by the backend.
4742 	 */
4743 	lun->flags |= CTL_LUN_DISABLED;
4744 	lun->backend = be_lun->be;
4745 	be_lun->ctl_lun = lun;
4746 	be_lun->lun_id = lun_number;
4747 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4748 		lun->flags |= CTL_LUN_EJECTED;
4749 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4750 		lun->flags |= CTL_LUN_NO_MEDIA;
4751 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4752 		lun->flags |= CTL_LUN_STOPPED;
4753 
4754 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4755 		lun->flags |= CTL_LUN_PRIMARY_SC;
4756 
4757 	value = dnvlist_get_string(be_lun->options, "removable", NULL);
4758 	if (value != NULL) {
4759 		if (strcmp(value, "on") == 0)
4760 			lun->flags |= CTL_LUN_REMOVABLE;
4761 	} else if (be_lun->lun_type == T_CDROM)
4762 		lun->flags |= CTL_LUN_REMOVABLE;
4763 
4764 	lun->ctl_softc = ctl_softc;
4765 #ifdef CTL_TIME_IO
4766 	lun->last_busy = getsbinuptime();
4767 #endif
4768 	LIST_INIT(&lun->ooa_queue);
4769 	STAILQ_INIT(&lun->error_list);
4770 	lun->ie_reported = 1;
4771 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4772 	ctl_tpc_lun_init(lun);
4773 	if (lun->flags & CTL_LUN_REMOVABLE) {
4774 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4775 		    M_CTL, M_WAITOK);
4776 	}
4777 
4778 	/*
4779 	 * Initialize the mode and log page index.
4780 	 */
4781 	ctl_init_page_index(lun);
4782 	ctl_init_log_page_index(lun);
4783 
4784 	/* Setup statistics gathering */
4785 	lun->stats.item = lun_number;
4786 
4787 	/*
4788 	 * Now, before we insert this lun on the lun list, set the lun
4789 	 * inventory changed UA for all other luns.
4790 	 */
4791 	mtx_lock(&ctl_softc->ctl_lock);
4792 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4793 		mtx_lock(&nlun->lun_lock);
4794 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4795 		mtx_unlock(&nlun->lun_lock);
4796 	}
4797 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4798 	ctl_softc->ctl_luns[lun_number] = lun;
4799 	ctl_softc->num_luns++;
4800 	mtx_unlock(&ctl_softc->ctl_lock);
4801 
4802 	/*
4803 	 * We successfully added the LUN, attempt to enable it.
4804 	 */
4805 	if (ctl_enable_lun(lun) != 0) {
4806 		printf("%s: ctl_enable_lun() failed!\n", __func__);
4807 		mtx_lock(&ctl_softc->ctl_lock);
4808 		STAILQ_REMOVE(&ctl_softc->lun_list, lun, ctl_lun, links);
4809 		ctl_clear_mask(ctl_softc->ctl_lun_mask, lun_number);
4810 		ctl_softc->ctl_luns[lun_number] = NULL;
4811 		ctl_softc->num_luns--;
4812 		mtx_unlock(&ctl_softc->ctl_lock);
4813 		free(lun->lun_devid, M_CTL);
4814 		free(lun, M_CTL);
4815 		return (EIO);
4816 	}
4817 
4818 	return (0);
4819 }
4820 
4821 /*
4822  * Free LUN that has no active requests.
4823  */
4824 static int
4825 ctl_free_lun(struct ctl_lun *lun)
4826 {
4827 	struct ctl_softc *softc = lun->ctl_softc;
4828 	struct ctl_lun *nlun;
4829 	int i;
4830 
4831 	KASSERT(LIST_EMPTY(&lun->ooa_queue),
4832 	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4833 
4834 	mtx_lock(&softc->ctl_lock);
4835 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4836 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4837 	softc->ctl_luns[lun->lun] = NULL;
4838 	softc->num_luns--;
4839 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4840 		mtx_lock(&nlun->lun_lock);
4841 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4842 		mtx_unlock(&nlun->lun_lock);
4843 	}
4844 	mtx_unlock(&softc->ctl_lock);
4845 
4846 	/*
4847 	 * Tell the backend to free resources, if this LUN has a backend.
4848 	 */
4849 	lun->be_lun->lun_shutdown(lun->be_lun);
4850 
4851 	lun->ie_reportcnt = UINT32_MAX;
4852 	callout_drain(&lun->ie_callout);
4853 	ctl_tpc_lun_shutdown(lun);
4854 	mtx_destroy(&lun->lun_lock);
4855 	free(lun->lun_devid, M_CTL);
4856 	for (i = 0; i < ctl_max_ports; i++)
4857 		free(lun->pending_ua[i], M_CTL);
4858 	free(lun->pending_ua, M_DEVBUF);
4859 	for (i = 0; i < ctl_max_ports; i++)
4860 		free(lun->pr_keys[i], M_CTL);
4861 	free(lun->pr_keys, M_DEVBUF);
4862 	free(lun->write_buffer, M_CTL);
4863 	free(lun->prevent, M_CTL);
4864 	free(lun, M_CTL);
4865 
4866 	return (0);
4867 }
4868 
4869 static int
4870 ctl_enable_lun(struct ctl_lun *lun)
4871 {
4872 	struct ctl_softc *softc;
4873 	struct ctl_port *port, *nport;
4874 	int retval;
4875 
4876 	softc = lun->ctl_softc;
4877 
4878 	mtx_lock(&softc->ctl_lock);
4879 	mtx_lock(&lun->lun_lock);
4880 	KASSERT((lun->flags & CTL_LUN_DISABLED) != 0,
4881 	    ("%s: LUN not disabled", __func__));
4882 	lun->flags &= ~CTL_LUN_DISABLED;
4883 	mtx_unlock(&lun->lun_lock);
4884 
4885 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4886 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4887 		    port->lun_map != NULL || port->lun_enable == NULL)
4888 			continue;
4889 
4890 		/*
4891 		 * Drop the lock while we call the FETD's enable routine.
4892 		 * This can lead to a callback into CTL (at least in the
4893 		 * case of the internal initiator frontend.
4894 		 */
4895 		mtx_unlock(&softc->ctl_lock);
4896 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4897 		mtx_lock(&softc->ctl_lock);
4898 		if (retval != 0) {
4899 			printf("%s: FETD %s port %d returned error "
4900 			       "%d for lun_enable on lun %jd\n",
4901 			       __func__, port->port_name, port->targ_port,
4902 			       retval, (intmax_t)lun->lun);
4903 		}
4904 	}
4905 
4906 	mtx_unlock(&softc->ctl_lock);
4907 	ctl_isc_announce_lun(lun);
4908 
4909 	return (0);
4910 }
4911 
4912 static int
4913 ctl_disable_lun(struct ctl_lun *lun)
4914 {
4915 	struct ctl_softc *softc;
4916 	struct ctl_port *port;
4917 	int retval;
4918 
4919 	softc = lun->ctl_softc;
4920 
4921 	mtx_lock(&softc->ctl_lock);
4922 	mtx_lock(&lun->lun_lock);
4923 	KASSERT((lun->flags & CTL_LUN_DISABLED) == 0,
4924 	    ("%s: LUN not enabled", __func__));
4925 	lun->flags |= CTL_LUN_DISABLED;
4926 	mtx_unlock(&lun->lun_lock);
4927 
4928 	STAILQ_FOREACH(port, &softc->port_list, links) {
4929 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4930 		    port->lun_map != NULL || port->lun_disable == NULL)
4931 			continue;
4932 
4933 		/*
4934 		 * Drop the lock before we call the frontend's disable
4935 		 * routine, to avoid lock order reversals.
4936 		 *
4937 		 * XXX KDM what happens if the frontend list changes while
4938 		 * we're traversing it?  It's unlikely, but should be handled.
4939 		 */
4940 		mtx_unlock(&softc->ctl_lock);
4941 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4942 		mtx_lock(&softc->ctl_lock);
4943 		if (retval != 0) {
4944 			printf("%s: FETD %s port %d returned error "
4945 			       "%d for lun_disable on lun %jd\n",
4946 			       __func__, port->port_name, port->targ_port,
4947 			       retval, (intmax_t)lun->lun);
4948 		}
4949 	}
4950 
4951 	mtx_unlock(&softc->ctl_lock);
4952 	ctl_isc_announce_lun(lun);
4953 
4954 	return (0);
4955 }
4956 
4957 int
4958 ctl_start_lun(struct ctl_be_lun *be_lun)
4959 {
4960 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4961 
4962 	mtx_lock(&lun->lun_lock);
4963 	lun->flags &= ~CTL_LUN_STOPPED;
4964 	mtx_unlock(&lun->lun_lock);
4965 	return (0);
4966 }
4967 
4968 int
4969 ctl_stop_lun(struct ctl_be_lun *be_lun)
4970 {
4971 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4972 
4973 	mtx_lock(&lun->lun_lock);
4974 	lun->flags |= CTL_LUN_STOPPED;
4975 	mtx_unlock(&lun->lun_lock);
4976 	return (0);
4977 }
4978 
4979 int
4980 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4981 {
4982 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4983 
4984 	mtx_lock(&lun->lun_lock);
4985 	lun->flags |= CTL_LUN_NO_MEDIA;
4986 	mtx_unlock(&lun->lun_lock);
4987 	return (0);
4988 }
4989 
4990 int
4991 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4992 {
4993 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4994 	union ctl_ha_msg msg;
4995 
4996 	mtx_lock(&lun->lun_lock);
4997 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4998 	if (lun->flags & CTL_LUN_REMOVABLE)
4999 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
5000 	mtx_unlock(&lun->lun_lock);
5001 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
5002 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5003 		bzero(&msg.ua, sizeof(msg.ua));
5004 		msg.hdr.msg_type = CTL_MSG_UA;
5005 		msg.hdr.nexus.initid = -1;
5006 		msg.hdr.nexus.targ_port = -1;
5007 		msg.hdr.nexus.targ_lun = lun->lun;
5008 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5009 		msg.ua.ua_all = 1;
5010 		msg.ua.ua_set = 1;
5011 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
5012 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5013 		    M_WAITOK);
5014 	}
5015 	return (0);
5016 }
5017 
5018 int
5019 ctl_lun_ejected(struct ctl_be_lun *be_lun)
5020 {
5021 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5022 
5023 	mtx_lock(&lun->lun_lock);
5024 	lun->flags |= CTL_LUN_EJECTED;
5025 	mtx_unlock(&lun->lun_lock);
5026 	return (0);
5027 }
5028 
5029 int
5030 ctl_lun_primary(struct ctl_be_lun *be_lun)
5031 {
5032 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5033 
5034 	mtx_lock(&lun->lun_lock);
5035 	lun->flags |= CTL_LUN_PRIMARY_SC;
5036 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5037 	mtx_unlock(&lun->lun_lock);
5038 	ctl_isc_announce_lun(lun);
5039 	return (0);
5040 }
5041 
5042 int
5043 ctl_lun_secondary(struct ctl_be_lun *be_lun)
5044 {
5045 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5046 
5047 	mtx_lock(&lun->lun_lock);
5048 	lun->flags &= ~CTL_LUN_PRIMARY_SC;
5049 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5050 	mtx_unlock(&lun->lun_lock);
5051 	ctl_isc_announce_lun(lun);
5052 	return (0);
5053 }
5054 
5055 /*
5056  * Remove LUN.  If there are active requests, wait for completion.
5057  *
5058  * Returns 0 for success, non-zero (errno) for failure.
5059  * Completion is reported to backed via the lun_shutdown() method.
5060  */
5061 int
5062 ctl_remove_lun(struct ctl_be_lun *be_lun)
5063 {
5064 	struct ctl_lun *lun;
5065 
5066 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5067 
5068 	ctl_disable_lun(lun);
5069 
5070 	mtx_lock(&lun->lun_lock);
5071 	lun->flags |= CTL_LUN_INVALID;
5072 
5073 	/*
5074 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5075 	 * If we have something in the OOA queue, we'll free it when the
5076 	 * last I/O completes.
5077 	 */
5078 	if (LIST_EMPTY(&lun->ooa_queue)) {
5079 		mtx_unlock(&lun->lun_lock);
5080 		ctl_free_lun(lun);
5081 	} else
5082 		mtx_unlock(&lun->lun_lock);
5083 
5084 	return (0);
5085 }
5086 
5087 void
5088 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5089 {
5090 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5091 	union ctl_ha_msg msg;
5092 
5093 	mtx_lock(&lun->lun_lock);
5094 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5095 	mtx_unlock(&lun->lun_lock);
5096 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5097 		/* Send msg to other side. */
5098 		bzero(&msg.ua, sizeof(msg.ua));
5099 		msg.hdr.msg_type = CTL_MSG_UA;
5100 		msg.hdr.nexus.initid = -1;
5101 		msg.hdr.nexus.targ_port = -1;
5102 		msg.hdr.nexus.targ_lun = lun->lun;
5103 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5104 		msg.ua.ua_all = 1;
5105 		msg.ua.ua_set = 1;
5106 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5107 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5108 		    M_WAITOK);
5109 	}
5110 }
5111 
5112 /*
5113  * Backend "memory move is complete" callback for requests that never
5114  * make it down to say RAIDCore's configuration code.
5115  */
5116 int
5117 ctl_config_move_done(union ctl_io *io, bool samethr)
5118 {
5119 	int retval;
5120 
5121 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5122 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5123 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
5124 
5125 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5126 		ctl_data_print(io);
5127 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5128 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5129 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5130 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5131 		/*
5132 		 * XXX KDM just assuming a single pointer here, and not a
5133 		 * S/G list.  If we start using S/G lists for config data,
5134 		 * we'll need to know how to clean them up here as well.
5135 		 */
5136 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5137 			free(io->scsiio.kern_data_ptr, M_CTL);
5138 		ctl_done(io);
5139 		retval = CTL_RETVAL_COMPLETE;
5140 	} else {
5141 		/*
5142 		 * XXX KDM now we need to continue data movement.  Some
5143 		 * options:
5144 		 * - call ctl_scsiio() again?  We don't do this for data
5145 		 *   writes, because for those at least we know ahead of
5146 		 *   time where the write will go and how long it is.  For
5147 		 *   config writes, though, that information is largely
5148 		 *   contained within the write itself, thus we need to
5149 		 *   parse out the data again.
5150 		 *
5151 		 * - Call some other function once the data is in?
5152 		 */
5153 
5154 		/*
5155 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5156 		 * bits to see whether we're allocated or not.
5157 		 */
5158 		retval = ctl_scsiio(&io->scsiio);
5159 	}
5160 	return (retval);
5161 }
5162 
5163 /*
5164  * This gets called by a backend driver when it is done with a
5165  * data_submit method.
5166  */
5167 void
5168 ctl_data_submit_done(union ctl_io *io)
5169 {
5170 	/*
5171 	 * If the IO_CONT flag is set, we need to call the supplied
5172 	 * function to continue processing the I/O, instead of completing
5173 	 * the I/O just yet.
5174 	 *
5175 	 * If there is an error, though, we don't want to keep processing.
5176 	 * Instead, just send status back to the initiator.
5177 	 */
5178 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5179 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5180 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5181 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5182 		io->scsiio.io_cont(io);
5183 		return;
5184 	}
5185 	ctl_done(io);
5186 }
5187 
5188 /*
5189  * This gets called by a backend driver when it is done with a
5190  * configuration write.
5191  */
5192 void
5193 ctl_config_write_done(union ctl_io *io)
5194 {
5195 	uint8_t *buf;
5196 
5197 	/*
5198 	 * If the IO_CONT flag is set, we need to call the supplied
5199 	 * function to continue processing the I/O, instead of completing
5200 	 * the I/O just yet.
5201 	 *
5202 	 * If there is an error, though, we don't want to keep processing.
5203 	 * Instead, just send status back to the initiator.
5204 	 */
5205 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5206 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5207 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5208 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5209 		io->scsiio.io_cont(io);
5210 		return;
5211 	}
5212 	/*
5213 	 * Since a configuration write can be done for commands that actually
5214 	 * have data allocated, like write buffer, and commands that have
5215 	 * no data, like start/stop unit, we need to check here.
5216 	 */
5217 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5218 		buf = io->scsiio.kern_data_ptr;
5219 	else
5220 		buf = NULL;
5221 	ctl_done(io);
5222 	if (buf)
5223 		free(buf, M_CTL);
5224 }
5225 
5226 void
5227 ctl_config_read_done(union ctl_io *io)
5228 {
5229 	uint8_t *buf;
5230 
5231 	/*
5232 	 * If there is some error -- we are done, skip data transfer.
5233 	 */
5234 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5235 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5236 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5237 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5238 			buf = io->scsiio.kern_data_ptr;
5239 		else
5240 			buf = NULL;
5241 		ctl_done(io);
5242 		if (buf)
5243 			free(buf, M_CTL);
5244 		return;
5245 	}
5246 
5247 	/*
5248 	 * If the IO_CONT flag is set, we need to call the supplied
5249 	 * function to continue processing the I/O, instead of completing
5250 	 * the I/O just yet.
5251 	 */
5252 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5253 		io->scsiio.io_cont(io);
5254 		return;
5255 	}
5256 
5257 	ctl_datamove(io);
5258 }
5259 
5260 /*
5261  * SCSI release command.
5262  */
5263 int
5264 ctl_scsi_release(struct ctl_scsiio *ctsio)
5265 {
5266 	struct ctl_lun *lun = CTL_LUN(ctsio);
5267 	uint32_t residx;
5268 
5269 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5270 
5271 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5272 
5273 	/*
5274 	 * XXX KDM right now, we only support LUN reservation.  We don't
5275 	 * support 3rd party reservations, or extent reservations, which
5276 	 * might actually need the parameter list.  If we've gotten this
5277 	 * far, we've got a LUN reservation.  Anything else got kicked out
5278 	 * above.  So, according to SPC, ignore the length.
5279 	 */
5280 
5281 	mtx_lock(&lun->lun_lock);
5282 
5283 	/*
5284 	 * According to SPC, it is not an error for an intiator to attempt
5285 	 * to release a reservation on a LUN that isn't reserved, or that
5286 	 * is reserved by another initiator.  The reservation can only be
5287 	 * released, though, by the initiator who made it or by one of
5288 	 * several reset type events.
5289 	 */
5290 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5291 			lun->flags &= ~CTL_LUN_RESERVED;
5292 
5293 	mtx_unlock(&lun->lun_lock);
5294 
5295 	ctl_set_success(ctsio);
5296 	ctl_done((union ctl_io *)ctsio);
5297 	return (CTL_RETVAL_COMPLETE);
5298 }
5299 
5300 int
5301 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5302 {
5303 	struct ctl_lun *lun = CTL_LUN(ctsio);
5304 	uint32_t residx;
5305 
5306 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5307 
5308 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5309 
5310 	/*
5311 	 * XXX KDM right now, we only support LUN reservation.  We don't
5312 	 * support 3rd party reservations, or extent reservations, which
5313 	 * might actually need the parameter list.  If we've gotten this
5314 	 * far, we've got a LUN reservation.  Anything else got kicked out
5315 	 * above.  So, according to SPC, ignore the length.
5316 	 */
5317 
5318 	mtx_lock(&lun->lun_lock);
5319 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5320 		ctl_set_reservation_conflict(ctsio);
5321 		goto bailout;
5322 	}
5323 
5324 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5325 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5326 		ctl_set_success(ctsio);
5327 		goto bailout;
5328 	}
5329 
5330 	lun->flags |= CTL_LUN_RESERVED;
5331 	lun->res_idx = residx;
5332 	ctl_set_success(ctsio);
5333 
5334 bailout:
5335 	mtx_unlock(&lun->lun_lock);
5336 	ctl_done((union ctl_io *)ctsio);
5337 	return (CTL_RETVAL_COMPLETE);
5338 }
5339 
5340 int
5341 ctl_start_stop(struct ctl_scsiio *ctsio)
5342 {
5343 	struct ctl_lun *lun = CTL_LUN(ctsio);
5344 	struct scsi_start_stop_unit *cdb;
5345 	int retval;
5346 
5347 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5348 
5349 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5350 
5351 	if ((cdb->how & SSS_PC_MASK) == 0) {
5352 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5353 		    (cdb->how & SSS_START) == 0) {
5354 			uint32_t residx;
5355 
5356 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5357 			if (ctl_get_prkey(lun, residx) == 0 ||
5358 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5359 				ctl_set_reservation_conflict(ctsio);
5360 				ctl_done((union ctl_io *)ctsio);
5361 				return (CTL_RETVAL_COMPLETE);
5362 			}
5363 		}
5364 
5365 		if ((cdb->how & SSS_LOEJ) &&
5366 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5367 			ctl_set_invalid_field(ctsio,
5368 					      /*sks_valid*/ 1,
5369 					      /*command*/ 1,
5370 					      /*field*/ 4,
5371 					      /*bit_valid*/ 1,
5372 					      /*bit*/ 1);
5373 			ctl_done((union ctl_io *)ctsio);
5374 			return (CTL_RETVAL_COMPLETE);
5375 		}
5376 
5377 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5378 		    lun->prevent_count > 0) {
5379 			/* "Medium removal prevented" */
5380 			ctl_set_sense(ctsio, /*current_error*/ 1,
5381 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5382 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5383 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5384 			ctl_done((union ctl_io *)ctsio);
5385 			return (CTL_RETVAL_COMPLETE);
5386 		}
5387 	}
5388 
5389 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5390 	return (retval);
5391 }
5392 
5393 int
5394 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5395 {
5396 	struct ctl_lun *lun = CTL_LUN(ctsio);
5397 	struct scsi_prevent *cdb;
5398 	int retval;
5399 	uint32_t initidx;
5400 
5401 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5402 
5403 	cdb = (struct scsi_prevent *)ctsio->cdb;
5404 
5405 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5406 		ctl_set_invalid_opcode(ctsio);
5407 		ctl_done((union ctl_io *)ctsio);
5408 		return (CTL_RETVAL_COMPLETE);
5409 	}
5410 
5411 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5412 	mtx_lock(&lun->lun_lock);
5413 	if ((cdb->how & PR_PREVENT) &&
5414 	    ctl_is_set(lun->prevent, initidx) == 0) {
5415 		ctl_set_mask(lun->prevent, initidx);
5416 		lun->prevent_count++;
5417 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5418 	    ctl_is_set(lun->prevent, initidx)) {
5419 		ctl_clear_mask(lun->prevent, initidx);
5420 		lun->prevent_count--;
5421 	}
5422 	mtx_unlock(&lun->lun_lock);
5423 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5424 	return (retval);
5425 }
5426 
5427 /*
5428  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5429  * we don't really do anything with the LBA and length fields if the user
5430  * passes them in.  Instead we'll just flush out the cache for the entire
5431  * LUN.
5432  */
5433 int
5434 ctl_sync_cache(struct ctl_scsiio *ctsio)
5435 {
5436 	struct ctl_lun *lun = CTL_LUN(ctsio);
5437 	struct ctl_lba_len_flags *lbalen;
5438 	uint64_t starting_lba;
5439 	uint32_t block_count;
5440 	int retval;
5441 	uint8_t byte2;
5442 
5443 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5444 
5445 	retval = 0;
5446 
5447 	switch (ctsio->cdb[0]) {
5448 	case SYNCHRONIZE_CACHE: {
5449 		struct scsi_sync_cache *cdb;
5450 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5451 
5452 		starting_lba = scsi_4btoul(cdb->begin_lba);
5453 		block_count = scsi_2btoul(cdb->lb_count);
5454 		byte2 = cdb->byte2;
5455 		break;
5456 	}
5457 	case SYNCHRONIZE_CACHE_16: {
5458 		struct scsi_sync_cache_16 *cdb;
5459 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5460 
5461 		starting_lba = scsi_8btou64(cdb->begin_lba);
5462 		block_count = scsi_4btoul(cdb->lb_count);
5463 		byte2 = cdb->byte2;
5464 		break;
5465 	}
5466 	default:
5467 		ctl_set_invalid_opcode(ctsio);
5468 		ctl_done((union ctl_io *)ctsio);
5469 		goto bailout;
5470 		break; /* NOTREACHED */
5471 	}
5472 
5473 	/*
5474 	 * We check the LBA and length, but don't do anything with them.
5475 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5476 	 * get flushed.  This check will just help satisfy anyone who wants
5477 	 * to see an error for an out of range LBA.
5478 	 */
5479 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5480 		ctl_set_lba_out_of_range(ctsio,
5481 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5482 		ctl_done((union ctl_io *)ctsio);
5483 		goto bailout;
5484 	}
5485 
5486 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5487 	lbalen->lba = starting_lba;
5488 	lbalen->len = block_count;
5489 	lbalen->flags = byte2;
5490 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5491 
5492 bailout:
5493 	return (retval);
5494 }
5495 
5496 int
5497 ctl_format(struct ctl_scsiio *ctsio)
5498 {
5499 	struct scsi_format *cdb;
5500 	int length, defect_list_len;
5501 
5502 	CTL_DEBUG_PRINT(("ctl_format\n"));
5503 
5504 	cdb = (struct scsi_format *)ctsio->cdb;
5505 
5506 	length = 0;
5507 	if (cdb->byte2 & SF_FMTDATA) {
5508 		if (cdb->byte2 & SF_LONGLIST)
5509 			length = sizeof(struct scsi_format_header_long);
5510 		else
5511 			length = sizeof(struct scsi_format_header_short);
5512 	}
5513 
5514 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5515 	 && (length > 0)) {
5516 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5517 		ctsio->kern_data_len = length;
5518 		ctsio->kern_total_len = length;
5519 		ctsio->kern_rel_offset = 0;
5520 		ctsio->kern_sg_entries = 0;
5521 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5522 		ctsio->be_move_done = ctl_config_move_done;
5523 		ctl_datamove((union ctl_io *)ctsio);
5524 
5525 		return (CTL_RETVAL_COMPLETE);
5526 	}
5527 
5528 	defect_list_len = 0;
5529 
5530 	if (cdb->byte2 & SF_FMTDATA) {
5531 		if (cdb->byte2 & SF_LONGLIST) {
5532 			struct scsi_format_header_long *header;
5533 
5534 			header = (struct scsi_format_header_long *)
5535 				ctsio->kern_data_ptr;
5536 
5537 			defect_list_len = scsi_4btoul(header->defect_list_len);
5538 			if (defect_list_len != 0) {
5539 				ctl_set_invalid_field(ctsio,
5540 						      /*sks_valid*/ 1,
5541 						      /*command*/ 0,
5542 						      /*field*/ 2,
5543 						      /*bit_valid*/ 0,
5544 						      /*bit*/ 0);
5545 				goto bailout;
5546 			}
5547 		} else {
5548 			struct scsi_format_header_short *header;
5549 
5550 			header = (struct scsi_format_header_short *)
5551 				ctsio->kern_data_ptr;
5552 
5553 			defect_list_len = scsi_2btoul(header->defect_list_len);
5554 			if (defect_list_len != 0) {
5555 				ctl_set_invalid_field(ctsio,
5556 						      /*sks_valid*/ 1,
5557 						      /*command*/ 0,
5558 						      /*field*/ 2,
5559 						      /*bit_valid*/ 0,
5560 						      /*bit*/ 0);
5561 				goto bailout;
5562 			}
5563 		}
5564 	}
5565 
5566 	ctl_set_success(ctsio);
5567 bailout:
5568 
5569 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5570 		free(ctsio->kern_data_ptr, M_CTL);
5571 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5572 	}
5573 
5574 	ctl_done((union ctl_io *)ctsio);
5575 	return (CTL_RETVAL_COMPLETE);
5576 }
5577 
5578 int
5579 ctl_read_buffer(struct ctl_scsiio *ctsio)
5580 {
5581 	struct ctl_lun *lun = CTL_LUN(ctsio);
5582 	uint64_t buffer_offset;
5583 	uint32_t len;
5584 	uint8_t byte2;
5585 	static uint8_t descr[4];
5586 	static uint8_t echo_descr[4] = { 0 };
5587 
5588 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5589 
5590 	switch (ctsio->cdb[0]) {
5591 	case READ_BUFFER: {
5592 		struct scsi_read_buffer *cdb;
5593 
5594 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5595 		buffer_offset = scsi_3btoul(cdb->offset);
5596 		len = scsi_3btoul(cdb->length);
5597 		byte2 = cdb->byte2;
5598 		break;
5599 	}
5600 	case READ_BUFFER_16: {
5601 		struct scsi_read_buffer_16 *cdb;
5602 
5603 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5604 		buffer_offset = scsi_8btou64(cdb->offset);
5605 		len = scsi_4btoul(cdb->length);
5606 		byte2 = cdb->byte2;
5607 		break;
5608 	}
5609 	default: /* This shouldn't happen. */
5610 		ctl_set_invalid_opcode(ctsio);
5611 		ctl_done((union ctl_io *)ctsio);
5612 		return (CTL_RETVAL_COMPLETE);
5613 	}
5614 
5615 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5616 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5617 		ctl_set_invalid_field(ctsio,
5618 				      /*sks_valid*/ 1,
5619 				      /*command*/ 1,
5620 				      /*field*/ 6,
5621 				      /*bit_valid*/ 0,
5622 				      /*bit*/ 0);
5623 		ctl_done((union ctl_io *)ctsio);
5624 		return (CTL_RETVAL_COMPLETE);
5625 	}
5626 
5627 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5628 		descr[0] = 0;
5629 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5630 		ctsio->kern_data_ptr = descr;
5631 		len = min(len, sizeof(descr));
5632 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5633 		ctsio->kern_data_ptr = echo_descr;
5634 		len = min(len, sizeof(echo_descr));
5635 	} else {
5636 		if (lun->write_buffer == NULL) {
5637 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5638 			    M_CTL, M_WAITOK);
5639 		}
5640 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5641 	}
5642 	ctsio->kern_data_len = len;
5643 	ctsio->kern_total_len = len;
5644 	ctsio->kern_rel_offset = 0;
5645 	ctsio->kern_sg_entries = 0;
5646 	ctl_set_success(ctsio);
5647 	ctsio->be_move_done = ctl_config_move_done;
5648 	ctl_datamove((union ctl_io *)ctsio);
5649 	return (CTL_RETVAL_COMPLETE);
5650 }
5651 
5652 int
5653 ctl_write_buffer(struct ctl_scsiio *ctsio)
5654 {
5655 	struct ctl_lun *lun = CTL_LUN(ctsio);
5656 	struct scsi_write_buffer *cdb;
5657 	int buffer_offset, len;
5658 
5659 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5660 
5661 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5662 
5663 	len = scsi_3btoul(cdb->length);
5664 	buffer_offset = scsi_3btoul(cdb->offset);
5665 
5666 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5667 		ctl_set_invalid_field(ctsio,
5668 				      /*sks_valid*/ 1,
5669 				      /*command*/ 1,
5670 				      /*field*/ 6,
5671 				      /*bit_valid*/ 0,
5672 				      /*bit*/ 0);
5673 		ctl_done((union ctl_io *)ctsio);
5674 		return (CTL_RETVAL_COMPLETE);
5675 	}
5676 
5677 	/*
5678 	 * If we've got a kernel request that hasn't been malloced yet,
5679 	 * malloc it and tell the caller the data buffer is here.
5680 	 */
5681 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5682 		if (lun->write_buffer == NULL) {
5683 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5684 			    M_CTL, M_WAITOK);
5685 		}
5686 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5687 		ctsio->kern_data_len = len;
5688 		ctsio->kern_total_len = len;
5689 		ctsio->kern_rel_offset = 0;
5690 		ctsio->kern_sg_entries = 0;
5691 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5692 		ctsio->be_move_done = ctl_config_move_done;
5693 		ctl_datamove((union ctl_io *)ctsio);
5694 
5695 		return (CTL_RETVAL_COMPLETE);
5696 	}
5697 
5698 	ctl_set_success(ctsio);
5699 	ctl_done((union ctl_io *)ctsio);
5700 	return (CTL_RETVAL_COMPLETE);
5701 }
5702 
5703 static int
5704 ctl_write_same_cont(union ctl_io *io)
5705 {
5706 	struct ctl_lun *lun = CTL_LUN(io);
5707 	struct ctl_scsiio *ctsio;
5708 	struct ctl_lba_len_flags *lbalen;
5709 	int retval;
5710 
5711 	ctsio = &io->scsiio;
5712 	ctsio->io_hdr.status = CTL_STATUS_NONE;
5713 	lbalen = (struct ctl_lba_len_flags *)
5714 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5715 	lbalen->lba += lbalen->len;
5716 	if ((lun->be_lun->maxlba + 1) - lbalen->lba <= UINT32_MAX) {
5717 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
5718 		lbalen->len = (lun->be_lun->maxlba + 1) - lbalen->lba;
5719 	}
5720 
5721 	CTL_DEBUG_PRINT(("ctl_write_same_cont: calling config_write()\n"));
5722 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5723 	return (retval);
5724 }
5725 
5726 int
5727 ctl_write_same(struct ctl_scsiio *ctsio)
5728 {
5729 	struct ctl_lun *lun = CTL_LUN(ctsio);
5730 	struct ctl_lba_len_flags *lbalen;
5731 	const char *val;
5732 	uint64_t lba, ival;
5733 	uint32_t num_blocks;
5734 	int len, retval;
5735 	uint8_t byte2;
5736 
5737 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5738 
5739 	switch (ctsio->cdb[0]) {
5740 	case WRITE_SAME_10: {
5741 		struct scsi_write_same_10 *cdb;
5742 
5743 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5744 
5745 		lba = scsi_4btoul(cdb->addr);
5746 		num_blocks = scsi_2btoul(cdb->length);
5747 		byte2 = cdb->byte2;
5748 		break;
5749 	}
5750 	case WRITE_SAME_16: {
5751 		struct scsi_write_same_16 *cdb;
5752 
5753 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5754 
5755 		lba = scsi_8btou64(cdb->addr);
5756 		num_blocks = scsi_4btoul(cdb->length);
5757 		byte2 = cdb->byte2;
5758 		break;
5759 	}
5760 	default:
5761 		/*
5762 		 * We got a command we don't support.  This shouldn't
5763 		 * happen, commands should be filtered out above us.
5764 		 */
5765 		ctl_set_invalid_opcode(ctsio);
5766 		ctl_done((union ctl_io *)ctsio);
5767 
5768 		return (CTL_RETVAL_COMPLETE);
5769 		break; /* NOTREACHED */
5770 	}
5771 
5772 	/* ANCHOR flag can be used only together with UNMAP */
5773 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5774 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5775 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5776 		ctl_done((union ctl_io *)ctsio);
5777 		return (CTL_RETVAL_COMPLETE);
5778 	}
5779 
5780 	/*
5781 	 * The first check is to make sure we're in bounds, the second
5782 	 * check is to catch wrap-around problems.  If the lba + num blocks
5783 	 * is less than the lba, then we've wrapped around and the block
5784 	 * range is invalid anyway.
5785 	 */
5786 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5787 	 || ((lba + num_blocks) < lba)) {
5788 		ctl_set_lba_out_of_range(ctsio,
5789 		    MAX(lba, lun->be_lun->maxlba + 1));
5790 		ctl_done((union ctl_io *)ctsio);
5791 		return (CTL_RETVAL_COMPLETE);
5792 	}
5793 
5794 	/* Zero number of blocks means "to the last logical block" */
5795 	if (num_blocks == 0) {
5796 		ival = UINT64_MAX;
5797 		val = dnvlist_get_string(lun->be_lun->options,
5798 		    "write_same_max_lba", NULL);
5799 		if (val != NULL)
5800 			ctl_expand_number(val, &ival);
5801 		if ((lun->be_lun->maxlba + 1) - lba > ival) {
5802 			ctl_set_invalid_field(ctsio,
5803 			    /*sks_valid*/ 1, /*command*/ 1,
5804 			    /*field*/ ctsio->cdb[0] == WRITE_SAME_10 ? 7 : 10,
5805 			    /*bit_valid*/ 0, /*bit*/ 0);
5806 			ctl_done((union ctl_io *)ctsio);
5807 			return (CTL_RETVAL_COMPLETE);
5808 		}
5809 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5810 			ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
5811 			ctsio->io_cont = ctl_write_same_cont;
5812 			num_blocks = 1 << 31;
5813 		} else
5814 			num_blocks = (lun->be_lun->maxlba + 1) - lba;
5815 	}
5816 
5817 	len = lun->be_lun->blocksize;
5818 
5819 	/*
5820 	 * If we've got a kernel request that hasn't been malloced yet,
5821 	 * malloc it and tell the caller the data buffer is here.
5822 	 */
5823 	if ((byte2 & SWS_NDOB) == 0 &&
5824 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5825 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5826 		ctsio->kern_data_len = len;
5827 		ctsio->kern_total_len = len;
5828 		ctsio->kern_rel_offset = 0;
5829 		ctsio->kern_sg_entries = 0;
5830 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5831 		ctsio->be_move_done = ctl_config_move_done;
5832 		ctl_datamove((union ctl_io *)ctsio);
5833 
5834 		return (CTL_RETVAL_COMPLETE);
5835 	}
5836 
5837 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5838 	lbalen->lba = lba;
5839 	lbalen->len = num_blocks;
5840 	lbalen->flags = byte2;
5841 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5842 
5843 	return (retval);
5844 }
5845 
5846 int
5847 ctl_unmap(struct ctl_scsiio *ctsio)
5848 {
5849 	struct ctl_lun *lun = CTL_LUN(ctsio);
5850 	struct scsi_unmap *cdb;
5851 	struct ctl_ptr_len_flags *ptrlen;
5852 	struct scsi_unmap_header *hdr;
5853 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5854 	uint64_t lba;
5855 	uint32_t num_blocks;
5856 	int len, retval;
5857 	uint8_t byte2;
5858 
5859 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5860 
5861 	cdb = (struct scsi_unmap *)ctsio->cdb;
5862 	len = scsi_2btoul(cdb->length);
5863 	byte2 = cdb->byte2;
5864 
5865 	/*
5866 	 * If we've got a kernel request that hasn't been malloced yet,
5867 	 * malloc it and tell the caller the data buffer is here.
5868 	 */
5869 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5870 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5871 		ctsio->kern_data_len = len;
5872 		ctsio->kern_total_len = len;
5873 		ctsio->kern_rel_offset = 0;
5874 		ctsio->kern_sg_entries = 0;
5875 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5876 		ctsio->be_move_done = ctl_config_move_done;
5877 		ctl_datamove((union ctl_io *)ctsio);
5878 
5879 		return (CTL_RETVAL_COMPLETE);
5880 	}
5881 
5882 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5883 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5884 	if (len < sizeof (*hdr) ||
5885 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5886 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5887 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5888 		ctl_set_invalid_field(ctsio,
5889 				      /*sks_valid*/ 0,
5890 				      /*command*/ 0,
5891 				      /*field*/ 0,
5892 				      /*bit_valid*/ 0,
5893 				      /*bit*/ 0);
5894 		goto done;
5895 	}
5896 	len = scsi_2btoul(hdr->desc_length);
5897 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5898 	end = buf + len / sizeof(*buf);
5899 
5900 	endnz = buf;
5901 	for (range = buf; range < end; range++) {
5902 		lba = scsi_8btou64(range->lba);
5903 		num_blocks = scsi_4btoul(range->length);
5904 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5905 		 || ((lba + num_blocks) < lba)) {
5906 			ctl_set_lba_out_of_range(ctsio,
5907 			    MAX(lba, lun->be_lun->maxlba + 1));
5908 			ctl_done((union ctl_io *)ctsio);
5909 			return (CTL_RETVAL_COMPLETE);
5910 		}
5911 		if (num_blocks != 0)
5912 			endnz = range + 1;
5913 	}
5914 
5915 	/*
5916 	 * Block backend can not handle zero last range.
5917 	 * Filter it out and return if there is nothing left.
5918 	 */
5919 	len = (uint8_t *)endnz - (uint8_t *)buf;
5920 	if (len == 0) {
5921 		ctl_set_success(ctsio);
5922 		goto done;
5923 	}
5924 
5925 	mtx_lock(&lun->lun_lock);
5926 	ptrlen = (struct ctl_ptr_len_flags *)
5927 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5928 	ptrlen->ptr = (void *)buf;
5929 	ptrlen->len = len;
5930 	ptrlen->flags = byte2;
5931 	ctl_try_unblock_others(lun, (union ctl_io *)ctsio, FALSE);
5932 	mtx_unlock(&lun->lun_lock);
5933 
5934 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5935 	return (retval);
5936 
5937 done:
5938 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5939 		free(ctsio->kern_data_ptr, M_CTL);
5940 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5941 	}
5942 	ctl_done((union ctl_io *)ctsio);
5943 	return (CTL_RETVAL_COMPLETE);
5944 }
5945 
5946 int
5947 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5948 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5949 {
5950 	struct ctl_lun *lun = CTL_LUN(ctsio);
5951 	uint8_t *current_cp;
5952 	int set_ua;
5953 	uint32_t initidx;
5954 
5955 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5956 	set_ua = 0;
5957 
5958 	current_cp = (page_index->page_data + (page_index->page_len *
5959 	    CTL_PAGE_CURRENT));
5960 
5961 	mtx_lock(&lun->lun_lock);
5962 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5963 		memcpy(current_cp, page_ptr, page_index->page_len);
5964 		set_ua = 1;
5965 	}
5966 	if (set_ua != 0)
5967 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5968 	mtx_unlock(&lun->lun_lock);
5969 	if (set_ua) {
5970 		ctl_isc_announce_mode(lun,
5971 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5972 		    page_index->page_code, page_index->subpage);
5973 	}
5974 	return (CTL_RETVAL_COMPLETE);
5975 }
5976 
5977 static void
5978 ctl_ie_timer(void *arg)
5979 {
5980 	struct ctl_lun *lun = arg;
5981 	uint64_t t;
5982 
5983 	if (lun->ie_asc == 0)
5984 		return;
5985 
5986 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5987 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5988 	else
5989 		lun->ie_reported = 0;
5990 
5991 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5992 		lun->ie_reportcnt++;
5993 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5994 		if (t == 0 || t == UINT32_MAX)
5995 			t = 3000;  /* 5 min */
5996 		callout_schedule_sbt(&lun->ie_callout, SBT_1S / 10 * t,
5997 		    SBT_1S / 10, 0);
5998 	}
5999 }
6000 
6001 int
6002 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
6003 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6004 {
6005 	struct ctl_lun *lun = CTL_LUN(ctsio);
6006 	struct scsi_info_exceptions_page *pg;
6007 	uint64_t t;
6008 
6009 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
6010 
6011 	pg = (struct scsi_info_exceptions_page *)page_ptr;
6012 	mtx_lock(&lun->lun_lock);
6013 	if (pg->info_flags & SIEP_FLAGS_TEST) {
6014 		lun->ie_asc = 0x5d;
6015 		lun->ie_ascq = 0xff;
6016 		if (pg->mrie == SIEP_MRIE_UA) {
6017 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
6018 			lun->ie_reported = 1;
6019 		} else {
6020 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
6021 			lun->ie_reported = -1;
6022 		}
6023 		lun->ie_reportcnt = 1;
6024 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
6025 			lun->ie_reportcnt++;
6026 			t = scsi_4btoul(pg->interval_timer);
6027 			if (t == 0 || t == UINT32_MAX)
6028 				t = 3000;  /* 5 min */
6029 			callout_reset_sbt(&lun->ie_callout, SBT_1S / 10 * t,
6030 			    SBT_1S / 10, ctl_ie_timer, lun, 0);
6031 		}
6032 	} else {
6033 		lun->ie_asc = 0;
6034 		lun->ie_ascq = 0;
6035 		lun->ie_reported = 1;
6036 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
6037 		lun->ie_reportcnt = UINT32_MAX;
6038 		callout_stop(&lun->ie_callout);
6039 	}
6040 	mtx_unlock(&lun->lun_lock);
6041 	return (CTL_RETVAL_COMPLETE);
6042 }
6043 
6044 static int
6045 ctl_do_mode_select(union ctl_io *io)
6046 {
6047 	struct ctl_lun *lun = CTL_LUN(io);
6048 	struct scsi_mode_page_header *page_header;
6049 	struct ctl_page_index *page_index;
6050 	struct ctl_scsiio *ctsio;
6051 	int page_len, page_len_offset, page_len_size;
6052 	union ctl_modepage_info *modepage_info;
6053 	uint16_t *len_left, *len_used;
6054 	int retval, i;
6055 
6056 	ctsio = &io->scsiio;
6057 	page_index = NULL;
6058 	page_len = 0;
6059 
6060 	modepage_info = (union ctl_modepage_info *)
6061 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6062 	len_left = &modepage_info->header.len_left;
6063 	len_used = &modepage_info->header.len_used;
6064 
6065 do_next_page:
6066 
6067 	page_header = (struct scsi_mode_page_header *)
6068 		(ctsio->kern_data_ptr + *len_used);
6069 
6070 	if (*len_left == 0) {
6071 		free(ctsio->kern_data_ptr, M_CTL);
6072 		ctl_set_success(ctsio);
6073 		ctl_done((union ctl_io *)ctsio);
6074 		return (CTL_RETVAL_COMPLETE);
6075 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6076 		free(ctsio->kern_data_ptr, M_CTL);
6077 		ctl_set_param_len_error(ctsio);
6078 		ctl_done((union ctl_io *)ctsio);
6079 		return (CTL_RETVAL_COMPLETE);
6080 
6081 	} else if ((page_header->page_code & SMPH_SPF)
6082 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6083 		free(ctsio->kern_data_ptr, M_CTL);
6084 		ctl_set_param_len_error(ctsio);
6085 		ctl_done((union ctl_io *)ctsio);
6086 		return (CTL_RETVAL_COMPLETE);
6087 	}
6088 
6089 	/*
6090 	 * XXX KDM should we do something with the block descriptor?
6091 	 */
6092 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6093 		page_index = &lun->mode_pages.index[i];
6094 		if (lun->be_lun->lun_type == T_DIRECT &&
6095 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6096 			continue;
6097 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6098 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6099 			continue;
6100 		if (lun->be_lun->lun_type == T_CDROM &&
6101 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6102 			continue;
6103 
6104 		if ((page_index->page_code & SMPH_PC_MASK) !=
6105 		    (page_header->page_code & SMPH_PC_MASK))
6106 			continue;
6107 
6108 		/*
6109 		 * If neither page has a subpage code, then we've got a
6110 		 * match.
6111 		 */
6112 		if (((page_index->page_code & SMPH_SPF) == 0)
6113 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6114 			page_len = page_header->page_length;
6115 			break;
6116 		}
6117 
6118 		/*
6119 		 * If both pages have subpages, then the subpage numbers
6120 		 * have to match.
6121 		 */
6122 		if ((page_index->page_code & SMPH_SPF)
6123 		  && (page_header->page_code & SMPH_SPF)) {
6124 			struct scsi_mode_page_header_sp *sph;
6125 
6126 			sph = (struct scsi_mode_page_header_sp *)page_header;
6127 			if (page_index->subpage == sph->subpage) {
6128 				page_len = scsi_2btoul(sph->page_length);
6129 				break;
6130 			}
6131 		}
6132 	}
6133 
6134 	/*
6135 	 * If we couldn't find the page, or if we don't have a mode select
6136 	 * handler for it, send back an error to the user.
6137 	 */
6138 	if ((i >= CTL_NUM_MODE_PAGES)
6139 	 || (page_index->select_handler == NULL)) {
6140 		ctl_set_invalid_field(ctsio,
6141 				      /*sks_valid*/ 1,
6142 				      /*command*/ 0,
6143 				      /*field*/ *len_used,
6144 				      /*bit_valid*/ 0,
6145 				      /*bit*/ 0);
6146 		free(ctsio->kern_data_ptr, M_CTL);
6147 		ctl_done((union ctl_io *)ctsio);
6148 		return (CTL_RETVAL_COMPLETE);
6149 	}
6150 
6151 	if (page_index->page_code & SMPH_SPF) {
6152 		page_len_offset = 2;
6153 		page_len_size = 2;
6154 	} else {
6155 		page_len_size = 1;
6156 		page_len_offset = 1;
6157 	}
6158 
6159 	/*
6160 	 * If the length the initiator gives us isn't the one we specify in
6161 	 * the mode page header, or if they didn't specify enough data in
6162 	 * the CDB to avoid truncating this page, kick out the request.
6163 	 */
6164 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6165 		ctl_set_invalid_field(ctsio,
6166 				      /*sks_valid*/ 1,
6167 				      /*command*/ 0,
6168 				      /*field*/ *len_used + page_len_offset,
6169 				      /*bit_valid*/ 0,
6170 				      /*bit*/ 0);
6171 		free(ctsio->kern_data_ptr, M_CTL);
6172 		ctl_done((union ctl_io *)ctsio);
6173 		return (CTL_RETVAL_COMPLETE);
6174 	}
6175 	if (*len_left < page_index->page_len) {
6176 		free(ctsio->kern_data_ptr, M_CTL);
6177 		ctl_set_param_len_error(ctsio);
6178 		ctl_done((union ctl_io *)ctsio);
6179 		return (CTL_RETVAL_COMPLETE);
6180 	}
6181 
6182 	/*
6183 	 * Run through the mode page, checking to make sure that the bits
6184 	 * the user changed are actually legal for him to change.
6185 	 */
6186 	for (i = 0; i < page_index->page_len; i++) {
6187 		uint8_t *user_byte, *change_mask, *current_byte;
6188 		int bad_bit;
6189 		int j;
6190 
6191 		user_byte = (uint8_t *)page_header + i;
6192 		change_mask = page_index->page_data +
6193 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6194 		current_byte = page_index->page_data +
6195 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6196 
6197 		/*
6198 		 * Check to see whether the user set any bits in this byte
6199 		 * that he is not allowed to set.
6200 		 */
6201 		if ((*user_byte & ~(*change_mask)) ==
6202 		    (*current_byte & ~(*change_mask)))
6203 			continue;
6204 
6205 		/*
6206 		 * Go through bit by bit to determine which one is illegal.
6207 		 */
6208 		bad_bit = 0;
6209 		for (j = 7; j >= 0; j--) {
6210 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6211 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6212 				bad_bit = i;
6213 				break;
6214 			}
6215 		}
6216 		ctl_set_invalid_field(ctsio,
6217 				      /*sks_valid*/ 1,
6218 				      /*command*/ 0,
6219 				      /*field*/ *len_used + i,
6220 				      /*bit_valid*/ 1,
6221 				      /*bit*/ bad_bit);
6222 		free(ctsio->kern_data_ptr, M_CTL);
6223 		ctl_done((union ctl_io *)ctsio);
6224 		return (CTL_RETVAL_COMPLETE);
6225 	}
6226 
6227 	/*
6228 	 * Decrement these before we call the page handler, since we may
6229 	 * end up getting called back one way or another before the handler
6230 	 * returns to this context.
6231 	 */
6232 	*len_left -= page_index->page_len;
6233 	*len_used += page_index->page_len;
6234 
6235 	retval = page_index->select_handler(ctsio, page_index,
6236 					    (uint8_t *)page_header);
6237 
6238 	/*
6239 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6240 	 * wait until this queued command completes to finish processing
6241 	 * the mode page.  If it returns anything other than
6242 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6243 	 * already set the sense information, freed the data pointer, and
6244 	 * completed the io for us.
6245 	 */
6246 	if (retval != CTL_RETVAL_COMPLETE)
6247 		goto bailout_no_done;
6248 
6249 	/*
6250 	 * If the initiator sent us more than one page, parse the next one.
6251 	 */
6252 	if (*len_left > 0)
6253 		goto do_next_page;
6254 
6255 	ctl_set_success(ctsio);
6256 	free(ctsio->kern_data_ptr, M_CTL);
6257 	ctl_done((union ctl_io *)ctsio);
6258 
6259 bailout_no_done:
6260 
6261 	return (CTL_RETVAL_COMPLETE);
6262 
6263 }
6264 
6265 int
6266 ctl_mode_select(struct ctl_scsiio *ctsio)
6267 {
6268 	struct ctl_lun *lun = CTL_LUN(ctsio);
6269 	union ctl_modepage_info *modepage_info;
6270 	int bd_len, i, header_size, param_len, rtd;
6271 	uint32_t initidx;
6272 
6273 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6274 	switch (ctsio->cdb[0]) {
6275 	case MODE_SELECT_6: {
6276 		struct scsi_mode_select_6 *cdb;
6277 
6278 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6279 
6280 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6281 		param_len = cdb->length;
6282 		header_size = sizeof(struct scsi_mode_header_6);
6283 		break;
6284 	}
6285 	case MODE_SELECT_10: {
6286 		struct scsi_mode_select_10 *cdb;
6287 
6288 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6289 
6290 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6291 		param_len = scsi_2btoul(cdb->length);
6292 		header_size = sizeof(struct scsi_mode_header_10);
6293 		break;
6294 	}
6295 	default:
6296 		ctl_set_invalid_opcode(ctsio);
6297 		ctl_done((union ctl_io *)ctsio);
6298 		return (CTL_RETVAL_COMPLETE);
6299 	}
6300 
6301 	if (rtd) {
6302 		if (param_len != 0) {
6303 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6304 			    /*command*/ 1, /*field*/ 0,
6305 			    /*bit_valid*/ 0, /*bit*/ 0);
6306 			ctl_done((union ctl_io *)ctsio);
6307 			return (CTL_RETVAL_COMPLETE);
6308 		}
6309 
6310 		/* Revert to defaults. */
6311 		ctl_init_page_index(lun);
6312 		mtx_lock(&lun->lun_lock);
6313 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6314 		mtx_unlock(&lun->lun_lock);
6315 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6316 			ctl_isc_announce_mode(lun, -1,
6317 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6318 			    lun->mode_pages.index[i].subpage);
6319 		}
6320 		ctl_set_success(ctsio);
6321 		ctl_done((union ctl_io *)ctsio);
6322 		return (CTL_RETVAL_COMPLETE);
6323 	}
6324 
6325 	/*
6326 	 * From SPC-3:
6327 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6328 	 * shall be empty. This condition shall not be considered as an error."
6329 	 */
6330 	if (param_len == 0) {
6331 		ctl_set_success(ctsio);
6332 		ctl_done((union ctl_io *)ctsio);
6333 		return (CTL_RETVAL_COMPLETE);
6334 	}
6335 
6336 	/*
6337 	 * Since we'll hit this the first time through, prior to
6338 	 * allocation, we don't need to free a data buffer here.
6339 	 */
6340 	if (param_len < header_size) {
6341 		ctl_set_param_len_error(ctsio);
6342 		ctl_done((union ctl_io *)ctsio);
6343 		return (CTL_RETVAL_COMPLETE);
6344 	}
6345 
6346 	/*
6347 	 * Allocate the data buffer and grab the user's data.  In theory,
6348 	 * we shouldn't have to sanity check the parameter list length here
6349 	 * because the maximum size is 64K.  We should be able to malloc
6350 	 * that much without too many problems.
6351 	 */
6352 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6353 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6354 		ctsio->kern_data_len = param_len;
6355 		ctsio->kern_total_len = param_len;
6356 		ctsio->kern_rel_offset = 0;
6357 		ctsio->kern_sg_entries = 0;
6358 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6359 		ctsio->be_move_done = ctl_config_move_done;
6360 		ctl_datamove((union ctl_io *)ctsio);
6361 
6362 		return (CTL_RETVAL_COMPLETE);
6363 	}
6364 
6365 	switch (ctsio->cdb[0]) {
6366 	case MODE_SELECT_6: {
6367 		struct scsi_mode_header_6 *mh6;
6368 
6369 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6370 		bd_len = mh6->blk_desc_len;
6371 		break;
6372 	}
6373 	case MODE_SELECT_10: {
6374 		struct scsi_mode_header_10 *mh10;
6375 
6376 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6377 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6378 		break;
6379 	}
6380 	default:
6381 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6382 	}
6383 
6384 	if (param_len < (header_size + bd_len)) {
6385 		free(ctsio->kern_data_ptr, M_CTL);
6386 		ctl_set_param_len_error(ctsio);
6387 		ctl_done((union ctl_io *)ctsio);
6388 		return (CTL_RETVAL_COMPLETE);
6389 	}
6390 
6391 	/*
6392 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6393 	 * ctl_config_write_done(), it'll get passed back to
6394 	 * ctl_do_mode_select() for further processing, or completion if
6395 	 * we're all done.
6396 	 */
6397 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6398 	ctsio->io_cont = ctl_do_mode_select;
6399 
6400 	modepage_info = (union ctl_modepage_info *)
6401 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6402 	memset(modepage_info, 0, sizeof(*modepage_info));
6403 	modepage_info->header.len_left = param_len - header_size - bd_len;
6404 	modepage_info->header.len_used = header_size + bd_len;
6405 
6406 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6407 }
6408 
6409 int
6410 ctl_mode_sense(struct ctl_scsiio *ctsio)
6411 {
6412 	struct ctl_lun *lun = CTL_LUN(ctsio);
6413 	int pc, page_code, llba, subpage;
6414 	int alloc_len, page_len, header_len, bd_len, total_len;
6415 	void *block_desc;
6416 	struct ctl_page_index *page_index;
6417 
6418 	llba = 0;
6419 
6420 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6421 
6422 	switch (ctsio->cdb[0]) {
6423 	case MODE_SENSE_6: {
6424 		struct scsi_mode_sense_6 *cdb;
6425 
6426 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6427 
6428 		header_len = sizeof(struct scsi_mode_hdr_6);
6429 		if (cdb->byte2 & SMS_DBD)
6430 			bd_len = 0;
6431 		else
6432 			bd_len = sizeof(struct scsi_mode_block_descr);
6433 		header_len += bd_len;
6434 
6435 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6436 		page_code = cdb->page & SMS_PAGE_CODE;
6437 		subpage = cdb->subpage;
6438 		alloc_len = cdb->length;
6439 		break;
6440 	}
6441 	case MODE_SENSE_10: {
6442 		struct scsi_mode_sense_10 *cdb;
6443 
6444 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6445 
6446 		header_len = sizeof(struct scsi_mode_hdr_10);
6447 		if (cdb->byte2 & SMS_DBD) {
6448 			bd_len = 0;
6449 		} else if (lun->be_lun->lun_type == T_DIRECT) {
6450 			if (cdb->byte2 & SMS10_LLBAA) {
6451 				llba = 1;
6452 				bd_len = sizeof(struct scsi_mode_block_descr_dlong);
6453 			} else
6454 				bd_len = sizeof(struct scsi_mode_block_descr_dshort);
6455 		} else
6456 			bd_len = sizeof(struct scsi_mode_block_descr);
6457 		header_len += bd_len;
6458 
6459 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6460 		page_code = cdb->page & SMS_PAGE_CODE;
6461 		subpage = cdb->subpage;
6462 		alloc_len = scsi_2btoul(cdb->length);
6463 		break;
6464 	}
6465 	default:
6466 		ctl_set_invalid_opcode(ctsio);
6467 		ctl_done((union ctl_io *)ctsio);
6468 		return (CTL_RETVAL_COMPLETE);
6469 		break; /* NOTREACHED */
6470 	}
6471 
6472 	/*
6473 	 * We have to make a first pass through to calculate the size of
6474 	 * the pages that match the user's query.  Then we allocate enough
6475 	 * memory to hold it, and actually copy the data into the buffer.
6476 	 */
6477 	switch (page_code) {
6478 	case SMS_ALL_PAGES_PAGE: {
6479 		u_int i;
6480 
6481 		page_len = 0;
6482 
6483 		/*
6484 		 * At the moment, values other than 0 and 0xff here are
6485 		 * reserved according to SPC-3.
6486 		 */
6487 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6488 		 && (subpage != SMS_SUBPAGE_ALL)) {
6489 			ctl_set_invalid_field(ctsio,
6490 					      /*sks_valid*/ 1,
6491 					      /*command*/ 1,
6492 					      /*field*/ 3,
6493 					      /*bit_valid*/ 0,
6494 					      /*bit*/ 0);
6495 			ctl_done((union ctl_io *)ctsio);
6496 			return (CTL_RETVAL_COMPLETE);
6497 		}
6498 
6499 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6500 			page_index = &lun->mode_pages.index[i];
6501 
6502 			/* Make sure the page is supported for this dev type */
6503 			if (lun->be_lun->lun_type == T_DIRECT &&
6504 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6505 				continue;
6506 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6507 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6508 				continue;
6509 			if (lun->be_lun->lun_type == T_CDROM &&
6510 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6511 				continue;
6512 
6513 			/*
6514 			 * We don't use this subpage if the user didn't
6515 			 * request all subpages.
6516 			 */
6517 			if ((page_index->subpage != 0)
6518 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6519 				continue;
6520 
6521 			page_len += page_index->page_len;
6522 		}
6523 		break;
6524 	}
6525 	default: {
6526 		u_int i;
6527 
6528 		page_len = 0;
6529 
6530 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6531 			page_index = &lun->mode_pages.index[i];
6532 
6533 			/* Make sure the page is supported for this dev type */
6534 			if (lun->be_lun->lun_type == T_DIRECT &&
6535 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6536 				continue;
6537 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6538 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6539 				continue;
6540 			if (lun->be_lun->lun_type == T_CDROM &&
6541 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6542 				continue;
6543 
6544 			/* Look for the right page code */
6545 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6546 				continue;
6547 
6548 			/* Look for the right subpage or the subpage wildcard*/
6549 			if ((page_index->subpage != subpage)
6550 			 && (subpage != SMS_SUBPAGE_ALL))
6551 				continue;
6552 
6553 			page_len += page_index->page_len;
6554 		}
6555 
6556 		if (page_len == 0) {
6557 			ctl_set_invalid_field(ctsio,
6558 					      /*sks_valid*/ 1,
6559 					      /*command*/ 1,
6560 					      /*field*/ 2,
6561 					      /*bit_valid*/ 1,
6562 					      /*bit*/ 5);
6563 			ctl_done((union ctl_io *)ctsio);
6564 			return (CTL_RETVAL_COMPLETE);
6565 		}
6566 		break;
6567 	}
6568 	}
6569 
6570 	total_len = header_len + page_len;
6571 
6572 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6573 	ctsio->kern_sg_entries = 0;
6574 	ctsio->kern_rel_offset = 0;
6575 	ctsio->kern_data_len = min(total_len, alloc_len);
6576 	ctsio->kern_total_len = ctsio->kern_data_len;
6577 
6578 	switch (ctsio->cdb[0]) {
6579 	case MODE_SENSE_6: {
6580 		struct scsi_mode_hdr_6 *header;
6581 
6582 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6583 
6584 		header->datalen = MIN(total_len - 1, 254);
6585 		if (lun->be_lun->lun_type == T_DIRECT) {
6586 			header->dev_specific = 0x10; /* DPOFUA */
6587 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6588 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6589 				header->dev_specific |= 0x80; /* WP */
6590 		}
6591 		header->block_descr_len = bd_len;
6592 		block_desc = &header[1];
6593 		break;
6594 	}
6595 	case MODE_SENSE_10: {
6596 		struct scsi_mode_hdr_10 *header;
6597 		int datalen;
6598 
6599 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6600 
6601 		datalen = MIN(total_len - 2, 65533);
6602 		scsi_ulto2b(datalen, header->datalen);
6603 		if (lun->be_lun->lun_type == T_DIRECT) {
6604 			header->dev_specific = 0x10; /* DPOFUA */
6605 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6606 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6607 				header->dev_specific |= 0x80; /* WP */
6608 		}
6609 		if (llba)
6610 			header->flags |= SMH_LONGLBA;
6611 		scsi_ulto2b(bd_len, header->block_descr_len);
6612 		block_desc = &header[1];
6613 		break;
6614 	}
6615 	default:
6616 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6617 	}
6618 
6619 	/*
6620 	 * If we've got a disk, use its blocksize in the block
6621 	 * descriptor.  Otherwise, just set it to 0.
6622 	 */
6623 	if (bd_len > 0) {
6624 		if (lun->be_lun->lun_type == T_DIRECT) {
6625 			if (llba) {
6626 				struct scsi_mode_block_descr_dlong *bd = block_desc;
6627 				if (lun->be_lun->maxlba != 0)
6628 					scsi_u64to8b(lun->be_lun->maxlba + 1,
6629 					    bd->num_blocks);
6630 				scsi_ulto4b(lun->be_lun->blocksize,
6631 				    bd->block_len);
6632 			} else {
6633 				struct scsi_mode_block_descr_dshort *bd = block_desc;
6634 				if (lun->be_lun->maxlba != 0)
6635 					scsi_ulto4b(MIN(lun->be_lun->maxlba+1,
6636 					    UINT32_MAX), bd->num_blocks);
6637 				scsi_ulto3b(lun->be_lun->blocksize,
6638 				    bd->block_len);
6639 			}
6640 		} else {
6641 			struct scsi_mode_block_descr *bd = block_desc;
6642 			scsi_ulto3b(0, bd->block_len);
6643 		}
6644 	}
6645 
6646 	switch (page_code) {
6647 	case SMS_ALL_PAGES_PAGE: {
6648 		int i, data_used;
6649 
6650 		data_used = header_len;
6651 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6652 			struct ctl_page_index *page_index;
6653 
6654 			page_index = &lun->mode_pages.index[i];
6655 			if (lun->be_lun->lun_type == T_DIRECT &&
6656 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6657 				continue;
6658 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6659 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6660 				continue;
6661 			if (lun->be_lun->lun_type == T_CDROM &&
6662 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6663 				continue;
6664 
6665 			/*
6666 			 * We don't use this subpage if the user didn't
6667 			 * request all subpages.  We already checked (above)
6668 			 * to make sure the user only specified a subpage
6669 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6670 			 */
6671 			if ((page_index->subpage != 0)
6672 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6673 				continue;
6674 
6675 			/*
6676 			 * Call the handler, if it exists, to update the
6677 			 * page to the latest values.
6678 			 */
6679 			if (page_index->sense_handler != NULL)
6680 				page_index->sense_handler(ctsio, page_index,pc);
6681 
6682 			memcpy(ctsio->kern_data_ptr + data_used,
6683 			       page_index->page_data +
6684 			       (page_index->page_len * pc),
6685 			       page_index->page_len);
6686 			data_used += page_index->page_len;
6687 		}
6688 		break;
6689 	}
6690 	default: {
6691 		int i, data_used;
6692 
6693 		data_used = header_len;
6694 
6695 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6696 			struct ctl_page_index *page_index;
6697 
6698 			page_index = &lun->mode_pages.index[i];
6699 
6700 			/* Look for the right page code */
6701 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6702 				continue;
6703 
6704 			/* Look for the right subpage or the subpage wildcard*/
6705 			if ((page_index->subpage != subpage)
6706 			 && (subpage != SMS_SUBPAGE_ALL))
6707 				continue;
6708 
6709 			/* Make sure the page is supported for this dev type */
6710 			if (lun->be_lun->lun_type == T_DIRECT &&
6711 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6712 				continue;
6713 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6714 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6715 				continue;
6716 			if (lun->be_lun->lun_type == T_CDROM &&
6717 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6718 				continue;
6719 
6720 			/*
6721 			 * Call the handler, if it exists, to update the
6722 			 * page to the latest values.
6723 			 */
6724 			if (page_index->sense_handler != NULL)
6725 				page_index->sense_handler(ctsio, page_index,pc);
6726 
6727 			memcpy(ctsio->kern_data_ptr + data_used,
6728 			       page_index->page_data +
6729 			       (page_index->page_len * pc),
6730 			       page_index->page_len);
6731 			data_used += page_index->page_len;
6732 		}
6733 		break;
6734 	}
6735 	}
6736 
6737 	ctl_set_success(ctsio);
6738 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6739 	ctsio->be_move_done = ctl_config_move_done;
6740 	ctl_datamove((union ctl_io *)ctsio);
6741 	return (CTL_RETVAL_COMPLETE);
6742 }
6743 
6744 int
6745 ctl_temp_log_sense_handler(struct ctl_scsiio *ctsio,
6746 			       struct ctl_page_index *page_index,
6747 			       int pc)
6748 {
6749 	struct ctl_lun *lun = CTL_LUN(ctsio);
6750 	struct scsi_log_temperature *data;
6751 	const char *value;
6752 
6753 	data = (struct scsi_log_temperature *)page_index->page_data;
6754 
6755 	scsi_ulto2b(SLP_TEMPERATURE, data->hdr.param_code);
6756 	data->hdr.param_control = SLP_LBIN;
6757 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6758 	    sizeof(struct scsi_log_param_header);
6759 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6760 	    NULL)) != NULL)
6761 		data->temperature = strtol(value, NULL, 0);
6762 	else
6763 		data->temperature = 0xff;
6764 	data++;
6765 
6766 	scsi_ulto2b(SLP_REFTEMPERATURE, data->hdr.param_code);
6767 	data->hdr.param_control = SLP_LBIN;
6768 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6769 	    sizeof(struct scsi_log_param_header);
6770 	if ((value = dnvlist_get_string(lun->be_lun->options, "reftemperature",
6771 	    NULL)) != NULL)
6772 		data->temperature = strtol(value, NULL, 0);
6773 	else
6774 		data->temperature = 0xff;
6775 	return (0);
6776 }
6777 
6778 int
6779 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6780 			       struct ctl_page_index *page_index,
6781 			       int pc)
6782 {
6783 	struct ctl_lun *lun = CTL_LUN(ctsio);
6784 	struct scsi_log_param_header *phdr;
6785 	uint8_t *data;
6786 	uint64_t val;
6787 
6788 	data = page_index->page_data;
6789 
6790 	if (lun->backend->lun_attr != NULL &&
6791 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksavail"))
6792 	     != UINT64_MAX) {
6793 		phdr = (struct scsi_log_param_header *)data;
6794 		scsi_ulto2b(0x0001, phdr->param_code);
6795 		phdr->param_control = SLP_LBIN | SLP_LP;
6796 		phdr->param_len = 8;
6797 		data = (uint8_t *)(phdr + 1);
6798 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6799 		data[4] = 0x02; /* per-pool */
6800 		data += phdr->param_len;
6801 	}
6802 
6803 	if (lun->backend->lun_attr != NULL &&
6804 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksused"))
6805 	     != UINT64_MAX) {
6806 		phdr = (struct scsi_log_param_header *)data;
6807 		scsi_ulto2b(0x0002, phdr->param_code);
6808 		phdr->param_control = SLP_LBIN | SLP_LP;
6809 		phdr->param_len = 8;
6810 		data = (uint8_t *)(phdr + 1);
6811 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6812 		data[4] = 0x01; /* per-LUN */
6813 		data += phdr->param_len;
6814 	}
6815 
6816 	if (lun->backend->lun_attr != NULL &&
6817 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksavail"))
6818 	     != UINT64_MAX) {
6819 		phdr = (struct scsi_log_param_header *)data;
6820 		scsi_ulto2b(0x00f1, phdr->param_code);
6821 		phdr->param_control = SLP_LBIN | SLP_LP;
6822 		phdr->param_len = 8;
6823 		data = (uint8_t *)(phdr + 1);
6824 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6825 		data[4] = 0x02; /* per-pool */
6826 		data += phdr->param_len;
6827 	}
6828 
6829 	if (lun->backend->lun_attr != NULL &&
6830 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksused"))
6831 	     != UINT64_MAX) {
6832 		phdr = (struct scsi_log_param_header *)data;
6833 		scsi_ulto2b(0x00f2, phdr->param_code);
6834 		phdr->param_control = SLP_LBIN | SLP_LP;
6835 		phdr->param_len = 8;
6836 		data = (uint8_t *)(phdr + 1);
6837 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6838 		data[4] = 0x02; /* per-pool */
6839 		data += phdr->param_len;
6840 	}
6841 
6842 	page_index->page_len = data - page_index->page_data;
6843 	return (0);
6844 }
6845 
6846 int
6847 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6848 			       struct ctl_page_index *page_index,
6849 			       int pc)
6850 {
6851 	struct ctl_lun *lun = CTL_LUN(ctsio);
6852 	struct stat_page *data;
6853 	struct bintime *t;
6854 
6855 	data = (struct stat_page *)page_index->page_data;
6856 
6857 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6858 	data->sap.hdr.param_control = SLP_LBIN;
6859 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6860 	    sizeof(struct scsi_log_param_header);
6861 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6862 	    data->sap.read_num);
6863 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6864 	    data->sap.write_num);
6865 	if (lun->be_lun->blocksize > 0) {
6866 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6867 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6868 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6869 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6870 	}
6871 	t = &lun->stats.time[CTL_STATS_READ];
6872 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6873 	    data->sap.read_int);
6874 	t = &lun->stats.time[CTL_STATS_WRITE];
6875 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6876 	    data->sap.write_int);
6877 	scsi_u64to8b(0, data->sap.weighted_num);
6878 	scsi_u64to8b(0, data->sap.weighted_int);
6879 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6880 	data->it.hdr.param_control = SLP_LBIN;
6881 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6882 	    sizeof(struct scsi_log_param_header);
6883 #ifdef CTL_TIME_IO
6884 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6885 #endif
6886 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6887 	data->it.hdr.param_control = SLP_LBIN;
6888 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6889 	    sizeof(struct scsi_log_param_header);
6890 	scsi_ulto4b(3, data->ti.exponent);
6891 	scsi_ulto4b(1, data->ti.integer);
6892 	return (0);
6893 }
6894 
6895 int
6896 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6897 			       struct ctl_page_index *page_index,
6898 			       int pc)
6899 {
6900 	struct ctl_lun *lun = CTL_LUN(ctsio);
6901 	struct scsi_log_informational_exceptions *data;
6902 	const char *value;
6903 
6904 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6905 
6906 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6907 	data->hdr.param_control = SLP_LBIN;
6908 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6909 	    sizeof(struct scsi_log_param_header);
6910 	data->ie_asc = lun->ie_asc;
6911 	data->ie_ascq = lun->ie_ascq;
6912 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6913 	    NULL)) != NULL)
6914 		data->temperature = strtol(value, NULL, 0);
6915 	else
6916 		data->temperature = 0xff;
6917 	return (0);
6918 }
6919 
6920 int
6921 ctl_log_sense(struct ctl_scsiio *ctsio)
6922 {
6923 	struct ctl_lun *lun = CTL_LUN(ctsio);
6924 	int i, pc, page_code, subpage;
6925 	int alloc_len, total_len;
6926 	struct ctl_page_index *page_index;
6927 	struct scsi_log_sense *cdb;
6928 	struct scsi_log_header *header;
6929 
6930 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6931 
6932 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6933 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6934 	page_code = cdb->page & SLS_PAGE_CODE;
6935 	subpage = cdb->subpage;
6936 	alloc_len = scsi_2btoul(cdb->length);
6937 
6938 	page_index = NULL;
6939 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6940 		page_index = &lun->log_pages.index[i];
6941 
6942 		/* Look for the right page code */
6943 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6944 			continue;
6945 
6946 		/* Look for the right subpage or the subpage wildcard*/
6947 		if (page_index->subpage != subpage)
6948 			continue;
6949 
6950 		break;
6951 	}
6952 	if (i >= CTL_NUM_LOG_PAGES) {
6953 		ctl_set_invalid_field(ctsio,
6954 				      /*sks_valid*/ 1,
6955 				      /*command*/ 1,
6956 				      /*field*/ 2,
6957 				      /*bit_valid*/ 0,
6958 				      /*bit*/ 0);
6959 		ctl_done((union ctl_io *)ctsio);
6960 		return (CTL_RETVAL_COMPLETE);
6961 	}
6962 
6963 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6964 
6965 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6966 	ctsio->kern_sg_entries = 0;
6967 	ctsio->kern_rel_offset = 0;
6968 	ctsio->kern_data_len = min(total_len, alloc_len);
6969 	ctsio->kern_total_len = ctsio->kern_data_len;
6970 
6971 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6972 	header->page = page_index->page_code;
6973 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6974 		header->page |= SL_DS;
6975 	if (page_index->subpage) {
6976 		header->page |= SL_SPF;
6977 		header->subpage = page_index->subpage;
6978 	}
6979 	scsi_ulto2b(page_index->page_len, header->datalen);
6980 
6981 	/*
6982 	 * Call the handler, if it exists, to update the
6983 	 * page to the latest values.
6984 	 */
6985 	if (page_index->sense_handler != NULL)
6986 		page_index->sense_handler(ctsio, page_index, pc);
6987 
6988 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6989 
6990 	ctl_set_success(ctsio);
6991 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6992 	ctsio->be_move_done = ctl_config_move_done;
6993 	ctl_datamove((union ctl_io *)ctsio);
6994 	return (CTL_RETVAL_COMPLETE);
6995 }
6996 
6997 int
6998 ctl_read_capacity(struct ctl_scsiio *ctsio)
6999 {
7000 	struct ctl_lun *lun = CTL_LUN(ctsio);
7001 	struct scsi_read_capacity *cdb;
7002 	struct scsi_read_capacity_data *data;
7003 	uint32_t lba;
7004 
7005 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7006 
7007 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7008 
7009 	lba = scsi_4btoul(cdb->addr);
7010 	if (((cdb->pmi & SRC_PMI) == 0)
7011 	 && (lba != 0)) {
7012 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7013 				      /*sks_valid*/ 1,
7014 				      /*command*/ 1,
7015 				      /*field*/ 2,
7016 				      /*bit_valid*/ 0,
7017 				      /*bit*/ 0);
7018 		ctl_done((union ctl_io *)ctsio);
7019 		return (CTL_RETVAL_COMPLETE);
7020 	}
7021 
7022 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7023 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7024 	ctsio->kern_data_len = sizeof(*data);
7025 	ctsio->kern_total_len = sizeof(*data);
7026 	ctsio->kern_rel_offset = 0;
7027 	ctsio->kern_sg_entries = 0;
7028 
7029 	/*
7030 	 * If the maximum LBA is greater than 0xfffffffe, the user must
7031 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7032 	 * serivce action set.
7033 	 */
7034 	if (lun->be_lun->maxlba > 0xfffffffe)
7035 		scsi_ulto4b(0xffffffff, data->addr);
7036 	else
7037 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7038 
7039 	/*
7040 	 * XXX KDM this may not be 512 bytes...
7041 	 */
7042 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7043 
7044 	ctl_set_success(ctsio);
7045 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7046 	ctsio->be_move_done = ctl_config_move_done;
7047 	ctl_datamove((union ctl_io *)ctsio);
7048 	return (CTL_RETVAL_COMPLETE);
7049 }
7050 
7051 int
7052 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7053 {
7054 	struct ctl_lun *lun = CTL_LUN(ctsio);
7055 	struct scsi_read_capacity_16 *cdb;
7056 	struct scsi_read_capacity_data_long *data;
7057 	uint64_t lba;
7058 	uint32_t alloc_len;
7059 
7060 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7061 
7062 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7063 
7064 	alloc_len = scsi_4btoul(cdb->alloc_len);
7065 	lba = scsi_8btou64(cdb->addr);
7066 
7067 	if ((cdb->reladr & SRC16_PMI)
7068 	 && (lba != 0)) {
7069 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7070 				      /*sks_valid*/ 1,
7071 				      /*command*/ 1,
7072 				      /*field*/ 2,
7073 				      /*bit_valid*/ 0,
7074 				      /*bit*/ 0);
7075 		ctl_done((union ctl_io *)ctsio);
7076 		return (CTL_RETVAL_COMPLETE);
7077 	}
7078 
7079 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7080 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7081 	ctsio->kern_rel_offset = 0;
7082 	ctsio->kern_sg_entries = 0;
7083 	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
7084 	ctsio->kern_total_len = ctsio->kern_data_len;
7085 
7086 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7087 	/* XXX KDM this may not be 512 bytes... */
7088 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7089 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7090 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7091 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7092 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7093 
7094 	ctl_set_success(ctsio);
7095 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7096 	ctsio->be_move_done = ctl_config_move_done;
7097 	ctl_datamove((union ctl_io *)ctsio);
7098 	return (CTL_RETVAL_COMPLETE);
7099 }
7100 
7101 int
7102 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7103 {
7104 	struct ctl_lun *lun = CTL_LUN(ctsio);
7105 	struct scsi_get_lba_status *cdb;
7106 	struct scsi_get_lba_status_data *data;
7107 	struct ctl_lba_len_flags *lbalen;
7108 	uint64_t lba;
7109 	uint32_t alloc_len, total_len;
7110 	int retval;
7111 
7112 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7113 
7114 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7115 	lba = scsi_8btou64(cdb->addr);
7116 	alloc_len = scsi_4btoul(cdb->alloc_len);
7117 
7118 	if (lba > lun->be_lun->maxlba) {
7119 		ctl_set_lba_out_of_range(ctsio, lba);
7120 		ctl_done((union ctl_io *)ctsio);
7121 		return (CTL_RETVAL_COMPLETE);
7122 	}
7123 
7124 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7125 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7126 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7127 	ctsio->kern_rel_offset = 0;
7128 	ctsio->kern_sg_entries = 0;
7129 	ctsio->kern_data_len = min(total_len, alloc_len);
7130 	ctsio->kern_total_len = ctsio->kern_data_len;
7131 
7132 	/* Fill dummy data in case backend can't tell anything. */
7133 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7134 	scsi_u64to8b(lba, data->descr[0].addr);
7135 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7136 	    data->descr[0].length);
7137 	data->descr[0].status = 0; /* Mapped or unknown. */
7138 
7139 	ctl_set_success(ctsio);
7140 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7141 	ctsio->be_move_done = ctl_config_move_done;
7142 
7143 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7144 	lbalen->lba = lba;
7145 	lbalen->len = total_len;
7146 	lbalen->flags = 0;
7147 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7148 	return (retval);
7149 }
7150 
7151 int
7152 ctl_read_defect(struct ctl_scsiio *ctsio)
7153 {
7154 	struct scsi_read_defect_data_10 *ccb10;
7155 	struct scsi_read_defect_data_12 *ccb12;
7156 	struct scsi_read_defect_data_hdr_10 *data10;
7157 	struct scsi_read_defect_data_hdr_12 *data12;
7158 	uint32_t alloc_len, data_len;
7159 	uint8_t format;
7160 
7161 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7162 
7163 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7164 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7165 		format = ccb10->format;
7166 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7167 		data_len = sizeof(*data10);
7168 	} else {
7169 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7170 		format = ccb12->format;
7171 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7172 		data_len = sizeof(*data12);
7173 	}
7174 	if (alloc_len == 0) {
7175 		ctl_set_success(ctsio);
7176 		ctl_done((union ctl_io *)ctsio);
7177 		return (CTL_RETVAL_COMPLETE);
7178 	}
7179 
7180 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7181 	ctsio->kern_rel_offset = 0;
7182 	ctsio->kern_sg_entries = 0;
7183 	ctsio->kern_data_len = min(data_len, alloc_len);
7184 	ctsio->kern_total_len = ctsio->kern_data_len;
7185 
7186 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7187 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7188 		    ctsio->kern_data_ptr;
7189 		data10->format = format;
7190 		scsi_ulto2b(0, data10->length);
7191 	} else {
7192 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7193 		    ctsio->kern_data_ptr;
7194 		data12->format = format;
7195 		scsi_ulto2b(0, data12->generation);
7196 		scsi_ulto4b(0, data12->length);
7197 	}
7198 
7199 	ctl_set_success(ctsio);
7200 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7201 	ctsio->be_move_done = ctl_config_move_done;
7202 	ctl_datamove((union ctl_io *)ctsio);
7203 	return (CTL_RETVAL_COMPLETE);
7204 }
7205 
7206 int
7207 ctl_report_ident_info(struct ctl_scsiio *ctsio)
7208 {
7209 	struct ctl_lun *lun = CTL_LUN(ctsio);
7210 	struct scsi_report_ident_info *cdb;
7211 	struct scsi_report_ident_info_data *rii_ptr;
7212 	struct scsi_report_ident_info_descr *riid_ptr;
7213 	const char *oii, *otii;
7214 	int retval, alloc_len, total_len = 0, len = 0;
7215 
7216 	CTL_DEBUG_PRINT(("ctl_report_ident_info\n"));
7217 
7218 	cdb = (struct scsi_report_ident_info *)ctsio->cdb;
7219 	retval = CTL_RETVAL_COMPLETE;
7220 
7221 	total_len = sizeof(struct scsi_report_ident_info_data);
7222 	switch (cdb->type) {
7223 	case RII_LUII:
7224 		oii = dnvlist_get_string(lun->be_lun->options,
7225 		    "ident_info", NULL);
7226 		if (oii)
7227 			len = strlen(oii);	/* Approximately */
7228 		break;
7229 	case RII_LUTII:
7230 		otii = dnvlist_get_string(lun->be_lun->options,
7231 		    "text_ident_info", NULL);
7232 		if (otii)
7233 			len = strlen(otii) + 1;	/* NULL-terminated */
7234 		break;
7235 	case RII_IIS:
7236 		len = 2 * sizeof(struct scsi_report_ident_info_descr);
7237 		break;
7238 	default:
7239 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7240 				      /*sks_valid*/ 1,
7241 				      /*command*/ 1,
7242 				      /*field*/ 11,
7243 				      /*bit_valid*/ 1,
7244 				      /*bit*/ 2);
7245 		ctl_done((union ctl_io *)ctsio);
7246 		return(retval);
7247 	}
7248 	total_len += len;
7249 	alloc_len = scsi_4btoul(cdb->length);
7250 
7251 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7252 	ctsio->kern_sg_entries = 0;
7253 	ctsio->kern_rel_offset = 0;
7254 	ctsio->kern_data_len = min(total_len, alloc_len);
7255 	ctsio->kern_total_len = ctsio->kern_data_len;
7256 
7257 	rii_ptr = (struct scsi_report_ident_info_data *)ctsio->kern_data_ptr;
7258 	switch (cdb->type) {
7259 	case RII_LUII:
7260 		if (oii) {
7261 			if (oii[0] == '0' && oii[1] == 'x')
7262 				len = hex2bin(oii, (uint8_t *)(rii_ptr + 1), len);
7263 			else
7264 				strncpy((uint8_t *)(rii_ptr + 1), oii, len);
7265 		}
7266 		break;
7267 	case RII_LUTII:
7268 		if (otii)
7269 			strlcpy((uint8_t *)(rii_ptr + 1), otii, len);
7270 		break;
7271 	case RII_IIS:
7272 		riid_ptr = (struct scsi_report_ident_info_descr *)(rii_ptr + 1);
7273 		riid_ptr->type = RII_LUII;
7274 		scsi_ulto2b(0xffff, riid_ptr->length);
7275 		riid_ptr++;
7276 		riid_ptr->type = RII_LUTII;
7277 		scsi_ulto2b(0xffff, riid_ptr->length);
7278 	}
7279 	scsi_ulto2b(len, rii_ptr->length);
7280 
7281 	ctl_set_success(ctsio);
7282 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7283 	ctsio->be_move_done = ctl_config_move_done;
7284 	ctl_datamove((union ctl_io *)ctsio);
7285 	return(retval);
7286 }
7287 
7288 int
7289 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7290 {
7291 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7292 	struct ctl_lun *lun = CTL_LUN(ctsio);
7293 	struct scsi_maintenance_in *cdb;
7294 	int retval;
7295 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7296 	int num_ha_groups, num_target_ports, shared_group;
7297 	struct ctl_port *port;
7298 	struct scsi_target_group_data *rtg_ptr;
7299 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7300 	struct scsi_target_port_group_descriptor *tpg_desc;
7301 
7302 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7303 
7304 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7305 	retval = CTL_RETVAL_COMPLETE;
7306 
7307 	switch (cdb->byte2 & STG_PDF_MASK) {
7308 	case STG_PDF_LENGTH:
7309 		ext = 0;
7310 		break;
7311 	case STG_PDF_EXTENDED:
7312 		ext = 1;
7313 		break;
7314 	default:
7315 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7316 				      /*sks_valid*/ 1,
7317 				      /*command*/ 1,
7318 				      /*field*/ 2,
7319 				      /*bit_valid*/ 1,
7320 				      /*bit*/ 5);
7321 		ctl_done((union ctl_io *)ctsio);
7322 		return(retval);
7323 	}
7324 
7325 	num_target_ports = 0;
7326 	shared_group = (softc->is_single != 0);
7327 	mtx_lock(&softc->ctl_lock);
7328 	STAILQ_FOREACH(port, &softc->port_list, links) {
7329 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7330 			continue;
7331 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7332 			continue;
7333 		num_target_ports++;
7334 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7335 			shared_group = 1;
7336 	}
7337 	mtx_unlock(&softc->ctl_lock);
7338 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7339 
7340 	if (ext)
7341 		total_len = sizeof(struct scsi_target_group_data_extended);
7342 	else
7343 		total_len = sizeof(struct scsi_target_group_data);
7344 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7345 		(shared_group + num_ha_groups) +
7346 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7347 
7348 	alloc_len = scsi_4btoul(cdb->length);
7349 
7350 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7351 	ctsio->kern_sg_entries = 0;
7352 	ctsio->kern_rel_offset = 0;
7353 	ctsio->kern_data_len = min(total_len, alloc_len);
7354 	ctsio->kern_total_len = ctsio->kern_data_len;
7355 
7356 	if (ext) {
7357 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7358 		    ctsio->kern_data_ptr;
7359 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7360 		rtg_ext_ptr->format_type = 0x10;
7361 		rtg_ext_ptr->implicit_transition_time = 0;
7362 		tpg_desc = &rtg_ext_ptr->groups[0];
7363 	} else {
7364 		rtg_ptr = (struct scsi_target_group_data *)
7365 		    ctsio->kern_data_ptr;
7366 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7367 		tpg_desc = &rtg_ptr->groups[0];
7368 	}
7369 
7370 	mtx_lock(&softc->ctl_lock);
7371 	pg = softc->port_min / softc->port_cnt;
7372 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7373 		/* Some shelf is known to be primary. */
7374 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7375 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7376 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7377 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7378 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7379 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7380 		else
7381 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7382 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7383 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7384 		} else {
7385 			ts = os;
7386 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7387 		}
7388 	} else {
7389 		/* No known primary shelf. */
7390 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7391 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7392 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7393 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7394 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7395 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7396 		} else {
7397 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7398 		}
7399 	}
7400 	if (shared_group) {
7401 		tpg_desc->pref_state = ts;
7402 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7403 		    TPG_U_SUP | TPG_T_SUP;
7404 		scsi_ulto2b(1, tpg_desc->target_port_group);
7405 		tpg_desc->status = TPG_IMPLICIT;
7406 		pc = 0;
7407 		STAILQ_FOREACH(port, &softc->port_list, links) {
7408 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7409 				continue;
7410 			if (!softc->is_single &&
7411 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7412 				continue;
7413 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7414 				continue;
7415 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7416 			    relative_target_port_identifier);
7417 			pc++;
7418 		}
7419 		tpg_desc->target_port_count = pc;
7420 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7421 		    &tpg_desc->descriptors[pc];
7422 	}
7423 	for (g = 0; g < num_ha_groups; g++) {
7424 		tpg_desc->pref_state = (g == pg) ? ts : os;
7425 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7426 		    TPG_U_SUP | TPG_T_SUP;
7427 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7428 		tpg_desc->status = TPG_IMPLICIT;
7429 		pc = 0;
7430 		STAILQ_FOREACH(port, &softc->port_list, links) {
7431 			if (port->targ_port < g * softc->port_cnt ||
7432 			    port->targ_port >= (g + 1) * softc->port_cnt)
7433 				continue;
7434 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7435 				continue;
7436 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7437 				continue;
7438 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7439 				continue;
7440 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7441 			    relative_target_port_identifier);
7442 			pc++;
7443 		}
7444 		tpg_desc->target_port_count = pc;
7445 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7446 		    &tpg_desc->descriptors[pc];
7447 	}
7448 	mtx_unlock(&softc->ctl_lock);
7449 
7450 	ctl_set_success(ctsio);
7451 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7452 	ctsio->be_move_done = ctl_config_move_done;
7453 	ctl_datamove((union ctl_io *)ctsio);
7454 	return(retval);
7455 }
7456 
7457 int
7458 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7459 {
7460 	struct ctl_lun *lun = CTL_LUN(ctsio);
7461 	struct scsi_report_supported_opcodes *cdb;
7462 	const struct ctl_cmd_entry *entry, *sentry;
7463 	struct scsi_report_supported_opcodes_all *all;
7464 	struct scsi_report_supported_opcodes_descr *descr;
7465 	struct scsi_report_supported_opcodes_one *one;
7466 	int retval;
7467 	int alloc_len, total_len;
7468 	int opcode, service_action, i, j, num;
7469 
7470 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7471 
7472 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7473 	retval = CTL_RETVAL_COMPLETE;
7474 
7475 	opcode = cdb->requested_opcode;
7476 	service_action = scsi_2btoul(cdb->requested_service_action);
7477 	switch (cdb->options & RSO_OPTIONS_MASK) {
7478 	case RSO_OPTIONS_ALL:
7479 		num = 0;
7480 		for (i = 0; i < 256; i++) {
7481 			entry = &ctl_cmd_table[i];
7482 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7483 				for (j = 0; j < 32; j++) {
7484 					sentry = &((const struct ctl_cmd_entry *)
7485 					    entry->execute)[j];
7486 					if (ctl_cmd_applicable(
7487 					    lun->be_lun->lun_type, sentry))
7488 						num++;
7489 				}
7490 			} else {
7491 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7492 				    entry))
7493 					num++;
7494 			}
7495 		}
7496 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7497 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7498 		break;
7499 	case RSO_OPTIONS_OC:
7500 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7501 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7502 					      /*sks_valid*/ 1,
7503 					      /*command*/ 1,
7504 					      /*field*/ 2,
7505 					      /*bit_valid*/ 1,
7506 					      /*bit*/ 2);
7507 			ctl_done((union ctl_io *)ctsio);
7508 			return (CTL_RETVAL_COMPLETE);
7509 		}
7510 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7511 		break;
7512 	case RSO_OPTIONS_OC_SA:
7513 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7514 		    service_action >= 32) {
7515 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7516 					      /*sks_valid*/ 1,
7517 					      /*command*/ 1,
7518 					      /*field*/ 2,
7519 					      /*bit_valid*/ 1,
7520 					      /*bit*/ 2);
7521 			ctl_done((union ctl_io *)ctsio);
7522 			return (CTL_RETVAL_COMPLETE);
7523 		}
7524 		/* FALLTHROUGH */
7525 	case RSO_OPTIONS_OC_ASA:
7526 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7527 		break;
7528 	default:
7529 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7530 				      /*sks_valid*/ 1,
7531 				      /*command*/ 1,
7532 				      /*field*/ 2,
7533 				      /*bit_valid*/ 1,
7534 				      /*bit*/ 2);
7535 		ctl_done((union ctl_io *)ctsio);
7536 		return (CTL_RETVAL_COMPLETE);
7537 	}
7538 
7539 	alloc_len = scsi_4btoul(cdb->length);
7540 
7541 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7542 	ctsio->kern_sg_entries = 0;
7543 	ctsio->kern_rel_offset = 0;
7544 	ctsio->kern_data_len = min(total_len, alloc_len);
7545 	ctsio->kern_total_len = ctsio->kern_data_len;
7546 
7547 	switch (cdb->options & RSO_OPTIONS_MASK) {
7548 	case RSO_OPTIONS_ALL:
7549 		all = (struct scsi_report_supported_opcodes_all *)
7550 		    ctsio->kern_data_ptr;
7551 		num = 0;
7552 		for (i = 0; i < 256; i++) {
7553 			entry = &ctl_cmd_table[i];
7554 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7555 				for (j = 0; j < 32; j++) {
7556 					sentry = &((const struct ctl_cmd_entry *)
7557 					    entry->execute)[j];
7558 					if (!ctl_cmd_applicable(
7559 					    lun->be_lun->lun_type, sentry))
7560 						continue;
7561 					descr = &all->descr[num++];
7562 					descr->opcode = i;
7563 					scsi_ulto2b(j, descr->service_action);
7564 					descr->flags = RSO_SERVACTV;
7565 					scsi_ulto2b(sentry->length,
7566 					    descr->cdb_length);
7567 				}
7568 			} else {
7569 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7570 				    entry))
7571 					continue;
7572 				descr = &all->descr[num++];
7573 				descr->opcode = i;
7574 				scsi_ulto2b(0, descr->service_action);
7575 				descr->flags = 0;
7576 				scsi_ulto2b(entry->length, descr->cdb_length);
7577 			}
7578 		}
7579 		scsi_ulto4b(
7580 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7581 		    all->length);
7582 		break;
7583 	case RSO_OPTIONS_OC:
7584 		one = (struct scsi_report_supported_opcodes_one *)
7585 		    ctsio->kern_data_ptr;
7586 		entry = &ctl_cmd_table[opcode];
7587 		goto fill_one;
7588 	case RSO_OPTIONS_OC_SA:
7589 		one = (struct scsi_report_supported_opcodes_one *)
7590 		    ctsio->kern_data_ptr;
7591 		entry = &ctl_cmd_table[opcode];
7592 		entry = &((const struct ctl_cmd_entry *)
7593 		    entry->execute)[service_action];
7594 fill_one:
7595 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7596 			one->support = 3;
7597 			scsi_ulto2b(entry->length, one->cdb_length);
7598 			one->cdb_usage[0] = opcode;
7599 			memcpy(&one->cdb_usage[1], entry->usage,
7600 			    entry->length - 1);
7601 		} else
7602 			one->support = 1;
7603 		break;
7604 	case RSO_OPTIONS_OC_ASA:
7605 		one = (struct scsi_report_supported_opcodes_one *)
7606 		    ctsio->kern_data_ptr;
7607 		entry = &ctl_cmd_table[opcode];
7608 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7609 			entry = &((const struct ctl_cmd_entry *)
7610 			    entry->execute)[service_action];
7611 		} else if (service_action != 0) {
7612 			one->support = 1;
7613 			break;
7614 		}
7615 		goto fill_one;
7616 	}
7617 
7618 	ctl_set_success(ctsio);
7619 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7620 	ctsio->be_move_done = ctl_config_move_done;
7621 	ctl_datamove((union ctl_io *)ctsio);
7622 	return(retval);
7623 }
7624 
7625 int
7626 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7627 {
7628 	struct scsi_report_supported_tmf *cdb;
7629 	struct scsi_report_supported_tmf_ext_data *data;
7630 	int retval;
7631 	int alloc_len, total_len;
7632 
7633 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7634 
7635 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7636 
7637 	retval = CTL_RETVAL_COMPLETE;
7638 
7639 	if (cdb->options & RST_REPD)
7640 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7641 	else
7642 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7643 	alloc_len = scsi_4btoul(cdb->length);
7644 
7645 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7646 	ctsio->kern_sg_entries = 0;
7647 	ctsio->kern_rel_offset = 0;
7648 	ctsio->kern_data_len = min(total_len, alloc_len);
7649 	ctsio->kern_total_len = ctsio->kern_data_len;
7650 
7651 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7652 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7653 	    RST_TRS;
7654 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7655 	data->length = total_len - 4;
7656 
7657 	ctl_set_success(ctsio);
7658 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7659 	ctsio->be_move_done = ctl_config_move_done;
7660 	ctl_datamove((union ctl_io *)ctsio);
7661 	return (retval);
7662 }
7663 
7664 int
7665 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7666 {
7667 	struct scsi_report_timestamp *cdb;
7668 	struct scsi_report_timestamp_data *data;
7669 	struct timeval tv;
7670 	int64_t timestamp;
7671 	int retval;
7672 	int alloc_len, total_len;
7673 
7674 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7675 
7676 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7677 
7678 	retval = CTL_RETVAL_COMPLETE;
7679 
7680 	total_len = sizeof(struct scsi_report_timestamp_data);
7681 	alloc_len = scsi_4btoul(cdb->length);
7682 
7683 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7684 	ctsio->kern_sg_entries = 0;
7685 	ctsio->kern_rel_offset = 0;
7686 	ctsio->kern_data_len = min(total_len, alloc_len);
7687 	ctsio->kern_total_len = ctsio->kern_data_len;
7688 
7689 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7690 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7691 	data->origin = RTS_ORIG_OUTSIDE;
7692 	getmicrotime(&tv);
7693 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7694 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7695 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7696 
7697 	ctl_set_success(ctsio);
7698 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7699 	ctsio->be_move_done = ctl_config_move_done;
7700 	ctl_datamove((union ctl_io *)ctsio);
7701 	return (retval);
7702 }
7703 
7704 int
7705 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7706 {
7707 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7708 	struct ctl_lun *lun = CTL_LUN(ctsio);
7709 	struct scsi_per_res_in *cdb;
7710 	int alloc_len, total_len = 0;
7711 	/* struct scsi_per_res_in_rsrv in_data; */
7712 	uint64_t key;
7713 
7714 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7715 
7716 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7717 
7718 	alloc_len = scsi_2btoul(cdb->length);
7719 
7720 retry:
7721 	mtx_lock(&lun->lun_lock);
7722 	switch (cdb->action) {
7723 	case SPRI_RK: /* read keys */
7724 		total_len = sizeof(struct scsi_per_res_in_keys) +
7725 			lun->pr_key_count *
7726 			sizeof(struct scsi_per_res_key);
7727 		break;
7728 	case SPRI_RR: /* read reservation */
7729 		if (lun->flags & CTL_LUN_PR_RESERVED)
7730 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7731 		else
7732 			total_len = sizeof(struct scsi_per_res_in_header);
7733 		break;
7734 	case SPRI_RC: /* report capabilities */
7735 		total_len = sizeof(struct scsi_per_res_cap);
7736 		break;
7737 	case SPRI_RS: /* read full status */
7738 		total_len = sizeof(struct scsi_per_res_in_header) +
7739 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7740 		    lun->pr_key_count;
7741 		break;
7742 	default:
7743 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7744 	}
7745 	mtx_unlock(&lun->lun_lock);
7746 
7747 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7748 	ctsio->kern_rel_offset = 0;
7749 	ctsio->kern_sg_entries = 0;
7750 	ctsio->kern_data_len = min(total_len, alloc_len);
7751 	ctsio->kern_total_len = ctsio->kern_data_len;
7752 
7753 	mtx_lock(&lun->lun_lock);
7754 	switch (cdb->action) {
7755 	case SPRI_RK: { // read keys
7756         struct scsi_per_res_in_keys *res_keys;
7757 		int i, key_count;
7758 
7759 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7760 
7761 		/*
7762 		 * We had to drop the lock to allocate our buffer, which
7763 		 * leaves time for someone to come in with another
7764 		 * persistent reservation.  (That is unlikely, though,
7765 		 * since this should be the only persistent reservation
7766 		 * command active right now.)
7767 		 */
7768 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7769 		    (lun->pr_key_count *
7770 		     sizeof(struct scsi_per_res_key)))){
7771 			mtx_unlock(&lun->lun_lock);
7772 			free(ctsio->kern_data_ptr, M_CTL);
7773 			printf("%s: reservation length changed, retrying\n",
7774 			       __func__);
7775 			goto retry;
7776 		}
7777 
7778 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7779 
7780 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7781 			     lun->pr_key_count, res_keys->header.length);
7782 
7783 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7784 			if ((key = ctl_get_prkey(lun, i)) == 0)
7785 				continue;
7786 
7787 			/*
7788 			 * We used lun->pr_key_count to calculate the
7789 			 * size to allocate.  If it turns out the number of
7790 			 * initiators with the registered flag set is
7791 			 * larger than that (i.e. they haven't been kept in
7792 			 * sync), we've got a problem.
7793 			 */
7794 			if (key_count >= lun->pr_key_count) {
7795 				key_count++;
7796 				continue;
7797 			}
7798 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7799 			key_count++;
7800 		}
7801 		break;
7802 	}
7803 	case SPRI_RR: { // read reservation
7804 		struct scsi_per_res_in_rsrv *res;
7805 		int tmp_len, header_only;
7806 
7807 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7808 
7809 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7810 
7811 		if (lun->flags & CTL_LUN_PR_RESERVED)
7812 		{
7813 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7814 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7815 				    res->header.length);
7816 			header_only = 0;
7817 		} else {
7818 			tmp_len = sizeof(struct scsi_per_res_in_header);
7819 			scsi_ulto4b(0, res->header.length);
7820 			header_only = 1;
7821 		}
7822 
7823 		/*
7824 		 * We had to drop the lock to allocate our buffer, which
7825 		 * leaves time for someone to come in with another
7826 		 * persistent reservation.  (That is unlikely, though,
7827 		 * since this should be the only persistent reservation
7828 		 * command active right now.)
7829 		 */
7830 		if (tmp_len != total_len) {
7831 			mtx_unlock(&lun->lun_lock);
7832 			free(ctsio->kern_data_ptr, M_CTL);
7833 			printf("%s: reservation status changed, retrying\n",
7834 			       __func__);
7835 			goto retry;
7836 		}
7837 
7838 		/*
7839 		 * No reservation held, so we're done.
7840 		 */
7841 		if (header_only != 0)
7842 			break;
7843 
7844 		/*
7845 		 * If the registration is an All Registrants type, the key
7846 		 * is 0, since it doesn't really matter.
7847 		 */
7848 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7849 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7850 			    res->data.reservation);
7851 		}
7852 		res->data.scopetype = lun->pr_res_type;
7853 		break;
7854 	}
7855 	case SPRI_RC:     //report capabilities
7856 	{
7857 		struct scsi_per_res_cap *res_cap;
7858 		uint16_t type_mask;
7859 
7860 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7861 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7862 		res_cap->flags1 = SPRI_CRH;
7863 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7864 		type_mask = SPRI_TM_WR_EX_AR |
7865 			    SPRI_TM_EX_AC_RO |
7866 			    SPRI_TM_WR_EX_RO |
7867 			    SPRI_TM_EX_AC |
7868 			    SPRI_TM_WR_EX |
7869 			    SPRI_TM_EX_AC_AR;
7870 		scsi_ulto2b(type_mask, res_cap->type_mask);
7871 		break;
7872 	}
7873 	case SPRI_RS: { // read full status
7874 		struct scsi_per_res_in_full *res_status;
7875 		struct scsi_per_res_in_full_desc *res_desc;
7876 		struct ctl_port *port;
7877 		int i, len;
7878 
7879 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7880 
7881 		/*
7882 		 * We had to drop the lock to allocate our buffer, which
7883 		 * leaves time for someone to come in with another
7884 		 * persistent reservation.  (That is unlikely, though,
7885 		 * since this should be the only persistent reservation
7886 		 * command active right now.)
7887 		 */
7888 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7889 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7890 		     lun->pr_key_count)){
7891 			mtx_unlock(&lun->lun_lock);
7892 			free(ctsio->kern_data_ptr, M_CTL);
7893 			printf("%s: reservation length changed, retrying\n",
7894 			       __func__);
7895 			goto retry;
7896 		}
7897 
7898 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7899 
7900 		res_desc = &res_status->desc[0];
7901 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7902 			if ((key = ctl_get_prkey(lun, i)) == 0)
7903 				continue;
7904 
7905 			scsi_u64to8b(key, res_desc->res_key.key);
7906 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7907 			    (lun->pr_res_idx == i ||
7908 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7909 				res_desc->flags = SPRI_FULL_R_HOLDER;
7910 				res_desc->scopetype = lun->pr_res_type;
7911 			}
7912 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7913 			    res_desc->rel_trgt_port_id);
7914 			len = 0;
7915 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7916 			if (port != NULL)
7917 				len = ctl_create_iid(port,
7918 				    i % CTL_MAX_INIT_PER_PORT,
7919 				    res_desc->transport_id);
7920 			scsi_ulto4b(len, res_desc->additional_length);
7921 			res_desc = (struct scsi_per_res_in_full_desc *)
7922 			    &res_desc->transport_id[len];
7923 		}
7924 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7925 		    res_status->header.length);
7926 		break;
7927 	}
7928 	default:
7929 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7930 	}
7931 	mtx_unlock(&lun->lun_lock);
7932 
7933 	ctl_set_success(ctsio);
7934 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7935 	ctsio->be_move_done = ctl_config_move_done;
7936 	ctl_datamove((union ctl_io *)ctsio);
7937 	return (CTL_RETVAL_COMPLETE);
7938 }
7939 
7940 /*
7941  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7942  * it should return.
7943  */
7944 static int
7945 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7946 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7947 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7948 		struct scsi_per_res_out_parms* param)
7949 {
7950 	union ctl_ha_msg persis_io;
7951 	int i;
7952 
7953 	mtx_lock(&lun->lun_lock);
7954 	if (sa_res_key == 0) {
7955 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7956 			/* validate scope and type */
7957 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7958 			     SPR_LU_SCOPE) {
7959 				mtx_unlock(&lun->lun_lock);
7960 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7961 						      /*sks_valid*/ 1,
7962 						      /*command*/ 1,
7963 						      /*field*/ 2,
7964 						      /*bit_valid*/ 1,
7965 						      /*bit*/ 4);
7966 				ctl_done((union ctl_io *)ctsio);
7967 				return (1);
7968 			}
7969 
7970 		        if (type>8 || type==2 || type==4 || type==0) {
7971 				mtx_unlock(&lun->lun_lock);
7972 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7973        	           				      /*sks_valid*/ 1,
7974 						      /*command*/ 1,
7975 						      /*field*/ 2,
7976 						      /*bit_valid*/ 1,
7977 						      /*bit*/ 0);
7978 				ctl_done((union ctl_io *)ctsio);
7979 				return (1);
7980 		        }
7981 
7982 			/*
7983 			 * Unregister everybody else and build UA for
7984 			 * them
7985 			 */
7986 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7987 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7988 					continue;
7989 
7990 				ctl_clr_prkey(lun, i);
7991 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7992 			}
7993 			lun->pr_key_count = 1;
7994 			lun->pr_res_type = type;
7995 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7996 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7997 				lun->pr_res_idx = residx;
7998 			lun->pr_generation++;
7999 			mtx_unlock(&lun->lun_lock);
8000 
8001 			/* send msg to other side */
8002 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8003 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8004 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8005 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8006 			persis_io.pr.pr_info.res_type = type;
8007 			memcpy(persis_io.pr.pr_info.sa_res_key,
8008 			       param->serv_act_res_key,
8009 			       sizeof(param->serv_act_res_key));
8010 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8011 			    sizeof(persis_io.pr), M_WAITOK);
8012 		} else {
8013 			/* not all registrants */
8014 			mtx_unlock(&lun->lun_lock);
8015 			free(ctsio->kern_data_ptr, M_CTL);
8016 			ctl_set_invalid_field(ctsio,
8017 					      /*sks_valid*/ 1,
8018 					      /*command*/ 0,
8019 					      /*field*/ 8,
8020 					      /*bit_valid*/ 0,
8021 					      /*bit*/ 0);
8022 			ctl_done((union ctl_io *)ctsio);
8023 			return (1);
8024 		}
8025 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8026 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8027 		int found = 0;
8028 
8029 		if (res_key == sa_res_key) {
8030 			/* special case */
8031 			/*
8032 			 * The spec implies this is not good but doesn't
8033 			 * say what to do. There are two choices either
8034 			 * generate a res conflict or check condition
8035 			 * with illegal field in parameter data. Since
8036 			 * that is what is done when the sa_res_key is
8037 			 * zero I'll take that approach since this has
8038 			 * to do with the sa_res_key.
8039 			 */
8040 			mtx_unlock(&lun->lun_lock);
8041 			free(ctsio->kern_data_ptr, M_CTL);
8042 			ctl_set_invalid_field(ctsio,
8043 					      /*sks_valid*/ 1,
8044 					      /*command*/ 0,
8045 					      /*field*/ 8,
8046 					      /*bit_valid*/ 0,
8047 					      /*bit*/ 0);
8048 			ctl_done((union ctl_io *)ctsio);
8049 			return (1);
8050 		}
8051 
8052 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8053 			if (ctl_get_prkey(lun, i) != sa_res_key)
8054 				continue;
8055 
8056 			found = 1;
8057 			ctl_clr_prkey(lun, i);
8058 			lun->pr_key_count--;
8059 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8060 		}
8061 		if (!found) {
8062 			mtx_unlock(&lun->lun_lock);
8063 			free(ctsio->kern_data_ptr, M_CTL);
8064 			ctl_set_reservation_conflict(ctsio);
8065 			ctl_done((union ctl_io *)ctsio);
8066 			return (CTL_RETVAL_COMPLETE);
8067 		}
8068 		lun->pr_generation++;
8069 		mtx_unlock(&lun->lun_lock);
8070 
8071 		/* send msg to other side */
8072 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8073 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8074 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8075 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8076 		persis_io.pr.pr_info.res_type = type;
8077 		memcpy(persis_io.pr.pr_info.sa_res_key,
8078 		       param->serv_act_res_key,
8079 		       sizeof(param->serv_act_res_key));
8080 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8081 		    sizeof(persis_io.pr), M_WAITOK);
8082 	} else {
8083 		/* Reserved but not all registrants */
8084 		/* sa_res_key is res holder */
8085 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8086 			/* validate scope and type */
8087 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8088 			     SPR_LU_SCOPE) {
8089 				mtx_unlock(&lun->lun_lock);
8090 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8091 						      /*sks_valid*/ 1,
8092 						      /*command*/ 1,
8093 						      /*field*/ 2,
8094 						      /*bit_valid*/ 1,
8095 						      /*bit*/ 4);
8096 				ctl_done((union ctl_io *)ctsio);
8097 				return (1);
8098 			}
8099 
8100 			if (type>8 || type==2 || type==4 || type==0) {
8101 				mtx_unlock(&lun->lun_lock);
8102 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8103 						      /*sks_valid*/ 1,
8104 						      /*command*/ 1,
8105 						      /*field*/ 2,
8106 						      /*bit_valid*/ 1,
8107 						      /*bit*/ 0);
8108 				ctl_done((union ctl_io *)ctsio);
8109 				return (1);
8110 			}
8111 
8112 			/*
8113 			 * Do the following:
8114 			 * if sa_res_key != res_key remove all
8115 			 * registrants w/sa_res_key and generate UA
8116 			 * for these registrants(Registrations
8117 			 * Preempted) if it wasn't an exclusive
8118 			 * reservation generate UA(Reservations
8119 			 * Preempted) for all other registered nexuses
8120 			 * if the type has changed. Establish the new
8121 			 * reservation and holder. If res_key and
8122 			 * sa_res_key are the same do the above
8123 			 * except don't unregister the res holder.
8124 			 */
8125 
8126 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8127 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8128 					continue;
8129 
8130 				if (sa_res_key == ctl_get_prkey(lun, i)) {
8131 					ctl_clr_prkey(lun, i);
8132 					lun->pr_key_count--;
8133 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8134 				} else if (type != lun->pr_res_type &&
8135 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8136 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8137 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8138 				}
8139 			}
8140 			lun->pr_res_type = type;
8141 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8142 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8143 				lun->pr_res_idx = residx;
8144 			else
8145 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8146 			lun->pr_generation++;
8147 			mtx_unlock(&lun->lun_lock);
8148 
8149 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8150 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8151 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8152 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8153 			persis_io.pr.pr_info.res_type = type;
8154 			memcpy(persis_io.pr.pr_info.sa_res_key,
8155 			       param->serv_act_res_key,
8156 			       sizeof(param->serv_act_res_key));
8157 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8158 			    sizeof(persis_io.pr), M_WAITOK);
8159 		} else {
8160 			/*
8161 			 * sa_res_key is not the res holder just
8162 			 * remove registrants
8163 			 */
8164 			int found=0;
8165 
8166 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8167 				if (sa_res_key != ctl_get_prkey(lun, i))
8168 					continue;
8169 
8170 				found = 1;
8171 				ctl_clr_prkey(lun, i);
8172 				lun->pr_key_count--;
8173 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8174 			}
8175 
8176 			if (!found) {
8177 				mtx_unlock(&lun->lun_lock);
8178 				free(ctsio->kern_data_ptr, M_CTL);
8179 				ctl_set_reservation_conflict(ctsio);
8180 				ctl_done((union ctl_io *)ctsio);
8181 		        	return (1);
8182 			}
8183 			lun->pr_generation++;
8184 			mtx_unlock(&lun->lun_lock);
8185 
8186 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8187 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8188 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8189 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8190 			persis_io.pr.pr_info.res_type = type;
8191 			memcpy(persis_io.pr.pr_info.sa_res_key,
8192 			       param->serv_act_res_key,
8193 			       sizeof(param->serv_act_res_key));
8194 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8195 			    sizeof(persis_io.pr), M_WAITOK);
8196 		}
8197 	}
8198 	return (0);
8199 }
8200 
8201 static void
8202 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8203 {
8204 	uint64_t sa_res_key;
8205 	int i;
8206 
8207 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8208 
8209 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8210 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8211 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8212 		if (sa_res_key == 0) {
8213 			/*
8214 			 * Unregister everybody else and build UA for
8215 			 * them
8216 			 */
8217 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8218 				if (i == msg->pr.pr_info.residx ||
8219 				    ctl_get_prkey(lun, i) == 0)
8220 					continue;
8221 
8222 				ctl_clr_prkey(lun, i);
8223 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8224 			}
8225 
8226 			lun->pr_key_count = 1;
8227 			lun->pr_res_type = msg->pr.pr_info.res_type;
8228 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8229 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8230 				lun->pr_res_idx = msg->pr.pr_info.residx;
8231 		} else {
8232 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8233 				if (sa_res_key == ctl_get_prkey(lun, i))
8234 					continue;
8235 
8236 				ctl_clr_prkey(lun, i);
8237 				lun->pr_key_count--;
8238 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8239 			}
8240 		}
8241 	} else {
8242 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8243 			if (i == msg->pr.pr_info.residx ||
8244 			    ctl_get_prkey(lun, i) == 0)
8245 				continue;
8246 
8247 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8248 				ctl_clr_prkey(lun, i);
8249 				lun->pr_key_count--;
8250 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8251 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8252 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8253 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8254 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8255 			}
8256 		}
8257 		lun->pr_res_type = msg->pr.pr_info.res_type;
8258 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8259 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8260 			lun->pr_res_idx = msg->pr.pr_info.residx;
8261 		else
8262 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8263 	}
8264 	lun->pr_generation++;
8265 
8266 }
8267 
8268 int
8269 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8270 {
8271 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8272 	struct ctl_lun *lun = CTL_LUN(ctsio);
8273 	int retval;
8274 	u_int32_t param_len;
8275 	struct scsi_per_res_out *cdb;
8276 	struct scsi_per_res_out_parms* param;
8277 	uint32_t residx;
8278 	uint64_t res_key, sa_res_key, key;
8279 	uint8_t type;
8280 	union ctl_ha_msg persis_io;
8281 	int    i;
8282 
8283 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8284 
8285 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8286 	retval = CTL_RETVAL_COMPLETE;
8287 
8288 	/*
8289 	 * We only support whole-LUN scope.  The scope & type are ignored for
8290 	 * register, register and ignore existing key and clear.
8291 	 * We sometimes ignore scope and type on preempts too!!
8292 	 * Verify reservation type here as well.
8293 	 */
8294 	type = cdb->scope_type & SPR_TYPE_MASK;
8295 	if ((cdb->action == SPRO_RESERVE)
8296 	 || (cdb->action == SPRO_RELEASE)) {
8297 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8298 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8299 					      /*sks_valid*/ 1,
8300 					      /*command*/ 1,
8301 					      /*field*/ 2,
8302 					      /*bit_valid*/ 1,
8303 					      /*bit*/ 4);
8304 			ctl_done((union ctl_io *)ctsio);
8305 			return (CTL_RETVAL_COMPLETE);
8306 		}
8307 
8308 		if (type>8 || type==2 || type==4 || type==0) {
8309 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8310 					      /*sks_valid*/ 1,
8311 					      /*command*/ 1,
8312 					      /*field*/ 2,
8313 					      /*bit_valid*/ 1,
8314 					      /*bit*/ 0);
8315 			ctl_done((union ctl_io *)ctsio);
8316 			return (CTL_RETVAL_COMPLETE);
8317 		}
8318 	}
8319 
8320 	param_len = scsi_4btoul(cdb->length);
8321 
8322 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8323 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8324 		ctsio->kern_data_len = param_len;
8325 		ctsio->kern_total_len = param_len;
8326 		ctsio->kern_rel_offset = 0;
8327 		ctsio->kern_sg_entries = 0;
8328 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8329 		ctsio->be_move_done = ctl_config_move_done;
8330 		ctl_datamove((union ctl_io *)ctsio);
8331 
8332 		return (CTL_RETVAL_COMPLETE);
8333 	}
8334 
8335 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8336 
8337 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8338 	res_key = scsi_8btou64(param->res_key.key);
8339 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8340 
8341 	/*
8342 	 * Validate the reservation key here except for SPRO_REG_IGNO
8343 	 * This must be done for all other service actions
8344 	 */
8345 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8346 		mtx_lock(&lun->lun_lock);
8347 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8348 			if (res_key != key) {
8349 				/*
8350 				 * The current key passed in doesn't match
8351 				 * the one the initiator previously
8352 				 * registered.
8353 				 */
8354 				mtx_unlock(&lun->lun_lock);
8355 				free(ctsio->kern_data_ptr, M_CTL);
8356 				ctl_set_reservation_conflict(ctsio);
8357 				ctl_done((union ctl_io *)ctsio);
8358 				return (CTL_RETVAL_COMPLETE);
8359 			}
8360 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8361 			/*
8362 			 * We are not registered
8363 			 */
8364 			mtx_unlock(&lun->lun_lock);
8365 			free(ctsio->kern_data_ptr, M_CTL);
8366 			ctl_set_reservation_conflict(ctsio);
8367 			ctl_done((union ctl_io *)ctsio);
8368 			return (CTL_RETVAL_COMPLETE);
8369 		} else if (res_key != 0) {
8370 			/*
8371 			 * We are not registered and trying to register but
8372 			 * the register key isn't zero.
8373 			 */
8374 			mtx_unlock(&lun->lun_lock);
8375 			free(ctsio->kern_data_ptr, M_CTL);
8376 			ctl_set_reservation_conflict(ctsio);
8377 			ctl_done((union ctl_io *)ctsio);
8378 			return (CTL_RETVAL_COMPLETE);
8379 		}
8380 		mtx_unlock(&lun->lun_lock);
8381 	}
8382 
8383 	switch (cdb->action & SPRO_ACTION_MASK) {
8384 	case SPRO_REGISTER:
8385 	case SPRO_REG_IGNO: {
8386 		/*
8387 		 * We don't support any of these options, as we report in
8388 		 * the read capabilities request (see
8389 		 * ctl_persistent_reserve_in(), above).
8390 		 */
8391 		if ((param->flags & SPR_SPEC_I_PT)
8392 		 || (param->flags & SPR_ALL_TG_PT)
8393 		 || (param->flags & SPR_APTPL)) {
8394 			int bit_ptr;
8395 
8396 			if (param->flags & SPR_APTPL)
8397 				bit_ptr = 0;
8398 			else if (param->flags & SPR_ALL_TG_PT)
8399 				bit_ptr = 2;
8400 			else /* SPR_SPEC_I_PT */
8401 				bit_ptr = 3;
8402 
8403 			free(ctsio->kern_data_ptr, M_CTL);
8404 			ctl_set_invalid_field(ctsio,
8405 					      /*sks_valid*/ 1,
8406 					      /*command*/ 0,
8407 					      /*field*/ 20,
8408 					      /*bit_valid*/ 1,
8409 					      /*bit*/ bit_ptr);
8410 			ctl_done((union ctl_io *)ctsio);
8411 			return (CTL_RETVAL_COMPLETE);
8412 		}
8413 
8414 		mtx_lock(&lun->lun_lock);
8415 
8416 		/*
8417 		 * The initiator wants to clear the
8418 		 * key/unregister.
8419 		 */
8420 		if (sa_res_key == 0) {
8421 			if ((res_key == 0
8422 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8423 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8424 			  && ctl_get_prkey(lun, residx) == 0)) {
8425 				mtx_unlock(&lun->lun_lock);
8426 				goto done;
8427 			}
8428 
8429 			ctl_clr_prkey(lun, residx);
8430 			lun->pr_key_count--;
8431 
8432 			if (residx == lun->pr_res_idx) {
8433 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8434 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8435 
8436 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8437 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8438 				    lun->pr_key_count) {
8439 					/*
8440 					 * If the reservation is a registrants
8441 					 * only type we need to generate a UA
8442 					 * for other registered inits.  The
8443 					 * sense code should be RESERVATIONS
8444 					 * RELEASED
8445 					 */
8446 
8447 					for (i = softc->init_min; i < softc->init_max; i++){
8448 						if (ctl_get_prkey(lun, i) == 0)
8449 							continue;
8450 						ctl_est_ua(lun, i,
8451 						    CTL_UA_RES_RELEASE);
8452 					}
8453 				}
8454 				lun->pr_res_type = 0;
8455 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8456 				if (lun->pr_key_count==0) {
8457 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8458 					lun->pr_res_type = 0;
8459 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8460 				}
8461 			}
8462 			lun->pr_generation++;
8463 			mtx_unlock(&lun->lun_lock);
8464 
8465 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8466 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8467 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8468 			persis_io.pr.pr_info.residx = residx;
8469 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8470 			    sizeof(persis_io.pr), M_WAITOK);
8471 		} else /* sa_res_key != 0 */ {
8472 			/*
8473 			 * If we aren't registered currently then increment
8474 			 * the key count and set the registered flag.
8475 			 */
8476 			ctl_alloc_prkey(lun, residx);
8477 			if (ctl_get_prkey(lun, residx) == 0)
8478 				lun->pr_key_count++;
8479 			ctl_set_prkey(lun, residx, sa_res_key);
8480 			lun->pr_generation++;
8481 			mtx_unlock(&lun->lun_lock);
8482 
8483 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8484 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8485 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8486 			persis_io.pr.pr_info.residx = residx;
8487 			memcpy(persis_io.pr.pr_info.sa_res_key,
8488 			       param->serv_act_res_key,
8489 			       sizeof(param->serv_act_res_key));
8490 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8491 			    sizeof(persis_io.pr), M_WAITOK);
8492 		}
8493 
8494 		break;
8495 	}
8496 	case SPRO_RESERVE:
8497 		mtx_lock(&lun->lun_lock);
8498 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8499 			/*
8500 			 * if this isn't the reservation holder and it's
8501 			 * not a "all registrants" type or if the type is
8502 			 * different then we have a conflict
8503 			 */
8504 			if ((lun->pr_res_idx != residx
8505 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8506 			 || lun->pr_res_type != type) {
8507 				mtx_unlock(&lun->lun_lock);
8508 				free(ctsio->kern_data_ptr, M_CTL);
8509 				ctl_set_reservation_conflict(ctsio);
8510 				ctl_done((union ctl_io *)ctsio);
8511 				return (CTL_RETVAL_COMPLETE);
8512 			}
8513 			mtx_unlock(&lun->lun_lock);
8514 		} else /* create a reservation */ {
8515 			/*
8516 			 * If it's not an "all registrants" type record
8517 			 * reservation holder
8518 			 */
8519 			if (type != SPR_TYPE_WR_EX_AR
8520 			 && type != SPR_TYPE_EX_AC_AR)
8521 				lun->pr_res_idx = residx; /* Res holder */
8522 			else
8523 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8524 
8525 			lun->flags |= CTL_LUN_PR_RESERVED;
8526 			lun->pr_res_type = type;
8527 
8528 			mtx_unlock(&lun->lun_lock);
8529 
8530 			/* send msg to other side */
8531 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8532 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8533 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8534 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8535 			persis_io.pr.pr_info.res_type = type;
8536 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8537 			    sizeof(persis_io.pr), M_WAITOK);
8538 		}
8539 		break;
8540 
8541 	case SPRO_RELEASE:
8542 		mtx_lock(&lun->lun_lock);
8543 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8544 			/* No reservation exists return good status */
8545 			mtx_unlock(&lun->lun_lock);
8546 			goto done;
8547 		}
8548 		/*
8549 		 * Is this nexus a reservation holder?
8550 		 */
8551 		if (lun->pr_res_idx != residx
8552 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8553 			/*
8554 			 * not a res holder return good status but
8555 			 * do nothing
8556 			 */
8557 			mtx_unlock(&lun->lun_lock);
8558 			goto done;
8559 		}
8560 
8561 		if (lun->pr_res_type != type) {
8562 			mtx_unlock(&lun->lun_lock);
8563 			free(ctsio->kern_data_ptr, M_CTL);
8564 			ctl_set_illegal_pr_release(ctsio);
8565 			ctl_done((union ctl_io *)ctsio);
8566 			return (CTL_RETVAL_COMPLETE);
8567 		}
8568 
8569 		/* okay to release */
8570 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8571 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8572 		lun->pr_res_type = 0;
8573 
8574 		/*
8575 		 * If this isn't an exclusive access reservation and NUAR
8576 		 * is not set, generate UA for all other registrants.
8577 		 */
8578 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8579 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8580 			for (i = softc->init_min; i < softc->init_max; i++) {
8581 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8582 					continue;
8583 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8584 			}
8585 		}
8586 		mtx_unlock(&lun->lun_lock);
8587 
8588 		/* Send msg to other side */
8589 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8590 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8591 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8592 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8593 		     sizeof(persis_io.pr), M_WAITOK);
8594 		break;
8595 
8596 	case SPRO_CLEAR:
8597 		/* send msg to other side */
8598 
8599 		mtx_lock(&lun->lun_lock);
8600 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8601 		lun->pr_res_type = 0;
8602 		lun->pr_key_count = 0;
8603 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8604 
8605 		ctl_clr_prkey(lun, residx);
8606 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8607 			if (ctl_get_prkey(lun, i) != 0) {
8608 				ctl_clr_prkey(lun, i);
8609 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8610 			}
8611 		lun->pr_generation++;
8612 		mtx_unlock(&lun->lun_lock);
8613 
8614 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8615 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8616 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8617 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8618 		     sizeof(persis_io.pr), M_WAITOK);
8619 		break;
8620 
8621 	case SPRO_PREEMPT:
8622 	case SPRO_PRE_ABO: {
8623 		int nretval;
8624 
8625 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8626 					  residx, ctsio, cdb, param);
8627 		if (nretval != 0)
8628 			return (CTL_RETVAL_COMPLETE);
8629 		break;
8630 	}
8631 	default:
8632 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8633 	}
8634 
8635 done:
8636 	free(ctsio->kern_data_ptr, M_CTL);
8637 	ctl_set_success(ctsio);
8638 	ctl_done((union ctl_io *)ctsio);
8639 
8640 	return (retval);
8641 }
8642 
8643 /*
8644  * This routine is for handling a message from the other SC pertaining to
8645  * persistent reserve out. All the error checking will have been done
8646  * so only performing the action need be done here to keep the two
8647  * in sync.
8648  */
8649 static void
8650 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8651 {
8652 	struct ctl_softc *softc = CTL_SOFTC(io);
8653 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8654 	struct ctl_lun *lun;
8655 	int i;
8656 	uint32_t residx, targ_lun;
8657 
8658 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8659 	mtx_lock(&softc->ctl_lock);
8660 	if (targ_lun >= ctl_max_luns ||
8661 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8662 		mtx_unlock(&softc->ctl_lock);
8663 		return;
8664 	}
8665 	mtx_lock(&lun->lun_lock);
8666 	mtx_unlock(&softc->ctl_lock);
8667 	if (lun->flags & CTL_LUN_DISABLED) {
8668 		mtx_unlock(&lun->lun_lock);
8669 		return;
8670 	}
8671 	residx = ctl_get_initindex(&msg->hdr.nexus);
8672 	switch(msg->pr.pr_info.action) {
8673 	case CTL_PR_REG_KEY:
8674 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8675 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8676 			lun->pr_key_count++;
8677 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8678 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8679 		lun->pr_generation++;
8680 		break;
8681 
8682 	case CTL_PR_UNREG_KEY:
8683 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8684 		lun->pr_key_count--;
8685 
8686 		/* XXX Need to see if the reservation has been released */
8687 		/* if so do we need to generate UA? */
8688 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8689 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8690 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8691 
8692 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8693 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8694 			    lun->pr_key_count) {
8695 				/*
8696 				 * If the reservation is a registrants
8697 				 * only type we need to generate a UA
8698 				 * for other registered inits.  The
8699 				 * sense code should be RESERVATIONS
8700 				 * RELEASED
8701 				 */
8702 
8703 				for (i = softc->init_min; i < softc->init_max; i++) {
8704 					if (ctl_get_prkey(lun, i) == 0)
8705 						continue;
8706 
8707 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8708 				}
8709 			}
8710 			lun->pr_res_type = 0;
8711 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8712 			if (lun->pr_key_count==0) {
8713 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8714 				lun->pr_res_type = 0;
8715 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8716 			}
8717 		}
8718 		lun->pr_generation++;
8719 		break;
8720 
8721 	case CTL_PR_RESERVE:
8722 		lun->flags |= CTL_LUN_PR_RESERVED;
8723 		lun->pr_res_type = msg->pr.pr_info.res_type;
8724 		lun->pr_res_idx = msg->pr.pr_info.residx;
8725 
8726 		break;
8727 
8728 	case CTL_PR_RELEASE:
8729 		/*
8730 		 * If this isn't an exclusive access reservation and NUAR
8731 		 * is not set, generate UA for all other registrants.
8732 		 */
8733 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8734 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8735 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8736 			for (i = softc->init_min; i < softc->init_max; i++) {
8737 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8738 					continue;
8739 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8740 			}
8741 		}
8742 
8743 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8744 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8745 		lun->pr_res_type = 0;
8746 		break;
8747 
8748 	case CTL_PR_PREEMPT:
8749 		ctl_pro_preempt_other(lun, msg);
8750 		break;
8751 	case CTL_PR_CLEAR:
8752 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8753 		lun->pr_res_type = 0;
8754 		lun->pr_key_count = 0;
8755 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8756 
8757 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8758 			if (ctl_get_prkey(lun, i) == 0)
8759 				continue;
8760 			ctl_clr_prkey(lun, i);
8761 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8762 		}
8763 		lun->pr_generation++;
8764 		break;
8765 	}
8766 
8767 	mtx_unlock(&lun->lun_lock);
8768 }
8769 
8770 int
8771 ctl_read_write(struct ctl_scsiio *ctsio)
8772 {
8773 	struct ctl_lun *lun = CTL_LUN(ctsio);
8774 	struct ctl_lba_len_flags *lbalen;
8775 	uint64_t lba;
8776 	uint32_t num_blocks;
8777 	int flags, retval;
8778 	int isread;
8779 
8780 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8781 
8782 	flags = 0;
8783 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8784 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8785 	switch (ctsio->cdb[0]) {
8786 	case READ_6:
8787 	case WRITE_6: {
8788 		struct scsi_rw_6 *cdb;
8789 
8790 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8791 
8792 		lba = scsi_3btoul(cdb->addr);
8793 		/* only 5 bits are valid in the most significant address byte */
8794 		lba &= 0x1fffff;
8795 		num_blocks = cdb->length;
8796 		/*
8797 		 * This is correct according to SBC-2.
8798 		 */
8799 		if (num_blocks == 0)
8800 			num_blocks = 256;
8801 		break;
8802 	}
8803 	case READ_10:
8804 	case WRITE_10: {
8805 		struct scsi_rw_10 *cdb;
8806 
8807 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8808 		if (cdb->byte2 & SRW10_FUA)
8809 			flags |= CTL_LLF_FUA;
8810 		if (cdb->byte2 & SRW10_DPO)
8811 			flags |= CTL_LLF_DPO;
8812 		lba = scsi_4btoul(cdb->addr);
8813 		num_blocks = scsi_2btoul(cdb->length);
8814 		break;
8815 	}
8816 	case WRITE_VERIFY_10: {
8817 		struct scsi_write_verify_10 *cdb;
8818 
8819 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8820 		flags |= CTL_LLF_FUA;
8821 		if (cdb->byte2 & SWV_DPO)
8822 			flags |= CTL_LLF_DPO;
8823 		lba = scsi_4btoul(cdb->addr);
8824 		num_blocks = scsi_2btoul(cdb->length);
8825 		break;
8826 	}
8827 	case READ_12:
8828 	case WRITE_12: {
8829 		struct scsi_rw_12 *cdb;
8830 
8831 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8832 		if (cdb->byte2 & SRW12_FUA)
8833 			flags |= CTL_LLF_FUA;
8834 		if (cdb->byte2 & SRW12_DPO)
8835 			flags |= CTL_LLF_DPO;
8836 		lba = scsi_4btoul(cdb->addr);
8837 		num_blocks = scsi_4btoul(cdb->length);
8838 		break;
8839 	}
8840 	case WRITE_VERIFY_12: {
8841 		struct scsi_write_verify_12 *cdb;
8842 
8843 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8844 		flags |= CTL_LLF_FUA;
8845 		if (cdb->byte2 & SWV_DPO)
8846 			flags |= CTL_LLF_DPO;
8847 		lba = scsi_4btoul(cdb->addr);
8848 		num_blocks = scsi_4btoul(cdb->length);
8849 		break;
8850 	}
8851 	case READ_16:
8852 	case WRITE_16: {
8853 		struct scsi_rw_16 *cdb;
8854 
8855 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8856 		if (cdb->byte2 & SRW12_FUA)
8857 			flags |= CTL_LLF_FUA;
8858 		if (cdb->byte2 & SRW12_DPO)
8859 			flags |= CTL_LLF_DPO;
8860 		lba = scsi_8btou64(cdb->addr);
8861 		num_blocks = scsi_4btoul(cdb->length);
8862 		break;
8863 	}
8864 	case WRITE_ATOMIC_16: {
8865 		struct scsi_write_atomic_16 *cdb;
8866 
8867 		if (lun->be_lun->atomicblock == 0) {
8868 			ctl_set_invalid_opcode(ctsio);
8869 			ctl_done((union ctl_io *)ctsio);
8870 			return (CTL_RETVAL_COMPLETE);
8871 		}
8872 
8873 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8874 		if (cdb->byte2 & SRW12_FUA)
8875 			flags |= CTL_LLF_FUA;
8876 		if (cdb->byte2 & SRW12_DPO)
8877 			flags |= CTL_LLF_DPO;
8878 		lba = scsi_8btou64(cdb->addr);
8879 		num_blocks = scsi_2btoul(cdb->length);
8880 		if (num_blocks > lun->be_lun->atomicblock) {
8881 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8882 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8883 			    /*bit*/ 0);
8884 			ctl_done((union ctl_io *)ctsio);
8885 			return (CTL_RETVAL_COMPLETE);
8886 		}
8887 		break;
8888 	}
8889 	case WRITE_VERIFY_16: {
8890 		struct scsi_write_verify_16 *cdb;
8891 
8892 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8893 		flags |= CTL_LLF_FUA;
8894 		if (cdb->byte2 & SWV_DPO)
8895 			flags |= CTL_LLF_DPO;
8896 		lba = scsi_8btou64(cdb->addr);
8897 		num_blocks = scsi_4btoul(cdb->length);
8898 		break;
8899 	}
8900 	default:
8901 		/*
8902 		 * We got a command we don't support.  This shouldn't
8903 		 * happen, commands should be filtered out above us.
8904 		 */
8905 		ctl_set_invalid_opcode(ctsio);
8906 		ctl_done((union ctl_io *)ctsio);
8907 
8908 		return (CTL_RETVAL_COMPLETE);
8909 		break; /* NOTREACHED */
8910 	}
8911 
8912 	/*
8913 	 * The first check is to make sure we're in bounds, the second
8914 	 * check is to catch wrap-around problems.  If the lba + num blocks
8915 	 * is less than the lba, then we've wrapped around and the block
8916 	 * range is invalid anyway.
8917 	 */
8918 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8919 	 || ((lba + num_blocks) < lba)) {
8920 		ctl_set_lba_out_of_range(ctsio,
8921 		    MAX(lba, lun->be_lun->maxlba + 1));
8922 		ctl_done((union ctl_io *)ctsio);
8923 		return (CTL_RETVAL_COMPLETE);
8924 	}
8925 
8926 	/*
8927 	 * According to SBC-3, a transfer length of 0 is not an error.
8928 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8929 	 * translates to 256 blocks for those commands.
8930 	 */
8931 	if (num_blocks == 0) {
8932 		ctl_set_success(ctsio);
8933 		ctl_done((union ctl_io *)ctsio);
8934 		return (CTL_RETVAL_COMPLETE);
8935 	}
8936 
8937 	/* Set FUA and/or DPO if caches are disabled. */
8938 	if (isread) {
8939 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8940 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8941 	} else {
8942 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8943 			flags |= CTL_LLF_FUA;
8944 	}
8945 
8946 	lbalen = (struct ctl_lba_len_flags *)
8947 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8948 	lbalen->lba = lba;
8949 	lbalen->len = num_blocks;
8950 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8951 
8952 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8953 	ctsio->kern_rel_offset = 0;
8954 
8955 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8956 
8957 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8958 	return (retval);
8959 }
8960 
8961 static int
8962 ctl_cnw_cont(union ctl_io *io)
8963 {
8964 	struct ctl_lun *lun = CTL_LUN(io);
8965 	struct ctl_scsiio *ctsio;
8966 	struct ctl_lba_len_flags *lbalen;
8967 	int retval;
8968 
8969 	ctsio = &io->scsiio;
8970 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8971 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8972 	lbalen = (struct ctl_lba_len_flags *)
8973 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8974 	lbalen->flags &= ~CTL_LLF_COMPARE;
8975 	lbalen->flags |= CTL_LLF_WRITE;
8976 
8977 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8978 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8979 	return (retval);
8980 }
8981 
8982 int
8983 ctl_cnw(struct ctl_scsiio *ctsio)
8984 {
8985 	struct ctl_lun *lun = CTL_LUN(ctsio);
8986 	struct ctl_lba_len_flags *lbalen;
8987 	uint64_t lba;
8988 	uint32_t num_blocks;
8989 	int flags, retval;
8990 
8991 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8992 
8993 	flags = 0;
8994 	switch (ctsio->cdb[0]) {
8995 	case COMPARE_AND_WRITE: {
8996 		struct scsi_compare_and_write *cdb;
8997 
8998 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8999 		if (cdb->byte2 & SRW10_FUA)
9000 			flags |= CTL_LLF_FUA;
9001 		if (cdb->byte2 & SRW10_DPO)
9002 			flags |= CTL_LLF_DPO;
9003 		lba = scsi_8btou64(cdb->addr);
9004 		num_blocks = cdb->length;
9005 		break;
9006 	}
9007 	default:
9008 		/*
9009 		 * We got a command we don't support.  This shouldn't
9010 		 * happen, commands should be filtered out above us.
9011 		 */
9012 		ctl_set_invalid_opcode(ctsio);
9013 		ctl_done((union ctl_io *)ctsio);
9014 
9015 		return (CTL_RETVAL_COMPLETE);
9016 		break; /* NOTREACHED */
9017 	}
9018 
9019 	/*
9020 	 * The first check is to make sure we're in bounds, the second
9021 	 * check is to catch wrap-around problems.  If the lba + num blocks
9022 	 * is less than the lba, then we've wrapped around and the block
9023 	 * range is invalid anyway.
9024 	 */
9025 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9026 	 || ((lba + num_blocks) < lba)) {
9027 		ctl_set_lba_out_of_range(ctsio,
9028 		    MAX(lba, lun->be_lun->maxlba + 1));
9029 		ctl_done((union ctl_io *)ctsio);
9030 		return (CTL_RETVAL_COMPLETE);
9031 	}
9032 
9033 	/*
9034 	 * According to SBC-3, a transfer length of 0 is not an error.
9035 	 */
9036 	if (num_blocks == 0) {
9037 		ctl_set_success(ctsio);
9038 		ctl_done((union ctl_io *)ctsio);
9039 		return (CTL_RETVAL_COMPLETE);
9040 	}
9041 
9042 	/* Set FUA if write cache is disabled. */
9043 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
9044 		flags |= CTL_LLF_FUA;
9045 
9046 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9047 	ctsio->kern_rel_offset = 0;
9048 
9049 	/*
9050 	 * Set the IO_CONT flag, so that if this I/O gets passed to
9051 	 * ctl_data_submit_done(), it'll get passed back to
9052 	 * ctl_ctl_cnw_cont() for further processing.
9053 	 */
9054 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9055 	ctsio->io_cont = ctl_cnw_cont;
9056 
9057 	lbalen = (struct ctl_lba_len_flags *)
9058 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9059 	lbalen->lba = lba;
9060 	lbalen->len = num_blocks;
9061 	lbalen->flags = CTL_LLF_COMPARE | flags;
9062 
9063 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9064 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9065 	return (retval);
9066 }
9067 
9068 int
9069 ctl_verify(struct ctl_scsiio *ctsio)
9070 {
9071 	struct ctl_lun *lun = CTL_LUN(ctsio);
9072 	struct ctl_lba_len_flags *lbalen;
9073 	uint64_t lba;
9074 	uint32_t num_blocks;
9075 	int bytchk, flags;
9076 	int retval;
9077 
9078 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9079 
9080 	bytchk = 0;
9081 	flags = CTL_LLF_FUA;
9082 	switch (ctsio->cdb[0]) {
9083 	case VERIFY_10: {
9084 		struct scsi_verify_10 *cdb;
9085 
9086 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9087 		if (cdb->byte2 & SVFY_BYTCHK)
9088 			bytchk = 1;
9089 		if (cdb->byte2 & SVFY_DPO)
9090 			flags |= CTL_LLF_DPO;
9091 		lba = scsi_4btoul(cdb->addr);
9092 		num_blocks = scsi_2btoul(cdb->length);
9093 		break;
9094 	}
9095 	case VERIFY_12: {
9096 		struct scsi_verify_12 *cdb;
9097 
9098 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9099 		if (cdb->byte2 & SVFY_BYTCHK)
9100 			bytchk = 1;
9101 		if (cdb->byte2 & SVFY_DPO)
9102 			flags |= CTL_LLF_DPO;
9103 		lba = scsi_4btoul(cdb->addr);
9104 		num_blocks = scsi_4btoul(cdb->length);
9105 		break;
9106 	}
9107 	case VERIFY_16: {
9108 		struct scsi_rw_16 *cdb;
9109 
9110 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9111 		if (cdb->byte2 & SVFY_BYTCHK)
9112 			bytchk = 1;
9113 		if (cdb->byte2 & SVFY_DPO)
9114 			flags |= CTL_LLF_DPO;
9115 		lba = scsi_8btou64(cdb->addr);
9116 		num_blocks = scsi_4btoul(cdb->length);
9117 		break;
9118 	}
9119 	default:
9120 		/*
9121 		 * We got a command we don't support.  This shouldn't
9122 		 * happen, commands should be filtered out above us.
9123 		 */
9124 		ctl_set_invalid_opcode(ctsio);
9125 		ctl_done((union ctl_io *)ctsio);
9126 		return (CTL_RETVAL_COMPLETE);
9127 	}
9128 
9129 	/*
9130 	 * The first check is to make sure we're in bounds, the second
9131 	 * check is to catch wrap-around problems.  If the lba + num blocks
9132 	 * is less than the lba, then we've wrapped around and the block
9133 	 * range is invalid anyway.
9134 	 */
9135 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9136 	 || ((lba + num_blocks) < lba)) {
9137 		ctl_set_lba_out_of_range(ctsio,
9138 		    MAX(lba, lun->be_lun->maxlba + 1));
9139 		ctl_done((union ctl_io *)ctsio);
9140 		return (CTL_RETVAL_COMPLETE);
9141 	}
9142 
9143 	/*
9144 	 * According to SBC-3, a transfer length of 0 is not an error.
9145 	 */
9146 	if (num_blocks == 0) {
9147 		ctl_set_success(ctsio);
9148 		ctl_done((union ctl_io *)ctsio);
9149 		return (CTL_RETVAL_COMPLETE);
9150 	}
9151 
9152 	lbalen = (struct ctl_lba_len_flags *)
9153 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9154 	lbalen->lba = lba;
9155 	lbalen->len = num_blocks;
9156 	if (bytchk) {
9157 		lbalen->flags = CTL_LLF_COMPARE | flags;
9158 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9159 	} else {
9160 		lbalen->flags = CTL_LLF_VERIFY | flags;
9161 		ctsio->kern_total_len = 0;
9162 	}
9163 	ctsio->kern_rel_offset = 0;
9164 
9165 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9166 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9167 	return (retval);
9168 }
9169 
9170 int
9171 ctl_report_luns(struct ctl_scsiio *ctsio)
9172 {
9173 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9174 	struct ctl_port *port = CTL_PORT(ctsio);
9175 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9176 	struct scsi_report_luns *cdb;
9177 	struct scsi_report_luns_data *lun_data;
9178 	int num_filled, num_luns, num_port_luns, retval;
9179 	uint32_t alloc_len, lun_datalen;
9180 	uint32_t initidx, targ_lun_id, lun_id;
9181 
9182 	retval = CTL_RETVAL_COMPLETE;
9183 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9184 
9185 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9186 
9187 	num_luns = 0;
9188 	num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
9189 	mtx_lock(&softc->ctl_lock);
9190 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9191 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9192 			num_luns++;
9193 	}
9194 	mtx_unlock(&softc->ctl_lock);
9195 
9196 	switch (cdb->select_report) {
9197 	case RPL_REPORT_DEFAULT:
9198 	case RPL_REPORT_ALL:
9199 	case RPL_REPORT_NONSUBSID:
9200 		break;
9201 	case RPL_REPORT_WELLKNOWN:
9202 	case RPL_REPORT_ADMIN:
9203 	case RPL_REPORT_CONGLOM:
9204 		num_luns = 0;
9205 		break;
9206 	default:
9207 		ctl_set_invalid_field(ctsio,
9208 				      /*sks_valid*/ 1,
9209 				      /*command*/ 1,
9210 				      /*field*/ 2,
9211 				      /*bit_valid*/ 0,
9212 				      /*bit*/ 0);
9213 		ctl_done((union ctl_io *)ctsio);
9214 		return (retval);
9215 		break; /* NOTREACHED */
9216 	}
9217 
9218 	alloc_len = scsi_4btoul(cdb->length);
9219 	/*
9220 	 * The initiator has to allocate at least 16 bytes for this request,
9221 	 * so he can at least get the header and the first LUN.  Otherwise
9222 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9223 	 */
9224 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9225 	    sizeof(struct scsi_report_luns_lundata))) {
9226 		ctl_set_invalid_field(ctsio,
9227 				      /*sks_valid*/ 1,
9228 				      /*command*/ 1,
9229 				      /*field*/ 6,
9230 				      /*bit_valid*/ 0,
9231 				      /*bit*/ 0);
9232 		ctl_done((union ctl_io *)ctsio);
9233 		return (retval);
9234 	}
9235 
9236 	lun_datalen = sizeof(*lun_data) +
9237 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9238 
9239 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9240 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9241 	ctsio->kern_sg_entries = 0;
9242 
9243 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9244 
9245 	mtx_lock(&softc->ctl_lock);
9246 	for (targ_lun_id = 0, num_filled = 0;
9247 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9248 	    targ_lun_id++) {
9249 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9250 		if (lun_id == UINT32_MAX)
9251 			continue;
9252 		lun = softc->ctl_luns[lun_id];
9253 		if (lun == NULL)
9254 			continue;
9255 
9256 		be64enc(lun_data->luns[num_filled++].lundata,
9257 		    ctl_encode_lun(targ_lun_id));
9258 
9259 		/*
9260 		 * According to SPC-3, rev 14 section 6.21:
9261 		 *
9262 		 * "The execution of a REPORT LUNS command to any valid and
9263 		 * installed logical unit shall clear the REPORTED LUNS DATA
9264 		 * HAS CHANGED unit attention condition for all logical
9265 		 * units of that target with respect to the requesting
9266 		 * initiator. A valid and installed logical unit is one
9267 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9268 		 * INQUIRY data (see 6.4.2)."
9269 		 *
9270 		 * If request_lun is NULL, the LUN this report luns command
9271 		 * was issued to is either disabled or doesn't exist. In that
9272 		 * case, we shouldn't clear any pending lun change unit
9273 		 * attention.
9274 		 */
9275 		if (request_lun != NULL) {
9276 			mtx_lock(&lun->lun_lock);
9277 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9278 			mtx_unlock(&lun->lun_lock);
9279 		}
9280 	}
9281 	mtx_unlock(&softc->ctl_lock);
9282 
9283 	/*
9284 	 * It's quite possible that we've returned fewer LUNs than we allocated
9285 	 * space for.  Trim it.
9286 	 */
9287 	lun_datalen = sizeof(*lun_data) +
9288 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9289 	ctsio->kern_rel_offset = 0;
9290 	ctsio->kern_sg_entries = 0;
9291 	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9292 	ctsio->kern_total_len = ctsio->kern_data_len;
9293 
9294 	/*
9295 	 * We set this to the actual data length, regardless of how much
9296 	 * space we actually have to return results.  If the user looks at
9297 	 * this value, he'll know whether or not he allocated enough space
9298 	 * and reissue the command if necessary.  We don't support well
9299 	 * known logical units, so if the user asks for that, return none.
9300 	 */
9301 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9302 
9303 	/*
9304 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9305 	 * this request.
9306 	 */
9307 	ctl_set_success(ctsio);
9308 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9309 	ctsio->be_move_done = ctl_config_move_done;
9310 	ctl_datamove((union ctl_io *)ctsio);
9311 	return (retval);
9312 }
9313 
9314 int
9315 ctl_request_sense(struct ctl_scsiio *ctsio)
9316 {
9317 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9318 	struct ctl_lun *lun = CTL_LUN(ctsio);
9319 	struct scsi_request_sense *cdb;
9320 	struct scsi_sense_data *sense_ptr, *ps;
9321 	uint32_t initidx;
9322 	int have_error;
9323 	u_int sense_len = SSD_FULL_SIZE;
9324 	scsi_sense_data_type sense_format;
9325 	ctl_ua_type ua_type;
9326 	uint8_t asc = 0, ascq = 0;
9327 
9328 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9329 
9330 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9331 
9332 	/*
9333 	 * Determine which sense format the user wants.
9334 	 */
9335 	if (cdb->byte2 & SRS_DESC)
9336 		sense_format = SSD_TYPE_DESC;
9337 	else
9338 		sense_format = SSD_TYPE_FIXED;
9339 
9340 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9341 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9342 	ctsio->kern_sg_entries = 0;
9343 	ctsio->kern_rel_offset = 0;
9344 
9345 	/*
9346 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9347 	 * larger than the largest allowed value for the length field in the
9348 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9349 	 */
9350 	ctsio->kern_data_len = cdb->length;
9351 	ctsio->kern_total_len = cdb->length;
9352 
9353 	/*
9354 	 * If we don't have a LUN, we don't have any pending sense.
9355 	 */
9356 	if (lun == NULL ||
9357 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9358 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9359 		/* "Logical unit not supported" */
9360 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9361 		    /*current_error*/ 1,
9362 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9363 		    /*asc*/ 0x25,
9364 		    /*ascq*/ 0x00,
9365 		    SSD_ELEM_NONE);
9366 		goto send;
9367 	}
9368 
9369 	have_error = 0;
9370 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9371 	/*
9372 	 * Check for pending sense, and then for pending unit attentions.
9373 	 * Pending sense gets returned first, then pending unit attentions.
9374 	 */
9375 	mtx_lock(&lun->lun_lock);
9376 	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9377 	if (ps != NULL)
9378 		ps += initidx % CTL_MAX_INIT_PER_PORT;
9379 	if (ps != NULL && ps->error_code != 0) {
9380 		scsi_sense_data_type stored_format;
9381 
9382 		/*
9383 		 * Check to see which sense format was used for the stored
9384 		 * sense data.
9385 		 */
9386 		stored_format = scsi_sense_type(ps);
9387 
9388 		/*
9389 		 * If the user requested a different sense format than the
9390 		 * one we stored, then we need to convert it to the other
9391 		 * format.  If we're going from descriptor to fixed format
9392 		 * sense data, we may lose things in translation, depending
9393 		 * on what options were used.
9394 		 *
9395 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9396 		 * for some reason we'll just copy it out as-is.
9397 		 */
9398 		if ((stored_format == SSD_TYPE_FIXED)
9399 		 && (sense_format == SSD_TYPE_DESC))
9400 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9401 			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9402 		else if ((stored_format == SSD_TYPE_DESC)
9403 		      && (sense_format == SSD_TYPE_FIXED))
9404 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9405 			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9406 		else
9407 			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9408 
9409 		ps->error_code = 0;
9410 		have_error = 1;
9411 	} else {
9412 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9413 		    sense_format);
9414 		if (ua_type != CTL_UA_NONE)
9415 			have_error = 1;
9416 	}
9417 	if (have_error == 0) {
9418 		/*
9419 		 * Report informational exception if have one and allowed.
9420 		 */
9421 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9422 			asc = lun->ie_asc;
9423 			ascq = lun->ie_ascq;
9424 		}
9425 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9426 		    /*current_error*/ 1,
9427 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9428 		    /*asc*/ asc,
9429 		    /*ascq*/ ascq,
9430 		    SSD_ELEM_NONE);
9431 	}
9432 	mtx_unlock(&lun->lun_lock);
9433 
9434 send:
9435 	/*
9436 	 * We report the SCSI status as OK, since the status of the command
9437 	 * itself is OK.  We're reporting sense as parameter data.
9438 	 */
9439 	ctl_set_success(ctsio);
9440 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9441 	ctsio->be_move_done = ctl_config_move_done;
9442 	ctl_datamove((union ctl_io *)ctsio);
9443 	return (CTL_RETVAL_COMPLETE);
9444 }
9445 
9446 int
9447 ctl_tur(struct ctl_scsiio *ctsio)
9448 {
9449 
9450 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9451 
9452 	ctl_set_success(ctsio);
9453 	ctl_done((union ctl_io *)ctsio);
9454 
9455 	return (CTL_RETVAL_COMPLETE);
9456 }
9457 
9458 /*
9459  * SCSI VPD page 0x00, the Supported VPD Pages page.
9460  */
9461 static int
9462 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9463 {
9464 	struct ctl_lun *lun = CTL_LUN(ctsio);
9465 	struct scsi_vpd_supported_pages *pages;
9466 	int sup_page_size;
9467 	int p;
9468 
9469 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9470 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9471 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9472 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9473 	ctsio->kern_rel_offset = 0;
9474 	ctsio->kern_sg_entries = 0;
9475 	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9476 	ctsio->kern_total_len = ctsio->kern_data_len;
9477 
9478 	/*
9479 	 * The control device is always connected.  The disk device, on the
9480 	 * other hand, may not be online all the time.  Need to change this
9481 	 * to figure out whether the disk device is actually online or not.
9482 	 */
9483 	if (lun != NULL)
9484 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9485 				lun->be_lun->lun_type;
9486 	else
9487 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9488 
9489 	p = 0;
9490 	/* Supported VPD pages */
9491 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9492 	/* Serial Number */
9493 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9494 	/* Device Identification */
9495 	pages->page_list[p++] = SVPD_DEVICE_ID;
9496 	/* Extended INQUIRY Data */
9497 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9498 	/* Mode Page Policy */
9499 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9500 	/* SCSI Ports */
9501 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9502 	/* Third-party Copy */
9503 	pages->page_list[p++] = SVPD_SCSI_TPC;
9504 	/* SCSI Feature Sets */
9505 	pages->page_list[p++] = SVPD_SCSI_SFS;
9506 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9507 		/* Block limits */
9508 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9509 		/* Block Device Characteristics */
9510 		pages->page_list[p++] = SVPD_BDC;
9511 		/* Logical Block Provisioning */
9512 		pages->page_list[p++] = SVPD_LBP;
9513 	}
9514 	pages->length = p;
9515 
9516 	ctl_set_success(ctsio);
9517 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9518 	ctsio->be_move_done = ctl_config_move_done;
9519 	ctl_datamove((union ctl_io *)ctsio);
9520 	return (CTL_RETVAL_COMPLETE);
9521 }
9522 
9523 /*
9524  * SCSI VPD page 0x80, the Unit Serial Number page.
9525  */
9526 static int
9527 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9528 {
9529 	struct ctl_lun *lun = CTL_LUN(ctsio);
9530 	struct scsi_vpd_unit_serial_number *sn_ptr;
9531 	int data_len;
9532 
9533 	data_len = 4 + CTL_SN_LEN;
9534 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9535 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9536 	ctsio->kern_rel_offset = 0;
9537 	ctsio->kern_sg_entries = 0;
9538 	ctsio->kern_data_len = min(data_len, alloc_len);
9539 	ctsio->kern_total_len = ctsio->kern_data_len;
9540 
9541 	/*
9542 	 * The control device is always connected.  The disk device, on the
9543 	 * other hand, may not be online all the time.  Need to change this
9544 	 * to figure out whether the disk device is actually online or not.
9545 	 */
9546 	if (lun != NULL)
9547 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9548 				  lun->be_lun->lun_type;
9549 	else
9550 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9551 
9552 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9553 	sn_ptr->length = CTL_SN_LEN;
9554 	/*
9555 	 * If we don't have a LUN, we just leave the serial number as
9556 	 * all spaces.
9557 	 */
9558 	if (lun != NULL) {
9559 		strncpy((char *)sn_ptr->serial_num,
9560 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9561 	} else
9562 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9563 
9564 	ctl_set_success(ctsio);
9565 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9566 	ctsio->be_move_done = ctl_config_move_done;
9567 	ctl_datamove((union ctl_io *)ctsio);
9568 	return (CTL_RETVAL_COMPLETE);
9569 }
9570 
9571 /*
9572  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9573  */
9574 static int
9575 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9576 {
9577 	struct ctl_lun *lun = CTL_LUN(ctsio);
9578 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9579 	int data_len;
9580 
9581 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9582 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9583 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9584 	ctsio->kern_sg_entries = 0;
9585 	ctsio->kern_rel_offset = 0;
9586 	ctsio->kern_data_len = min(data_len, alloc_len);
9587 	ctsio->kern_total_len = ctsio->kern_data_len;
9588 
9589 	/*
9590 	 * The control device is always connected.  The disk device, on the
9591 	 * other hand, may not be online all the time.
9592 	 */
9593 	if (lun != NULL)
9594 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9595 				     lun->be_lun->lun_type;
9596 	else
9597 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9598 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9599 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9600 	/*
9601 	 * We support head of queue, ordered and simple tags.
9602 	 */
9603 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9604 	/*
9605 	 * Volatile cache supported.
9606 	 */
9607 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9608 
9609 	/*
9610 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9611 	 * attention for a particular IT nexus on all LUNs once we report
9612 	 * it to that nexus once.  This bit is required as of SPC-4.
9613 	 */
9614 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9615 
9616 	/*
9617 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9618 	 */
9619 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9620 
9621 	/*
9622 	 * XXX KDM in order to correctly answer this, we would need
9623 	 * information from the SIM to determine how much sense data it
9624 	 * can send.  So this would really be a path inquiry field, most
9625 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9626 	 * but the hardware may or may not be able to support that much.
9627 	 * 0 just means that the maximum sense data length is not reported.
9628 	 */
9629 	eid_ptr->max_sense_length = 0;
9630 
9631 	ctl_set_success(ctsio);
9632 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9633 	ctsio->be_move_done = ctl_config_move_done;
9634 	ctl_datamove((union ctl_io *)ctsio);
9635 	return (CTL_RETVAL_COMPLETE);
9636 }
9637 
9638 static int
9639 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9640 {
9641 	struct ctl_lun *lun = CTL_LUN(ctsio);
9642 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9643 	int data_len;
9644 
9645 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9646 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9647 
9648 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9649 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9650 	ctsio->kern_rel_offset = 0;
9651 	ctsio->kern_sg_entries = 0;
9652 	ctsio->kern_data_len = min(data_len, alloc_len);
9653 	ctsio->kern_total_len = ctsio->kern_data_len;
9654 
9655 	/*
9656 	 * The control device is always connected.  The disk device, on the
9657 	 * other hand, may not be online all the time.
9658 	 */
9659 	if (lun != NULL)
9660 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9661 				     lun->be_lun->lun_type;
9662 	else
9663 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9664 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9665 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9666 	mpp_ptr->descr[0].page_code = 0x3f;
9667 	mpp_ptr->descr[0].subpage_code = 0xff;
9668 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9669 
9670 	ctl_set_success(ctsio);
9671 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9672 	ctsio->be_move_done = ctl_config_move_done;
9673 	ctl_datamove((union ctl_io *)ctsio);
9674 	return (CTL_RETVAL_COMPLETE);
9675 }
9676 
9677 /*
9678  * SCSI VPD page 0x83, the Device Identification page.
9679  */
9680 static int
9681 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9682 {
9683 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9684 	struct ctl_port *port = CTL_PORT(ctsio);
9685 	struct ctl_lun *lun = CTL_LUN(ctsio);
9686 	struct scsi_vpd_device_id *devid_ptr;
9687 	struct scsi_vpd_id_descriptor *desc;
9688 	int data_len, g;
9689 	uint8_t proto;
9690 
9691 	data_len = sizeof(struct scsi_vpd_device_id) +
9692 	    sizeof(struct scsi_vpd_id_descriptor) +
9693 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9694 	    sizeof(struct scsi_vpd_id_descriptor) +
9695 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9696 	if (lun && lun->lun_devid)
9697 		data_len += lun->lun_devid->len;
9698 	if (port && port->port_devid)
9699 		data_len += port->port_devid->len;
9700 	if (port && port->target_devid)
9701 		data_len += port->target_devid->len;
9702 
9703 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9704 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9705 	ctsio->kern_sg_entries = 0;
9706 	ctsio->kern_rel_offset = 0;
9707 	ctsio->kern_sg_entries = 0;
9708 	ctsio->kern_data_len = min(data_len, alloc_len);
9709 	ctsio->kern_total_len = ctsio->kern_data_len;
9710 
9711 	/*
9712 	 * The control device is always connected.  The disk device, on the
9713 	 * other hand, may not be online all the time.
9714 	 */
9715 	if (lun != NULL)
9716 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9717 				     lun->be_lun->lun_type;
9718 	else
9719 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9720 	devid_ptr->page_code = SVPD_DEVICE_ID;
9721 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9722 
9723 	if (port && port->port_type == CTL_PORT_FC)
9724 		proto = SCSI_PROTO_FC << 4;
9725 	else if (port && port->port_type == CTL_PORT_SAS)
9726 		proto = SCSI_PROTO_SAS << 4;
9727 	else if (port && port->port_type == CTL_PORT_ISCSI)
9728 		proto = SCSI_PROTO_ISCSI << 4;
9729 	else
9730 		proto = SCSI_PROTO_SPI << 4;
9731 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9732 
9733 	/*
9734 	 * We're using a LUN association here.  i.e., this device ID is a
9735 	 * per-LUN identifier.
9736 	 */
9737 	if (lun && lun->lun_devid) {
9738 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9739 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9740 		    lun->lun_devid->len);
9741 	}
9742 
9743 	/*
9744 	 * This is for the WWPN which is a port association.
9745 	 */
9746 	if (port && port->port_devid) {
9747 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9748 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9749 		    port->port_devid->len);
9750 	}
9751 
9752 	/*
9753 	 * This is for the Relative Target Port(type 4h) identifier
9754 	 */
9755 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9756 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9757 	    SVPD_ID_TYPE_RELTARG;
9758 	desc->length = 4;
9759 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9760 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9761 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9762 
9763 	/*
9764 	 * This is for the Target Port Group(type 5h) identifier
9765 	 */
9766 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9767 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9768 	    SVPD_ID_TYPE_TPORTGRP;
9769 	desc->length = 4;
9770 	if (softc->is_single ||
9771 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9772 		g = 1;
9773 	else
9774 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9775 	scsi_ulto2b(g, &desc->identifier[2]);
9776 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9777 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9778 
9779 	/*
9780 	 * This is for the Target identifier
9781 	 */
9782 	if (port && port->target_devid) {
9783 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9784 	}
9785 
9786 	ctl_set_success(ctsio);
9787 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9788 	ctsio->be_move_done = ctl_config_move_done;
9789 	ctl_datamove((union ctl_io *)ctsio);
9790 	return (CTL_RETVAL_COMPLETE);
9791 }
9792 
9793 static int
9794 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9795 {
9796 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9797 	struct ctl_lun *lun = CTL_LUN(ctsio);
9798 	struct scsi_vpd_scsi_ports *sp;
9799 	struct scsi_vpd_port_designation *pd;
9800 	struct scsi_vpd_port_designation_cont *pdc;
9801 	struct ctl_port *port;
9802 	int data_len, num_target_ports, iid_len, id_len;
9803 
9804 	num_target_ports = 0;
9805 	iid_len = 0;
9806 	id_len = 0;
9807 	mtx_lock(&softc->ctl_lock);
9808 	STAILQ_FOREACH(port, &softc->port_list, links) {
9809 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9810 			continue;
9811 		if (lun != NULL &&
9812 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9813 			continue;
9814 		num_target_ports++;
9815 		if (port->init_devid)
9816 			iid_len += port->init_devid->len;
9817 		if (port->port_devid)
9818 			id_len += port->port_devid->len;
9819 	}
9820 	mtx_unlock(&softc->ctl_lock);
9821 
9822 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9823 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9824 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9825 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9826 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9827 	ctsio->kern_sg_entries = 0;
9828 	ctsio->kern_rel_offset = 0;
9829 	ctsio->kern_sg_entries = 0;
9830 	ctsio->kern_data_len = min(data_len, alloc_len);
9831 	ctsio->kern_total_len = ctsio->kern_data_len;
9832 
9833 	/*
9834 	 * The control device is always connected.  The disk device, on the
9835 	 * other hand, may not be online all the time.  Need to change this
9836 	 * to figure out whether the disk device is actually online or not.
9837 	 */
9838 	if (lun != NULL)
9839 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9840 				  lun->be_lun->lun_type;
9841 	else
9842 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9843 
9844 	sp->page_code = SVPD_SCSI_PORTS;
9845 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9846 	    sp->page_length);
9847 	pd = &sp->design[0];
9848 
9849 	mtx_lock(&softc->ctl_lock);
9850 	STAILQ_FOREACH(port, &softc->port_list, links) {
9851 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9852 			continue;
9853 		if (lun != NULL &&
9854 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9855 			continue;
9856 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9857 		if (port->init_devid) {
9858 			iid_len = port->init_devid->len;
9859 			memcpy(pd->initiator_transportid,
9860 			    port->init_devid->data, port->init_devid->len);
9861 		} else
9862 			iid_len = 0;
9863 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9864 		pdc = (struct scsi_vpd_port_designation_cont *)
9865 		    (&pd->initiator_transportid[iid_len]);
9866 		if (port->port_devid) {
9867 			id_len = port->port_devid->len;
9868 			memcpy(pdc->target_port_descriptors,
9869 			    port->port_devid->data, port->port_devid->len);
9870 		} else
9871 			id_len = 0;
9872 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9873 		pd = (struct scsi_vpd_port_designation *)
9874 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9875 	}
9876 	mtx_unlock(&softc->ctl_lock);
9877 
9878 	ctl_set_success(ctsio);
9879 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9880 	ctsio->be_move_done = ctl_config_move_done;
9881 	ctl_datamove((union ctl_io *)ctsio);
9882 	return (CTL_RETVAL_COMPLETE);
9883 }
9884 
9885 static int
9886 ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len)
9887 {
9888 	struct ctl_lun *lun = CTL_LUN(ctsio);
9889 	struct scsi_vpd_sfs *sfs_ptr;
9890 	int sfs_page_size, n;
9891 
9892 	sfs_page_size = sizeof(*sfs_ptr) + 5 * 2;
9893 	ctsio->kern_data_ptr = malloc(sfs_page_size, M_CTL, M_WAITOK | M_ZERO);
9894 	sfs_ptr = (struct scsi_vpd_sfs *)ctsio->kern_data_ptr;
9895 	ctsio->kern_sg_entries = 0;
9896 	ctsio->kern_rel_offset = 0;
9897 	ctsio->kern_sg_entries = 0;
9898 	ctsio->kern_data_len = min(sfs_page_size, alloc_len);
9899 	ctsio->kern_total_len = ctsio->kern_data_len;
9900 
9901 	/*
9902 	 * The control device is always connected.  The disk device, on the
9903 	 * other hand, may not be online all the time.  Need to change this
9904 	 * to figure out whether the disk device is actually online or not.
9905 	 */
9906 	if (lun != NULL)
9907 		sfs_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9908 				  lun->be_lun->lun_type;
9909 	else
9910 		sfs_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9911 
9912 	sfs_ptr->page_code = SVPD_SCSI_SFS;
9913 	n = 0;
9914 	/* Discovery 2016 */
9915 	scsi_ulto2b(0x0001, &sfs_ptr->codes[2 * n++]);
9916 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9917 		 /* SBC Base 2016 */
9918 		scsi_ulto2b(0x0101, &sfs_ptr->codes[2 * n++]);
9919 		 /* SBC Base 2010 */
9920 		scsi_ulto2b(0x0102, &sfs_ptr->codes[2 * n++]);
9921 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9922 			/* Basic Provisioning 2016 */
9923 			scsi_ulto2b(0x0103, &sfs_ptr->codes[2 * n++]);
9924 		}
9925 		/* Drive Maintenance 2016 */
9926 		//scsi_ulto2b(0x0104, &sfs_ptr->codes[2 * n++]);
9927 	}
9928 	scsi_ulto2b(4 + 2 * n, sfs_ptr->page_length);
9929 
9930 	ctl_set_success(ctsio);
9931 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9932 	ctsio->be_move_done = ctl_config_move_done;
9933 	ctl_datamove((union ctl_io *)ctsio);
9934 	return (CTL_RETVAL_COMPLETE);
9935 }
9936 
9937 static int
9938 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9939 {
9940 	struct ctl_lun *lun = CTL_LUN(ctsio);
9941 	struct scsi_vpd_block_limits *bl_ptr;
9942 	const char *val;
9943 	uint64_t ival;
9944 
9945 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9946 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9947 	ctsio->kern_sg_entries = 0;
9948 	ctsio->kern_rel_offset = 0;
9949 	ctsio->kern_sg_entries = 0;
9950 	ctsio->kern_data_len = min(sizeof(*bl_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 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9960 				  lun->be_lun->lun_type;
9961 	else
9962 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9963 
9964 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9965 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9966 	bl_ptr->max_cmp_write_len = 0xff;
9967 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9968 	if (lun != NULL) {
9969 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9970 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9971 			ival = 0xffffffff;
9972 			val = dnvlist_get_string(lun->be_lun->options,
9973 			    "unmap_max_lba", NULL);
9974 			if (val != NULL)
9975 				ctl_expand_number(val, &ival);
9976 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9977 			ival = 0xffffffff;
9978 			val = dnvlist_get_string(lun->be_lun->options,
9979 			    "unmap_max_descr", NULL);
9980 			if (val != NULL)
9981 				ctl_expand_number(val, &ival);
9982 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9983 			if (lun->be_lun->ublockexp != 0) {
9984 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9985 				    bl_ptr->opt_unmap_grain);
9986 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9987 				    bl_ptr->unmap_grain_align);
9988 			}
9989 		}
9990 		scsi_ulto4b(lun->be_lun->atomicblock,
9991 		    bl_ptr->max_atomic_transfer_length);
9992 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9993 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9994 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9995 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9996 		ival = UINT64_MAX;
9997 		val = dnvlist_get_string(lun->be_lun->options,
9998 		    "write_same_max_lba", NULL);
9999 		if (val != NULL)
10000 			ctl_expand_number(val, &ival);
10001 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
10002 		if (lun->be_lun->maxlba + 1 > ival)
10003 			bl_ptr->flags |= SVPD_BL_WSNZ;
10004 	}
10005 
10006 	ctl_set_success(ctsio);
10007 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10008 	ctsio->be_move_done = ctl_config_move_done;
10009 	ctl_datamove((union ctl_io *)ctsio);
10010 	return (CTL_RETVAL_COMPLETE);
10011 }
10012 
10013 static int
10014 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10015 {
10016 	struct ctl_lun *lun = CTL_LUN(ctsio);
10017 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10018 	const char *value;
10019 	u_int i;
10020 
10021 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10022 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10023 	ctsio->kern_sg_entries = 0;
10024 	ctsio->kern_rel_offset = 0;
10025 	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
10026 	ctsio->kern_total_len = ctsio->kern_data_len;
10027 
10028 	/*
10029 	 * The control device is always connected.  The disk device, on the
10030 	 * other hand, may not be online all the time.  Need to change this
10031 	 * to figure out whether the disk device is actually online or not.
10032 	 */
10033 	if (lun != NULL)
10034 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10035 				  lun->be_lun->lun_type;
10036 	else
10037 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10038 	bdc_ptr->page_code = SVPD_BDC;
10039 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10040 	if (lun != NULL &&
10041 	    (value = dnvlist_get_string(lun->be_lun->options, "rpm", NULL)) != NULL)
10042 		i = strtol(value, NULL, 0);
10043 	else
10044 		i = CTL_DEFAULT_ROTATION_RATE;
10045 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10046 	if (lun != NULL &&
10047 	    (value = dnvlist_get_string(lun->be_lun->options, "formfactor", NULL)) != NULL)
10048 		i = strtol(value, NULL, 0);
10049 	else
10050 		i = 0;
10051 	bdc_ptr->wab_wac_ff = (i & 0x0f);
10052 	bdc_ptr->flags = SVPD_RBWZ | SVPD_FUAB | SVPD_VBULS;
10053 
10054 	ctl_set_success(ctsio);
10055 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10056 	ctsio->be_move_done = ctl_config_move_done;
10057 	ctl_datamove((union ctl_io *)ctsio);
10058 	return (CTL_RETVAL_COMPLETE);
10059 }
10060 
10061 static int
10062 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10063 {
10064 	struct ctl_lun *lun = CTL_LUN(ctsio);
10065 	struct scsi_vpd_logical_block_prov *lbp_ptr;
10066 	const char *value;
10067 
10068 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10069 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10070 	ctsio->kern_sg_entries = 0;
10071 	ctsio->kern_rel_offset = 0;
10072 	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
10073 	ctsio->kern_total_len = ctsio->kern_data_len;
10074 
10075 	/*
10076 	 * The control device is always connected.  The disk device, on the
10077 	 * other hand, may not be online all the time.  Need to change this
10078 	 * to figure out whether the disk device is actually online or not.
10079 	 */
10080 	if (lun != NULL)
10081 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10082 				  lun->be_lun->lun_type;
10083 	else
10084 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10085 
10086 	lbp_ptr->page_code = SVPD_LBP;
10087 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10088 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10089 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10090 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10091 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10092 		value = dnvlist_get_string(lun->be_lun->options,
10093 		    "provisioning_type", NULL);
10094 		if (value != NULL) {
10095 			if (strcmp(value, "resource") == 0)
10096 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10097 			else if (strcmp(value, "thin") == 0)
10098 				lbp_ptr->prov_type = SVPD_LBP_THIN;
10099 		} else
10100 			lbp_ptr->prov_type = SVPD_LBP_THIN;
10101 	}
10102 
10103 	ctl_set_success(ctsio);
10104 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10105 	ctsio->be_move_done = ctl_config_move_done;
10106 	ctl_datamove((union ctl_io *)ctsio);
10107 	return (CTL_RETVAL_COMPLETE);
10108 }
10109 
10110 /*
10111  * INQUIRY with the EVPD bit set.
10112  */
10113 static int
10114 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10115 {
10116 	struct ctl_lun *lun = CTL_LUN(ctsio);
10117 	struct scsi_inquiry *cdb;
10118 	int alloc_len, retval;
10119 
10120 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10121 	alloc_len = scsi_2btoul(cdb->length);
10122 
10123 	switch (cdb->page_code) {
10124 	case SVPD_SUPPORTED_PAGES:
10125 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10126 		break;
10127 	case SVPD_UNIT_SERIAL_NUMBER:
10128 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10129 		break;
10130 	case SVPD_DEVICE_ID:
10131 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10132 		break;
10133 	case SVPD_EXTENDED_INQUIRY_DATA:
10134 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10135 		break;
10136 	case SVPD_MODE_PAGE_POLICY:
10137 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10138 		break;
10139 	case SVPD_SCSI_PORTS:
10140 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10141 		break;
10142 	case SVPD_SCSI_TPC:
10143 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10144 		break;
10145 	case SVPD_SCSI_SFS:
10146 		retval = ctl_inquiry_evpd_sfs(ctsio, alloc_len);
10147 		break;
10148 	case SVPD_BLOCK_LIMITS:
10149 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10150 			goto err;
10151 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10152 		break;
10153 	case SVPD_BDC:
10154 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10155 			goto err;
10156 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10157 		break;
10158 	case SVPD_LBP:
10159 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10160 			goto err;
10161 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10162 		break;
10163 	default:
10164 err:
10165 		ctl_set_invalid_field(ctsio,
10166 				      /*sks_valid*/ 1,
10167 				      /*command*/ 1,
10168 				      /*field*/ 2,
10169 				      /*bit_valid*/ 0,
10170 				      /*bit*/ 0);
10171 		ctl_done((union ctl_io *)ctsio);
10172 		retval = CTL_RETVAL_COMPLETE;
10173 		break;
10174 	}
10175 
10176 	return (retval);
10177 }
10178 
10179 /*
10180  * Standard INQUIRY data.
10181  */
10182 static int
10183 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10184 {
10185 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
10186 	struct ctl_port *port = CTL_PORT(ctsio);
10187 	struct ctl_lun *lun = CTL_LUN(ctsio);
10188 	struct scsi_inquiry_data *inq_ptr;
10189 	struct scsi_inquiry *cdb;
10190 	const char *val;
10191 	uint32_t alloc_len, data_len;
10192 	ctl_port_type port_type;
10193 
10194 	port_type = port->port_type;
10195 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10196 		port_type = CTL_PORT_SCSI;
10197 
10198 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10199 	alloc_len = scsi_2btoul(cdb->length);
10200 
10201 	/*
10202 	 * We malloc the full inquiry data size here and fill it
10203 	 * in.  If the user only asks for less, we'll give him
10204 	 * that much.
10205 	 */
10206 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10207 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10208 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10209 	ctsio->kern_sg_entries = 0;
10210 	ctsio->kern_rel_offset = 0;
10211 	ctsio->kern_data_len = min(data_len, alloc_len);
10212 	ctsio->kern_total_len = ctsio->kern_data_len;
10213 
10214 	if (lun != NULL) {
10215 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10216 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10217 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10218 			    lun->be_lun->lun_type;
10219 		} else {
10220 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10221 			    lun->be_lun->lun_type;
10222 		}
10223 		if (lun->flags & CTL_LUN_REMOVABLE)
10224 			inq_ptr->dev_qual2 |= SID_RMB;
10225 	} else
10226 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10227 
10228 	/* RMB in byte 2 is 0 */
10229 	inq_ptr->version = SCSI_REV_SPC5;
10230 
10231 	/*
10232 	 * According to SAM-3, even if a device only supports a single
10233 	 * level of LUN addressing, it should still set the HISUP bit:
10234 	 *
10235 	 * 4.9.1 Logical unit numbers overview
10236 	 *
10237 	 * All logical unit number formats described in this standard are
10238 	 * hierarchical in structure even when only a single level in that
10239 	 * hierarchy is used. The HISUP bit shall be set to one in the
10240 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10241 	 * format described in this standard is used.  Non-hierarchical
10242 	 * formats are outside the scope of this standard.
10243 	 *
10244 	 * Therefore we set the HiSup bit here.
10245 	 *
10246 	 * The response format is 2, per SPC-3.
10247 	 */
10248 	inq_ptr->response_format = SID_HiSup | 2;
10249 
10250 	inq_ptr->additional_length = data_len -
10251 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10252 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10253 			 inq_ptr->additional_length));
10254 
10255 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10256 	if (port_type == CTL_PORT_SCSI)
10257 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10258 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10259 	inq_ptr->flags = SID_CmdQue;
10260 	if (port_type == CTL_PORT_SCSI)
10261 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10262 
10263 	/*
10264 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10265 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10266 	 * name and 4 bytes for the revision.
10267 	 */
10268 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10269 	    "vendor", NULL)) == NULL) {
10270 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10271 	} else {
10272 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10273 		strncpy(inq_ptr->vendor, val,
10274 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10275 	}
10276 	if (lun == NULL) {
10277 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10278 		    sizeof(inq_ptr->product));
10279 	} else if ((val = dnvlist_get_string(lun->be_lun->options, "product",
10280 	    NULL)) == NULL) {
10281 		switch (lun->be_lun->lun_type) {
10282 		case T_DIRECT:
10283 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10284 			    sizeof(inq_ptr->product));
10285 			break;
10286 		case T_PROCESSOR:
10287 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10288 			    sizeof(inq_ptr->product));
10289 			break;
10290 		case T_CDROM:
10291 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10292 			    sizeof(inq_ptr->product));
10293 			break;
10294 		default:
10295 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10296 			    sizeof(inq_ptr->product));
10297 			break;
10298 		}
10299 	} else {
10300 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10301 		strncpy(inq_ptr->product, val,
10302 		    min(sizeof(inq_ptr->product), strlen(val)));
10303 	}
10304 
10305 	/*
10306 	 * XXX make this a macro somewhere so it automatically gets
10307 	 * incremented when we make changes.
10308 	 */
10309 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10310 	    "revision", NULL)) == NULL) {
10311 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10312 	} else {
10313 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10314 		strncpy(inq_ptr->revision, val,
10315 		    min(sizeof(inq_ptr->revision), strlen(val)));
10316 	}
10317 
10318 	/*
10319 	 * For parallel SCSI, we support double transition and single
10320 	 * transition clocking.  We also support QAS (Quick Arbitration
10321 	 * and Selection) and Information Unit transfers on both the
10322 	 * control and array devices.
10323 	 */
10324 	if (port_type == CTL_PORT_SCSI)
10325 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10326 				    SID_SPI_IUS;
10327 
10328 	/* SAM-6 (no version claimed) */
10329 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10330 	/* SPC-5 (no version claimed) */
10331 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10332 	if (port_type == CTL_PORT_FC) {
10333 		/* FCP-2 ANSI INCITS.350:2003 */
10334 		scsi_ulto2b(0x0917, inq_ptr->version3);
10335 	} else if (port_type == CTL_PORT_SCSI) {
10336 		/* SPI-4 ANSI INCITS.362:200x */
10337 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10338 	} else if (port_type == CTL_PORT_ISCSI) {
10339 		/* iSCSI (no version claimed) */
10340 		scsi_ulto2b(0x0960, inq_ptr->version3);
10341 	} else if (port_type == CTL_PORT_SAS) {
10342 		/* SAS (no version claimed) */
10343 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10344 	} else if (port_type == CTL_PORT_UMASS) {
10345 		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10346 		scsi_ulto2b(0x1730, inq_ptr->version3);
10347 	}
10348 
10349 	if (lun == NULL) {
10350 		/* SBC-4 (no version claimed) */
10351 		scsi_ulto2b(0x0600, inq_ptr->version4);
10352 	} else {
10353 		switch (lun->be_lun->lun_type) {
10354 		case T_DIRECT:
10355 			/* SBC-4 (no version claimed) */
10356 			scsi_ulto2b(0x0600, inq_ptr->version4);
10357 			break;
10358 		case T_PROCESSOR:
10359 			break;
10360 		case T_CDROM:
10361 			/* MMC-6 (no version claimed) */
10362 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10363 			break;
10364 		default:
10365 			break;
10366 		}
10367 	}
10368 
10369 	ctl_set_success(ctsio);
10370 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10371 	ctsio->be_move_done = ctl_config_move_done;
10372 	ctl_datamove((union ctl_io *)ctsio);
10373 	return (CTL_RETVAL_COMPLETE);
10374 }
10375 
10376 int
10377 ctl_inquiry(struct ctl_scsiio *ctsio)
10378 {
10379 	struct scsi_inquiry *cdb;
10380 	int retval;
10381 
10382 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10383 
10384 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10385 	if (cdb->byte2 & SI_EVPD)
10386 		retval = ctl_inquiry_evpd(ctsio);
10387 	else if (cdb->page_code == 0)
10388 		retval = ctl_inquiry_std(ctsio);
10389 	else {
10390 		ctl_set_invalid_field(ctsio,
10391 				      /*sks_valid*/ 1,
10392 				      /*command*/ 1,
10393 				      /*field*/ 2,
10394 				      /*bit_valid*/ 0,
10395 				      /*bit*/ 0);
10396 		ctl_done((union ctl_io *)ctsio);
10397 		return (CTL_RETVAL_COMPLETE);
10398 	}
10399 
10400 	return (retval);
10401 }
10402 
10403 int
10404 ctl_get_config(struct ctl_scsiio *ctsio)
10405 {
10406 	struct ctl_lun *lun = CTL_LUN(ctsio);
10407 	struct scsi_get_config_header *hdr;
10408 	struct scsi_get_config_feature *feature;
10409 	struct scsi_get_config *cdb;
10410 	uint32_t alloc_len, data_len;
10411 	int rt, starting;
10412 
10413 	cdb = (struct scsi_get_config *)ctsio->cdb;
10414 	rt = (cdb->rt & SGC_RT_MASK);
10415 	starting = scsi_2btoul(cdb->starting_feature);
10416 	alloc_len = scsi_2btoul(cdb->length);
10417 
10418 	data_len = sizeof(struct scsi_get_config_header) +
10419 	    sizeof(struct scsi_get_config_feature) + 8 +
10420 	    sizeof(struct scsi_get_config_feature) + 8 +
10421 	    sizeof(struct scsi_get_config_feature) + 4 +
10422 	    sizeof(struct scsi_get_config_feature) + 4 +
10423 	    sizeof(struct scsi_get_config_feature) + 8 +
10424 	    sizeof(struct scsi_get_config_feature) +
10425 	    sizeof(struct scsi_get_config_feature) + 4 +
10426 	    sizeof(struct scsi_get_config_feature) + 4 +
10427 	    sizeof(struct scsi_get_config_feature) + 4 +
10428 	    sizeof(struct scsi_get_config_feature) + 4 +
10429 	    sizeof(struct scsi_get_config_feature) + 4 +
10430 	    sizeof(struct scsi_get_config_feature) + 4;
10431 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10432 	ctsio->kern_sg_entries = 0;
10433 	ctsio->kern_rel_offset = 0;
10434 
10435 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10436 	if (lun->flags & CTL_LUN_NO_MEDIA)
10437 		scsi_ulto2b(0x0000, hdr->current_profile);
10438 	else
10439 		scsi_ulto2b(0x0010, hdr->current_profile);
10440 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10441 
10442 	if (starting > 0x003b)
10443 		goto done;
10444 	if (starting > 0x003a)
10445 		goto f3b;
10446 	if (starting > 0x002b)
10447 		goto f3a;
10448 	if (starting > 0x002a)
10449 		goto f2b;
10450 	if (starting > 0x001f)
10451 		goto f2a;
10452 	if (starting > 0x001e)
10453 		goto f1f;
10454 	if (starting > 0x001d)
10455 		goto f1e;
10456 	if (starting > 0x0010)
10457 		goto f1d;
10458 	if (starting > 0x0003)
10459 		goto f10;
10460 	if (starting > 0x0002)
10461 		goto f3;
10462 	if (starting > 0x0001)
10463 		goto f2;
10464 	if (starting > 0x0000)
10465 		goto f1;
10466 
10467 	/* Profile List */
10468 	scsi_ulto2b(0x0000, feature->feature_code);
10469 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10470 	feature->add_length = 8;
10471 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10472 	feature->feature_data[2] = 0x00;
10473 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10474 	feature->feature_data[6] = 0x01;
10475 	feature = (struct scsi_get_config_feature *)
10476 	    &feature->feature_data[feature->add_length];
10477 
10478 f1:	/* Core */
10479 	scsi_ulto2b(0x0001, feature->feature_code);
10480 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10481 	feature->add_length = 8;
10482 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10483 	feature->feature_data[4] = 0x03;
10484 	feature = (struct scsi_get_config_feature *)
10485 	    &feature->feature_data[feature->add_length];
10486 
10487 f2:	/* Morphing */
10488 	scsi_ulto2b(0x0002, feature->feature_code);
10489 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10490 	feature->add_length = 4;
10491 	feature->feature_data[0] = 0x02;
10492 	feature = (struct scsi_get_config_feature *)
10493 	    &feature->feature_data[feature->add_length];
10494 
10495 f3:	/* Removable Medium */
10496 	scsi_ulto2b(0x0003, feature->feature_code);
10497 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10498 	feature->add_length = 4;
10499 	feature->feature_data[0] = 0x39;
10500 	feature = (struct scsi_get_config_feature *)
10501 	    &feature->feature_data[feature->add_length];
10502 
10503 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10504 		goto done;
10505 
10506 f10:	/* Random Read */
10507 	scsi_ulto2b(0x0010, feature->feature_code);
10508 	feature->flags = 0x00;
10509 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10510 		feature->flags |= SGC_F_CURRENT;
10511 	feature->add_length = 8;
10512 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10513 	scsi_ulto2b(1, &feature->feature_data[4]);
10514 	feature->feature_data[6] = 0x00;
10515 	feature = (struct scsi_get_config_feature *)
10516 	    &feature->feature_data[feature->add_length];
10517 
10518 f1d:	/* Multi-Read */
10519 	scsi_ulto2b(0x001D, feature->feature_code);
10520 	feature->flags = 0x00;
10521 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10522 		feature->flags |= SGC_F_CURRENT;
10523 	feature->add_length = 0;
10524 	feature = (struct scsi_get_config_feature *)
10525 	    &feature->feature_data[feature->add_length];
10526 
10527 f1e:	/* CD Read */
10528 	scsi_ulto2b(0x001E, feature->feature_code);
10529 	feature->flags = 0x00;
10530 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10531 		feature->flags |= SGC_F_CURRENT;
10532 	feature->add_length = 4;
10533 	feature->feature_data[0] = 0x00;
10534 	feature = (struct scsi_get_config_feature *)
10535 	    &feature->feature_data[feature->add_length];
10536 
10537 f1f:	/* DVD Read */
10538 	scsi_ulto2b(0x001F, feature->feature_code);
10539 	feature->flags = 0x08;
10540 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10541 		feature->flags |= SGC_F_CURRENT;
10542 	feature->add_length = 4;
10543 	feature->feature_data[0] = 0x01;
10544 	feature->feature_data[2] = 0x03;
10545 	feature = (struct scsi_get_config_feature *)
10546 	    &feature->feature_data[feature->add_length];
10547 
10548 f2a:	/* DVD+RW */
10549 	scsi_ulto2b(0x002A, feature->feature_code);
10550 	feature->flags = 0x04;
10551 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10552 		feature->flags |= SGC_F_CURRENT;
10553 	feature->add_length = 4;
10554 	feature->feature_data[0] = 0x00;
10555 	feature->feature_data[1] = 0x00;
10556 	feature = (struct scsi_get_config_feature *)
10557 	    &feature->feature_data[feature->add_length];
10558 
10559 f2b:	/* DVD+R */
10560 	scsi_ulto2b(0x002B, feature->feature_code);
10561 	feature->flags = 0x00;
10562 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10563 		feature->flags |= SGC_F_CURRENT;
10564 	feature->add_length = 4;
10565 	feature->feature_data[0] = 0x00;
10566 	feature = (struct scsi_get_config_feature *)
10567 	    &feature->feature_data[feature->add_length];
10568 
10569 f3a:	/* DVD+RW Dual Layer */
10570 	scsi_ulto2b(0x003A, feature->feature_code);
10571 	feature->flags = 0x00;
10572 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10573 		feature->flags |= SGC_F_CURRENT;
10574 	feature->add_length = 4;
10575 	feature->feature_data[0] = 0x00;
10576 	feature->feature_data[1] = 0x00;
10577 	feature = (struct scsi_get_config_feature *)
10578 	    &feature->feature_data[feature->add_length];
10579 
10580 f3b:	/* DVD+R Dual Layer */
10581 	scsi_ulto2b(0x003B, feature->feature_code);
10582 	feature->flags = 0x00;
10583 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10584 		feature->flags |= SGC_F_CURRENT;
10585 	feature->add_length = 4;
10586 	feature->feature_data[0] = 0x00;
10587 	feature = (struct scsi_get_config_feature *)
10588 	    &feature->feature_data[feature->add_length];
10589 
10590 done:
10591 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10592 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10593 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10594 		if (scsi_2btoul(feature->feature_code) == starting)
10595 			feature = (struct scsi_get_config_feature *)
10596 			    &feature->feature_data[feature->add_length];
10597 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10598 	}
10599 	scsi_ulto4b(data_len - 4, hdr->data_length);
10600 	ctsio->kern_data_len = min(data_len, alloc_len);
10601 	ctsio->kern_total_len = ctsio->kern_data_len;
10602 
10603 	ctl_set_success(ctsio);
10604 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10605 	ctsio->be_move_done = ctl_config_move_done;
10606 	ctl_datamove((union ctl_io *)ctsio);
10607 	return (CTL_RETVAL_COMPLETE);
10608 }
10609 
10610 int
10611 ctl_get_event_status(struct ctl_scsiio *ctsio)
10612 {
10613 	struct scsi_get_event_status_header *hdr;
10614 	struct scsi_get_event_status *cdb;
10615 	uint32_t alloc_len, data_len;
10616 
10617 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10618 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10619 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10620 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10621 		ctl_done((union ctl_io *)ctsio);
10622 		return (CTL_RETVAL_COMPLETE);
10623 	}
10624 	alloc_len = scsi_2btoul(cdb->length);
10625 
10626 	data_len = sizeof(struct scsi_get_event_status_header);
10627 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10628 	ctsio->kern_sg_entries = 0;
10629 	ctsio->kern_rel_offset = 0;
10630 	ctsio->kern_data_len = min(data_len, alloc_len);
10631 	ctsio->kern_total_len = ctsio->kern_data_len;
10632 
10633 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10634 	scsi_ulto2b(0, hdr->descr_length);
10635 	hdr->nea_class = SGESN_NEA;
10636 	hdr->supported_class = 0;
10637 
10638 	ctl_set_success(ctsio);
10639 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10640 	ctsio->be_move_done = ctl_config_move_done;
10641 	ctl_datamove((union ctl_io *)ctsio);
10642 	return (CTL_RETVAL_COMPLETE);
10643 }
10644 
10645 int
10646 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10647 {
10648 	struct scsi_mechanism_status_header *hdr;
10649 	struct scsi_mechanism_status *cdb;
10650 	uint32_t alloc_len, data_len;
10651 
10652 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10653 	alloc_len = scsi_2btoul(cdb->length);
10654 
10655 	data_len = sizeof(struct scsi_mechanism_status_header);
10656 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10657 	ctsio->kern_sg_entries = 0;
10658 	ctsio->kern_rel_offset = 0;
10659 	ctsio->kern_data_len = min(data_len, alloc_len);
10660 	ctsio->kern_total_len = ctsio->kern_data_len;
10661 
10662 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10663 	hdr->state1 = 0x00;
10664 	hdr->state2 = 0xe0;
10665 	scsi_ulto3b(0, hdr->lba);
10666 	hdr->slots_num = 0;
10667 	scsi_ulto2b(0, hdr->slots_length);
10668 
10669 	ctl_set_success(ctsio);
10670 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10671 	ctsio->be_move_done = ctl_config_move_done;
10672 	ctl_datamove((union ctl_io *)ctsio);
10673 	return (CTL_RETVAL_COMPLETE);
10674 }
10675 
10676 static void
10677 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10678 {
10679 
10680 	lba += 150;
10681 	buf[0] = 0;
10682 	buf[1] = bin2bcd((lba / 75) / 60);
10683 	buf[2] = bin2bcd((lba / 75) % 60);
10684 	buf[3] = bin2bcd(lba % 75);
10685 }
10686 
10687 int
10688 ctl_read_toc(struct ctl_scsiio *ctsio)
10689 {
10690 	struct ctl_lun *lun = CTL_LUN(ctsio);
10691 	struct scsi_read_toc_hdr *hdr;
10692 	struct scsi_read_toc_type01_descr *descr;
10693 	struct scsi_read_toc *cdb;
10694 	uint32_t alloc_len, data_len;
10695 	int format, msf;
10696 
10697 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10698 	msf = (cdb->byte2 & CD_MSF) != 0;
10699 	format = cdb->format;
10700 	alloc_len = scsi_2btoul(cdb->data_len);
10701 
10702 	data_len = sizeof(struct scsi_read_toc_hdr);
10703 	if (format == 0)
10704 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10705 	else
10706 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10707 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10708 	ctsio->kern_sg_entries = 0;
10709 	ctsio->kern_rel_offset = 0;
10710 	ctsio->kern_data_len = min(data_len, alloc_len);
10711 	ctsio->kern_total_len = ctsio->kern_data_len;
10712 
10713 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10714 	if (format == 0) {
10715 		scsi_ulto2b(0x12, hdr->data_length);
10716 		hdr->first = 1;
10717 		hdr->last = 1;
10718 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10719 		descr->addr_ctl = 0x14;
10720 		descr->track_number = 1;
10721 		if (msf)
10722 			ctl_ultomsf(0, descr->track_start);
10723 		else
10724 			scsi_ulto4b(0, descr->track_start);
10725 		descr++;
10726 		descr->addr_ctl = 0x14;
10727 		descr->track_number = 0xaa;
10728 		if (msf)
10729 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10730 		else
10731 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10732 	} else {
10733 		scsi_ulto2b(0x0a, hdr->data_length);
10734 		hdr->first = 1;
10735 		hdr->last = 1;
10736 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10737 		descr->addr_ctl = 0x14;
10738 		descr->track_number = 1;
10739 		if (msf)
10740 			ctl_ultomsf(0, descr->track_start);
10741 		else
10742 			scsi_ulto4b(0, descr->track_start);
10743 	}
10744 
10745 	ctl_set_success(ctsio);
10746 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10747 	ctsio->be_move_done = ctl_config_move_done;
10748 	ctl_datamove((union ctl_io *)ctsio);
10749 	return (CTL_RETVAL_COMPLETE);
10750 }
10751 
10752 /*
10753  * For known CDB types, parse the LBA and length.
10754  */
10755 static int
10756 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10757 {
10758 
10759 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10760 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10761 
10762 	switch (io->scsiio.cdb[0]) {
10763 	case COMPARE_AND_WRITE: {
10764 		struct scsi_compare_and_write *cdb;
10765 
10766 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10767 
10768 		*lba = scsi_8btou64(cdb->addr);
10769 		*len = cdb->length;
10770 		break;
10771 	}
10772 	case READ_6:
10773 	case WRITE_6: {
10774 		struct scsi_rw_6 *cdb;
10775 
10776 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10777 
10778 		*lba = scsi_3btoul(cdb->addr);
10779 		/* only 5 bits are valid in the most significant address byte */
10780 		*lba &= 0x1fffff;
10781 		*len = cdb->length;
10782 		break;
10783 	}
10784 	case READ_10:
10785 	case WRITE_10: {
10786 		struct scsi_rw_10 *cdb;
10787 
10788 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10789 
10790 		*lba = scsi_4btoul(cdb->addr);
10791 		*len = scsi_2btoul(cdb->length);
10792 		break;
10793 	}
10794 	case WRITE_VERIFY_10: {
10795 		struct scsi_write_verify_10 *cdb;
10796 
10797 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10798 
10799 		*lba = scsi_4btoul(cdb->addr);
10800 		*len = scsi_2btoul(cdb->length);
10801 		break;
10802 	}
10803 	case READ_12:
10804 	case WRITE_12: {
10805 		struct scsi_rw_12 *cdb;
10806 
10807 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10808 
10809 		*lba = scsi_4btoul(cdb->addr);
10810 		*len = scsi_4btoul(cdb->length);
10811 		break;
10812 	}
10813 	case WRITE_VERIFY_12: {
10814 		struct scsi_write_verify_12 *cdb;
10815 
10816 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10817 
10818 		*lba = scsi_4btoul(cdb->addr);
10819 		*len = scsi_4btoul(cdb->length);
10820 		break;
10821 	}
10822 	case READ_16:
10823 	case WRITE_16: {
10824 		struct scsi_rw_16 *cdb;
10825 
10826 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10827 
10828 		*lba = scsi_8btou64(cdb->addr);
10829 		*len = scsi_4btoul(cdb->length);
10830 		break;
10831 	}
10832 	case WRITE_ATOMIC_16: {
10833 		struct scsi_write_atomic_16 *cdb;
10834 
10835 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10836 
10837 		*lba = scsi_8btou64(cdb->addr);
10838 		*len = scsi_2btoul(cdb->length);
10839 		break;
10840 	}
10841 	case WRITE_VERIFY_16: {
10842 		struct scsi_write_verify_16 *cdb;
10843 
10844 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10845 
10846 		*lba = scsi_8btou64(cdb->addr);
10847 		*len = scsi_4btoul(cdb->length);
10848 		break;
10849 	}
10850 	case WRITE_SAME_10: {
10851 		struct scsi_write_same_10 *cdb;
10852 
10853 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10854 
10855 		*lba = scsi_4btoul(cdb->addr);
10856 		*len = scsi_2btoul(cdb->length);
10857 		break;
10858 	}
10859 	case WRITE_SAME_16: {
10860 		struct scsi_write_same_16 *cdb;
10861 
10862 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10863 
10864 		*lba = scsi_8btou64(cdb->addr);
10865 		*len = scsi_4btoul(cdb->length);
10866 		break;
10867 	}
10868 	case VERIFY_10: {
10869 		struct scsi_verify_10 *cdb;
10870 
10871 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10872 
10873 		*lba = scsi_4btoul(cdb->addr);
10874 		*len = scsi_2btoul(cdb->length);
10875 		break;
10876 	}
10877 	case VERIFY_12: {
10878 		struct scsi_verify_12 *cdb;
10879 
10880 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10881 
10882 		*lba = scsi_4btoul(cdb->addr);
10883 		*len = scsi_4btoul(cdb->length);
10884 		break;
10885 	}
10886 	case VERIFY_16: {
10887 		struct scsi_verify_16 *cdb;
10888 
10889 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10890 
10891 		*lba = scsi_8btou64(cdb->addr);
10892 		*len = scsi_4btoul(cdb->length);
10893 		break;
10894 	}
10895 	case UNMAP: {
10896 		*lba = 0;
10897 		*len = UINT64_MAX;
10898 		break;
10899 	}
10900 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10901 		struct scsi_get_lba_status *cdb;
10902 
10903 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10904 		*lba = scsi_8btou64(cdb->addr);
10905 		*len = UINT32_MAX;
10906 		break;
10907 	}
10908 	default:
10909 		*lba = 0;
10910 		*len = UINT64_MAX;
10911 		return (1);
10912 	}
10913 
10914 	return (0);
10915 }
10916 
10917 static ctl_action
10918 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10919     bool seq)
10920 {
10921 	uint64_t endlba1, endlba2;
10922 
10923 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10924 	endlba2 = lba2 + len2 - 1;
10925 
10926 	if ((endlba1 < lba2) || (endlba2 < lba1))
10927 		return (CTL_ACTION_PASS);
10928 	else
10929 		return (CTL_ACTION_BLOCK);
10930 }
10931 
10932 static int
10933 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10934 {
10935 	struct ctl_ptr_len_flags *ptrlen;
10936 	struct scsi_unmap_desc *buf, *end, *range;
10937 	uint64_t lba;
10938 	uint32_t len;
10939 
10940 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10941 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10942 
10943 	/* If not UNMAP -- go other way. */
10944 	if (io->scsiio.cdb[0] != UNMAP)
10945 		return (CTL_ACTION_SKIP);
10946 
10947 	/* If UNMAP without data -- block and wait for data. */
10948 	ptrlen = (struct ctl_ptr_len_flags *)
10949 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10950 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10951 	    ptrlen->ptr == NULL)
10952 		return (CTL_ACTION_BLOCK);
10953 
10954 	/* UNMAP with data -- check for collision. */
10955 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10956 	end = buf + ptrlen->len / sizeof(*buf);
10957 	for (range = buf; range < end; range++) {
10958 		lba = scsi_8btou64(range->lba);
10959 		len = scsi_4btoul(range->length);
10960 		if ((lba < lba2 + len2) && (lba + len > lba2))
10961 			return (CTL_ACTION_BLOCK);
10962 	}
10963 	return (CTL_ACTION_PASS);
10964 }
10965 
10966 static ctl_action
10967 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10968 {
10969 	uint64_t lba1, lba2;
10970 	uint64_t len1, len2;
10971 	int retval;
10972 
10973 	retval = ctl_get_lba_len(io2, &lba2, &len2);
10974 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10975 
10976 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10977 	if (retval != CTL_ACTION_SKIP)
10978 		return (retval);
10979 
10980 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10981 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10982 
10983 	if (seq && (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE))
10984 		seq = FALSE;
10985 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10986 }
10987 
10988 static ctl_action
10989 ctl_seq_check(union ctl_io *io1, union ctl_io *io2)
10990 {
10991 	uint64_t lba1, lba2;
10992 	uint64_t len1, len2;
10993 	int retval __diagused;
10994 
10995 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10996 		return (CTL_ACTION_PASS);
10997 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10998 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10999 	retval = ctl_get_lba_len(io2, &lba2, &len2);
11000 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
11001 
11002 	if (lba1 + len1 == lba2)
11003 		return (CTL_ACTION_BLOCK);
11004 	return (CTL_ACTION_PASS);
11005 }
11006 
11007 static ctl_action
11008 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11009     const uint8_t *serialize_row, union ctl_io *ooa_io)
11010 {
11011 
11012 	/*
11013 	 * The initiator attempted multiple untagged commands at the same
11014 	 * time.  Can't do that.
11015 	 */
11016 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11017 	 && __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11018 	 && ((pending_io->io_hdr.nexus.targ_port ==
11019 	      ooa_io->io_hdr.nexus.targ_port)
11020 	  && (pending_io->io_hdr.nexus.initid ==
11021 	      ooa_io->io_hdr.nexus.initid))
11022 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11023 	      CTL_FLAG_STATUS_SENT)) == 0))
11024 		return (CTL_ACTION_OVERLAP);
11025 
11026 	/*
11027 	 * The initiator attempted to send multiple tagged commands with
11028 	 * the same ID.  (It's fine if different initiators have the same
11029 	 * tag ID.)
11030 	 *
11031 	 * Even if all of those conditions are true, we don't kill the I/O
11032 	 * if the command ahead of us has been aborted.  We won't end up
11033 	 * sending it to the FETD, and it's perfectly legal to resend a
11034 	 * command with the same tag number as long as the previous
11035 	 * instance of this tag number has been aborted somehow.
11036 	 */
11037 	if (__predict_true(pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11038 	 && __predict_true(ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11039 	 && __predict_false(pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11040 	 && ((pending_io->io_hdr.nexus.targ_port ==
11041 	      ooa_io->io_hdr.nexus.targ_port)
11042 	  && (pending_io->io_hdr.nexus.initid ==
11043 	      ooa_io->io_hdr.nexus.initid))
11044 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11045 	      CTL_FLAG_STATUS_SENT)) == 0))
11046 		return (CTL_ACTION_OVERLAP_TAG);
11047 
11048 	/*
11049 	 * If we get a head of queue tag, SAM-3 says that we should
11050 	 * immediately execute it.
11051 	 *
11052 	 * What happens if this command would normally block for some other
11053 	 * reason?  e.g. a request sense with a head of queue tag
11054 	 * immediately after a write.  Normally that would block, but this
11055 	 * will result in its getting executed immediately...
11056 	 *
11057 	 * We currently return "pass" instead of "skip", so we'll end up
11058 	 * going through the rest of the queue to check for overlapped tags.
11059 	 *
11060 	 * XXX KDM check for other types of blockage first??
11061 	 */
11062 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
11063 		return (CTL_ACTION_PASS);
11064 
11065 	/*
11066 	 * Simple tags get blocked until all head of queue and ordered tags
11067 	 * ahead of them have completed.  I'm lumping untagged commands in
11068 	 * with simple tags here.  XXX KDM is that the right thing to do?
11069 	 */
11070 	if (__predict_false(ooa_io->scsiio.tag_type == CTL_TAG_ORDERED) ||
11071 	    __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
11072 		return (CTL_ACTION_BLOCK);
11073 
11074 	/* Unsupported command in OOA queue. */
11075 	if (__predict_false(ooa_io->scsiio.seridx == CTL_SERIDX_INVLD))
11076 		return (CTL_ACTION_PASS);
11077 
11078 	switch (serialize_row[ooa_io->scsiio.seridx]) {
11079 	case CTL_SER_SEQ:
11080 		if (lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11081 			return (ctl_seq_check(ooa_io, pending_io));
11082 		/* FALLTHROUGH */
11083 	case CTL_SER_PASS:
11084 		return (CTL_ACTION_PASS);
11085 	case CTL_SER_EXTENTOPT:
11086 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
11087 		    SCP_QUEUE_ALG_UNRESTRICTED)
11088 			return (CTL_ACTION_PASS);
11089 		/* FALLTHROUGH */
11090 	case CTL_SER_EXTENT:
11091 		return (ctl_extent_check(ooa_io, pending_io,
11092 		    (lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11093 	case CTL_SER_BLOCKOPT:
11094 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
11095 		    SCP_QUEUE_ALG_UNRESTRICTED)
11096 			return (CTL_ACTION_PASS);
11097 		/* FALLTHROUGH */
11098 	case CTL_SER_BLOCK:
11099 		return (CTL_ACTION_BLOCK);
11100 	default:
11101 		__assert_unreachable();
11102 	}
11103 }
11104 
11105 /*
11106  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11107  * Assumptions:
11108  * - pending_io is generally either incoming, or on the blocked queue
11109  * - starting I/O is the I/O we want to start the check with.
11110  */
11111 static ctl_action
11112 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11113 	      union ctl_io **starting_io)
11114 {
11115 	union ctl_io *ooa_io = *starting_io;
11116 	const uint8_t *serialize_row;
11117 	ctl_action action;
11118 
11119 	mtx_assert(&lun->lun_lock, MA_OWNED);
11120 
11121 	/*
11122 	 * Aborted commands are not going to be executed and may even
11123 	 * not report completion, so we don't care about their order.
11124 	 * Let them complete ASAP to clean the OOA queue.
11125 	 */
11126 	if (__predict_false(pending_io->io_hdr.flags & CTL_FLAG_ABORT))
11127 		return (CTL_ACTION_SKIP);
11128 
11129 	/*
11130 	 * Ordered tags have to block until all items ahead of them have
11131 	 * completed.  If we get called with an ordered tag, we always
11132 	 * block, if something else is ahead of us in the queue.
11133 	 */
11134 	if ((pending_io->scsiio.tag_type == CTL_TAG_ORDERED) &&
11135 	    (ooa_io != NULL))
11136 		return (CTL_ACTION_BLOCK);
11137 
11138 	serialize_row = ctl_serialize_table[pending_io->scsiio.seridx];
11139 
11140 	/*
11141 	 * Run back along the OOA queue, starting with the current
11142 	 * blocked I/O and going through every I/O before it on the
11143 	 * queue.  If starting_io is NULL, we'll just end up returning
11144 	 * CTL_ACTION_PASS.
11145 	 */
11146 	for (; ooa_io != NULL;
11147 	     ooa_io = (union ctl_io *)LIST_NEXT(&ooa_io->io_hdr, ooa_links)) {
11148 		action = ctl_check_for_blockage(lun, pending_io, serialize_row,
11149 		    ooa_io);
11150 		if (action != CTL_ACTION_PASS) {
11151 			*starting_io = ooa_io;
11152 			return (action);
11153 		}
11154 	}
11155 
11156 	*starting_io = NULL;
11157 	return (CTL_ACTION_PASS);
11158 }
11159 
11160 /*
11161  * Try to unblock the specified I/O.
11162  *
11163  * skip parameter allows explicitly skip present blocker of the I/O,
11164  * starting from the previous one on OOA queue.  It can be used when
11165  * we know for sure that the blocker I/O does no longer count.
11166  */
11167 static void
11168 ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io, bool skip)
11169 {
11170 	struct ctl_softc *softc = lun->ctl_softc;
11171 	union ctl_io *bio, *obio;
11172 	const struct ctl_cmd_entry *entry;
11173 	union ctl_ha_msg msg_info;
11174 	ctl_action action;
11175 
11176 	mtx_assert(&lun->lun_lock, MA_OWNED);
11177 
11178 	if (io->io_hdr.blocker == NULL)
11179 		return;
11180 
11181 	obio = bio = io->io_hdr.blocker;
11182 	if (skip)
11183 		bio = (union ctl_io *)LIST_NEXT(&bio->io_hdr, ooa_links);
11184 	action = ctl_check_ooa(lun, io, &bio);
11185 	if (action == CTL_ACTION_BLOCK) {
11186 		/* Still blocked, but may be by different I/O now. */
11187 		if (bio != obio) {
11188 			TAILQ_REMOVE(&obio->io_hdr.blocked_queue,
11189 			    &io->io_hdr, blocked_links);
11190 			TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue,
11191 			    &io->io_hdr, blocked_links);
11192 			io->io_hdr.blocker = bio;
11193 		}
11194 		return;
11195 	}
11196 
11197 	/* No longer blocked, one way or another. */
11198 	TAILQ_REMOVE(&obio->io_hdr.blocked_queue, &io->io_hdr, blocked_links);
11199 	io->io_hdr.blocker = NULL;
11200 
11201 	switch (action) {
11202 	case CTL_ACTION_PASS:
11203 	case CTL_ACTION_SKIP:
11204 
11205 		/* Serializing commands from the other SC retire there. */
11206 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11207 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11208 			io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11209 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11210 			msg_info.hdr.serializing_sc = io;
11211 			msg_info.hdr.msg_type = CTL_MSG_R2R;
11212 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11213 			    sizeof(msg_info.hdr), M_NOWAIT);
11214 			break;
11215 		}
11216 
11217 		/*
11218 		 * Check this I/O for LUN state changes that may have happened
11219 		 * while this command was blocked. The LUN state may have been
11220 		 * changed by a command ahead of us in the queue.
11221 		 */
11222 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11223 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
11224 			ctl_done(io);
11225 			break;
11226 		}
11227 
11228 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11229 		ctl_enqueue_rtr(io);
11230 		break;
11231 	default:
11232 		__assert_unreachable();
11233 	case CTL_ACTION_OVERLAP:
11234 		ctl_set_overlapped_cmd(&io->scsiio);
11235 		goto error;
11236 	case CTL_ACTION_OVERLAP_TAG:
11237 		ctl_set_overlapped_tag(&io->scsiio,
11238 		    io->scsiio.tag_num & 0xff);
11239 error:
11240 		/* Serializing commands from the other SC are done here. */
11241 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11242 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11243 			ctl_try_unblock_others(lun, io, TRUE);
11244 			LIST_REMOVE(&io->io_hdr, ooa_links);
11245 
11246 			ctl_copy_sense_data_back(io, &msg_info);
11247 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11248 			msg_info.hdr.serializing_sc = NULL;
11249 			msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
11250 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11251 			    sizeof(msg_info.scsi), M_WAITOK);
11252 			ctl_free_io(io);
11253 			break;
11254 		}
11255 
11256 		ctl_done(io);
11257 		break;
11258 	}
11259 }
11260 
11261 /*
11262  * Try to unblock I/Os blocked by the specified I/O.
11263  *
11264  * skip parameter allows explicitly skip the specified I/O as blocker,
11265  * starting from the previous one on the OOA queue.  It can be used when
11266  * we know for sure that the specified I/O does no longer count (done).
11267  * It has to be still on OOA queue though so that we know where to start.
11268  */
11269 static void
11270 ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *bio, bool skip)
11271 {
11272 	union ctl_io *io, *next_io;
11273 
11274 	mtx_assert(&lun->lun_lock, MA_OWNED);
11275 
11276 	for (io = (union ctl_io *)TAILQ_FIRST(&bio->io_hdr.blocked_queue);
11277 	     io != NULL; io = next_io) {
11278 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, blocked_links);
11279 
11280 		KASSERT(io->io_hdr.blocker != NULL,
11281 		    ("I/O %p on blocked list without blocker", io));
11282 		ctl_try_unblock_io(lun, io, skip);
11283 	}
11284 	KASSERT(!skip || TAILQ_EMPTY(&bio->io_hdr.blocked_queue),
11285 	    ("blocked_queue is not empty after skipping %p", bio));
11286 }
11287 
11288 /*
11289  * This routine (with one exception) checks LUN flags that can be set by
11290  * commands ahead of us in the OOA queue.  These flags have to be checked
11291  * when a command initially comes in, and when we pull a command off the
11292  * blocked queue and are preparing to execute it.  The reason we have to
11293  * check these flags for commands on the blocked queue is that the LUN
11294  * state may have been changed by a command ahead of us while we're on the
11295  * blocked queue.
11296  *
11297  * Ordering is somewhat important with these checks, so please pay
11298  * careful attention to the placement of any new checks.
11299  */
11300 static int
11301 ctl_scsiio_lun_check(struct ctl_lun *lun,
11302     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11303 {
11304 	struct ctl_softc *softc = lun->ctl_softc;
11305 	int retval;
11306 	uint32_t residx;
11307 
11308 	retval = 0;
11309 
11310 	mtx_assert(&lun->lun_lock, MA_OWNED);
11311 
11312 	/*
11313 	 * If this shelf is a secondary shelf controller, we may have to
11314 	 * reject some commands disallowed by HA mode and link state.
11315 	 */
11316 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11317 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11318 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11319 			ctl_set_lun_unavail(ctsio);
11320 			retval = 1;
11321 			goto bailout;
11322 		}
11323 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11324 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11325 			ctl_set_lun_transit(ctsio);
11326 			retval = 1;
11327 			goto bailout;
11328 		}
11329 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11330 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11331 			ctl_set_lun_standby(ctsio);
11332 			retval = 1;
11333 			goto bailout;
11334 		}
11335 
11336 		/* The rest of checks are only done on executing side */
11337 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11338 			goto bailout;
11339 	}
11340 
11341 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11342 		if (lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11343 			ctl_set_hw_write_protected(ctsio);
11344 			retval = 1;
11345 			goto bailout;
11346 		}
11347 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11348 			ctl_set_sense(ctsio, /*current_error*/ 1,
11349 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11350 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11351 			retval = 1;
11352 			goto bailout;
11353 		}
11354 	}
11355 
11356 	/*
11357 	 * Check for a reservation conflict.  If this command isn't allowed
11358 	 * even on reserved LUNs, and if this initiator isn't the one who
11359 	 * reserved us, reject the command with a reservation conflict.
11360 	 */
11361 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11362 	if ((lun->flags & CTL_LUN_RESERVED)
11363 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11364 		if (lun->res_idx != residx) {
11365 			ctl_set_reservation_conflict(ctsio);
11366 			retval = 1;
11367 			goto bailout;
11368 		}
11369 	}
11370 
11371 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11372 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11373 		/* No reservation or command is allowed. */;
11374 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11375 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11376 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11377 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11378 		/* The command is allowed for Write Exclusive resv. */;
11379 	} else {
11380 		/*
11381 		 * if we aren't registered or it's a res holder type
11382 		 * reservation and this isn't the res holder then set a
11383 		 * conflict.
11384 		 */
11385 		if (ctl_get_prkey(lun, residx) == 0 ||
11386 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11387 			ctl_set_reservation_conflict(ctsio);
11388 			retval = 1;
11389 			goto bailout;
11390 		}
11391 	}
11392 
11393 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11394 		if (lun->flags & CTL_LUN_EJECTED)
11395 			ctl_set_lun_ejected(ctsio);
11396 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11397 			if (lun->flags & CTL_LUN_REMOVABLE)
11398 				ctl_set_lun_no_media(ctsio);
11399 			else
11400 				ctl_set_lun_int_reqd(ctsio);
11401 		} else if (lun->flags & CTL_LUN_STOPPED)
11402 			ctl_set_lun_stopped(ctsio);
11403 		else
11404 			goto bailout;
11405 		retval = 1;
11406 		goto bailout;
11407 	}
11408 
11409 bailout:
11410 	return (retval);
11411 }
11412 
11413 static void
11414 ctl_failover_io(union ctl_io *io, int have_lock)
11415 {
11416 	ctl_set_busy(&io->scsiio);
11417 	ctl_done(io);
11418 }
11419 
11420 static void
11421 ctl_failover_lun(union ctl_io *rio)
11422 {
11423 	struct ctl_softc *softc = CTL_SOFTC(rio);
11424 	struct ctl_lun *lun;
11425 	struct ctl_io_hdr *io, *next_io;
11426 	uint32_t targ_lun;
11427 
11428 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11429 	CTL_DEBUG_PRINT(("FAILOVER for lun %u\n", targ_lun));
11430 
11431 	/* Find and lock the LUN. */
11432 	mtx_lock(&softc->ctl_lock);
11433 	if (targ_lun > ctl_max_luns ||
11434 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11435 		mtx_unlock(&softc->ctl_lock);
11436 		return;
11437 	}
11438 	mtx_lock(&lun->lun_lock);
11439 	mtx_unlock(&softc->ctl_lock);
11440 	if (lun->flags & CTL_LUN_DISABLED) {
11441 		mtx_unlock(&lun->lun_lock);
11442 		return;
11443 	}
11444 
11445 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11446 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11447 			/* We are master */
11448 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11449 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11450 					io->flags |= CTL_FLAG_ABORT |
11451 					    CTL_FLAG_FAILOVER;
11452 					ctl_try_unblock_io(lun,
11453 					    (union ctl_io *)io, FALSE);
11454 				} else { /* This can be only due to DATAMOVE */
11455 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11456 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11457 					io->flags |= CTL_FLAG_IO_ACTIVE;
11458 					io->port_status = 31340;
11459 					ctl_enqueue_isc((union ctl_io *)io);
11460 				}
11461 			} else
11462 			/* We are slave */
11463 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11464 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11465 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11466 					io->flags |= CTL_FLAG_FAILOVER;
11467 				} else {
11468 					ctl_set_busy(&((union ctl_io *)io)->
11469 					    scsiio);
11470 					ctl_done((union ctl_io *)io);
11471 				}
11472 			}
11473 		}
11474 	} else { /* SERIALIZE modes */
11475 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11476 			/* We are master */
11477 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11478 				if (io->blocker != NULL) {
11479 					TAILQ_REMOVE(&io->blocker->io_hdr.blocked_queue,
11480 					    io, blocked_links);
11481 					io->blocker = NULL;
11482 				}
11483 				ctl_try_unblock_others(lun, (union ctl_io *)io,
11484 				    TRUE);
11485 				LIST_REMOVE(io, ooa_links);
11486 				ctl_free_io((union ctl_io *)io);
11487 			} else
11488 			/* We are slave */
11489 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11490 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11491 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11492 					ctl_set_busy(&((union ctl_io *)io)->
11493 					    scsiio);
11494 					ctl_done((union ctl_io *)io);
11495 				}
11496 			}
11497 		}
11498 	}
11499 	mtx_unlock(&lun->lun_lock);
11500 }
11501 
11502 static void
11503 ctl_scsiio_precheck(struct ctl_scsiio *ctsio)
11504 {
11505 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
11506 	struct ctl_lun *lun;
11507 	const struct ctl_cmd_entry *entry;
11508 	union ctl_io *bio;
11509 	uint32_t initidx, targ_lun;
11510 
11511 	lun = NULL;
11512 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11513 	if (targ_lun < ctl_max_luns)
11514 		lun = softc->ctl_luns[targ_lun];
11515 	if (lun) {
11516 		/*
11517 		 * If the LUN is invalid, pretend that it doesn't exist.
11518 		 * It will go away as soon as all pending I/O has been
11519 		 * completed.
11520 		 */
11521 		mtx_lock(&lun->lun_lock);
11522 		if (lun->flags & CTL_LUN_DISABLED) {
11523 			mtx_unlock(&lun->lun_lock);
11524 			lun = NULL;
11525 		}
11526 	}
11527 	CTL_LUN(ctsio) = lun;
11528 	if (lun) {
11529 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11530 
11531 		/*
11532 		 * Every I/O goes into the OOA queue for a particular LUN,
11533 		 * and stays there until completion.
11534 		 */
11535 #ifdef CTL_TIME_IO
11536 		if (LIST_EMPTY(&lun->ooa_queue))
11537 			lun->idle_time += getsbinuptime() - lun->last_busy;
11538 #endif
11539 		LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11540 	}
11541 
11542 	/* Get command entry and return error if it is unsuppotyed. */
11543 	entry = ctl_validate_command(ctsio);
11544 	if (entry == NULL) {
11545 		if (lun)
11546 			mtx_unlock(&lun->lun_lock);
11547 		return;
11548 	}
11549 
11550 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11551 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11552 
11553 	/*
11554 	 * Check to see whether we can send this command to LUNs that don't
11555 	 * exist.  This should pretty much only be the case for inquiry
11556 	 * and request sense.  Further checks, below, really require having
11557 	 * a LUN, so we can't really check the command anymore.  Just put
11558 	 * it on the rtr queue.
11559 	 */
11560 	if (lun == NULL) {
11561 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11562 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11563 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11564 			return;
11565 		}
11566 
11567 		ctl_set_unsupported_lun(ctsio);
11568 		ctl_done((union ctl_io *)ctsio);
11569 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11570 		return;
11571 	} else {
11572 		/*
11573 		 * Make sure we support this particular command on this LUN.
11574 		 * e.g., we don't support writes to the control LUN.
11575 		 */
11576 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11577 			mtx_unlock(&lun->lun_lock);
11578 			ctl_set_invalid_opcode(ctsio);
11579 			ctl_done((union ctl_io *)ctsio);
11580 			return;
11581 		}
11582 	}
11583 
11584 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11585 
11586 	/*
11587 	 * If we've got a request sense, it'll clear the contingent
11588 	 * allegiance condition.  Otherwise, if we have a CA condition for
11589 	 * this initiator, clear it, because it sent down a command other
11590 	 * than request sense.
11591 	 */
11592 	if (ctsio->cdb[0] != REQUEST_SENSE) {
11593 		struct scsi_sense_data *ps;
11594 
11595 		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11596 		if (ps != NULL)
11597 			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11598 	}
11599 
11600 	/*
11601 	 * If the command has this flag set, it handles its own unit
11602 	 * attention reporting, we shouldn't do anything.  Otherwise we
11603 	 * check for any pending unit attentions, and send them back to the
11604 	 * initiator.  We only do this when a command initially comes in,
11605 	 * not when we pull it off the blocked queue.
11606 	 *
11607 	 * According to SAM-3, section 5.3.2, the order that things get
11608 	 * presented back to the host is basically unit attentions caused
11609 	 * by some sort of reset event, busy status, reservation conflicts
11610 	 * or task set full, and finally any other status.
11611 	 *
11612 	 * One issue here is that some of the unit attentions we report
11613 	 * don't fall into the "reset" category (e.g. "reported luns data
11614 	 * has changed").  So reporting it here, before the reservation
11615 	 * check, may be technically wrong.  I guess the only thing to do
11616 	 * would be to check for and report the reset events here, and then
11617 	 * check for the other unit attention types after we check for a
11618 	 * reservation conflict.
11619 	 *
11620 	 * XXX KDM need to fix this
11621 	 */
11622 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11623 		ctl_ua_type ua_type;
11624 		u_int sense_len = 0;
11625 
11626 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11627 		    &sense_len, SSD_TYPE_NONE);
11628 		if (ua_type != CTL_UA_NONE) {
11629 			mtx_unlock(&lun->lun_lock);
11630 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11631 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11632 			ctsio->sense_len = sense_len;
11633 			ctl_done((union ctl_io *)ctsio);
11634 			return;
11635 		}
11636 	}
11637 
11638 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11639 		mtx_unlock(&lun->lun_lock);
11640 		ctl_done((union ctl_io *)ctsio);
11641 		return;
11642 	}
11643 
11644 	/*
11645 	 * XXX CHD this is where we want to send IO to other side if
11646 	 * this LUN is secondary on this SC. We will need to make a copy
11647 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11648 	 * the copy we send as FROM_OTHER.
11649 	 * We also need to stuff the address of the original IO so we can
11650 	 * find it easily. Something similar will need be done on the other
11651 	 * side so when we are done we can find the copy.
11652 	 */
11653 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11654 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11655 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11656 		union ctl_ha_msg msg_info;
11657 		int isc_retval;
11658 
11659 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11660 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11661 		mtx_unlock(&lun->lun_lock);
11662 
11663 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11664 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11665 		msg_info.hdr.serializing_sc = NULL;
11666 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11667 		msg_info.scsi.tag_num = ctsio->tag_num;
11668 		msg_info.scsi.tag_type = ctsio->tag_type;
11669 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11670 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11671 		msg_info.scsi.priority = ctsio->priority;
11672 
11673 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11674 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11675 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11676 			ctsio->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11677 			ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
11678 			ctl_set_busy(ctsio);
11679 			ctl_done((union ctl_io *)ctsio);
11680 			return;
11681 		}
11682 		return;
11683 	}
11684 
11685 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
11686 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
11687 	case CTL_ACTION_PASS:
11688 	case CTL_ACTION_SKIP:
11689 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11690 		mtx_unlock(&lun->lun_lock);
11691 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11692 		break;
11693 	case CTL_ACTION_BLOCK:
11694 		ctsio->io_hdr.blocker = bio;
11695 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
11696 				  blocked_links);
11697 		mtx_unlock(&lun->lun_lock);
11698 		break;
11699 	case CTL_ACTION_OVERLAP:
11700 		mtx_unlock(&lun->lun_lock);
11701 		ctl_set_overlapped_cmd(ctsio);
11702 		ctl_done((union ctl_io *)ctsio);
11703 		break;
11704 	case CTL_ACTION_OVERLAP_TAG:
11705 		mtx_unlock(&lun->lun_lock);
11706 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11707 		ctl_done((union ctl_io *)ctsio);
11708 		break;
11709 	default:
11710 		__assert_unreachable();
11711 	}
11712 }
11713 
11714 const struct ctl_cmd_entry *
11715 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11716 {
11717 	const struct ctl_cmd_entry *entry;
11718 	int service_action;
11719 
11720 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11721 	if (sa)
11722 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11723 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11724 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11725 		entry = &((const struct ctl_cmd_entry *)
11726 		    entry->execute)[service_action];
11727 	}
11728 	return (entry);
11729 }
11730 
11731 const struct ctl_cmd_entry *
11732 ctl_validate_command(struct ctl_scsiio *ctsio)
11733 {
11734 	const struct ctl_cmd_entry *entry;
11735 	int i, sa;
11736 	uint8_t diff;
11737 
11738 	entry = ctl_get_cmd_entry(ctsio, &sa);
11739 	ctsio->seridx = entry->seridx;
11740 	if (entry->execute == NULL) {
11741 		if (sa)
11742 			ctl_set_invalid_field(ctsio,
11743 					      /*sks_valid*/ 1,
11744 					      /*command*/ 1,
11745 					      /*field*/ 1,
11746 					      /*bit_valid*/ 1,
11747 					      /*bit*/ 4);
11748 		else
11749 			ctl_set_invalid_opcode(ctsio);
11750 		ctl_done((union ctl_io *)ctsio);
11751 		return (NULL);
11752 	}
11753 	KASSERT(entry->length > 0,
11754 	    ("Not defined length for command 0x%02x/0x%02x",
11755 	     ctsio->cdb[0], ctsio->cdb[1]));
11756 	for (i = 1; i < entry->length; i++) {
11757 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11758 		if (diff == 0)
11759 			continue;
11760 		ctl_set_invalid_field(ctsio,
11761 				      /*sks_valid*/ 1,
11762 				      /*command*/ 1,
11763 				      /*field*/ i,
11764 				      /*bit_valid*/ 1,
11765 				      /*bit*/ fls(diff) - 1);
11766 		ctl_done((union ctl_io *)ctsio);
11767 		return (NULL);
11768 	}
11769 	return (entry);
11770 }
11771 
11772 static int
11773 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11774 {
11775 
11776 	switch (lun_type) {
11777 	case T_DIRECT:
11778 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11779 			return (0);
11780 		break;
11781 	case T_PROCESSOR:
11782 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11783 			return (0);
11784 		break;
11785 	case T_CDROM:
11786 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11787 			return (0);
11788 		break;
11789 	default:
11790 		return (0);
11791 	}
11792 	return (1);
11793 }
11794 
11795 static int
11796 ctl_scsiio(struct ctl_scsiio *ctsio)
11797 {
11798 	int retval;
11799 	const struct ctl_cmd_entry *entry;
11800 
11801 	retval = CTL_RETVAL_COMPLETE;
11802 
11803 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11804 
11805 	entry = ctl_get_cmd_entry(ctsio, NULL);
11806 
11807 	/*
11808 	 * If this I/O has been aborted, just send it straight to
11809 	 * ctl_done() without executing it.
11810 	 */
11811 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11812 		ctl_done((union ctl_io *)ctsio);
11813 		goto bailout;
11814 	}
11815 
11816 	/*
11817 	 * All the checks should have been handled by ctl_scsiio_precheck().
11818 	 * We should be clear now to just execute the I/O.
11819 	 */
11820 	retval = entry->execute(ctsio);
11821 
11822 bailout:
11823 	return (retval);
11824 }
11825 
11826 static int
11827 ctl_target_reset(union ctl_io *io)
11828 {
11829 	struct ctl_softc *softc = CTL_SOFTC(io);
11830 	struct ctl_port *port = CTL_PORT(io);
11831 	struct ctl_lun *lun;
11832 	uint32_t initidx;
11833 	ctl_ua_type ua_type;
11834 
11835 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11836 		union ctl_ha_msg msg_info;
11837 
11838 		msg_info.hdr.nexus = io->io_hdr.nexus;
11839 		msg_info.task.task_action = io->taskio.task_action;
11840 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11841 		msg_info.hdr.original_sc = NULL;
11842 		msg_info.hdr.serializing_sc = NULL;
11843 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11844 		    sizeof(msg_info.task), M_WAITOK);
11845 	}
11846 
11847 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11848 	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11849 		ua_type = CTL_UA_TARG_RESET;
11850 	else
11851 		ua_type = CTL_UA_BUS_RESET;
11852 	mtx_lock(&softc->ctl_lock);
11853 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11854 		if (port != NULL &&
11855 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11856 			continue;
11857 		ctl_do_lun_reset(lun, initidx, ua_type);
11858 	}
11859 	mtx_unlock(&softc->ctl_lock);
11860 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11861 	return (0);
11862 }
11863 
11864 /*
11865  * The LUN should always be set.  The I/O is optional, and is used to
11866  * distinguish between I/Os sent by this initiator, and by other
11867  * initiators.  We set unit attention for initiators other than this one.
11868  * SAM-3 is vague on this point.  It does say that a unit attention should
11869  * be established for other initiators when a LUN is reset (see section
11870  * 5.7.3), but it doesn't specifically say that the unit attention should
11871  * be established for this particular initiator when a LUN is reset.  Here
11872  * is the relevant text, from SAM-3 rev 8:
11873  *
11874  * 5.7.2 When a SCSI initiator port aborts its own tasks
11875  *
11876  * When a SCSI initiator port causes its own task(s) to be aborted, no
11877  * notification that the task(s) have been aborted shall be returned to
11878  * the SCSI initiator port other than the completion response for the
11879  * command or task management function action that caused the task(s) to
11880  * be aborted and notification(s) associated with related effects of the
11881  * action (e.g., a reset unit attention condition).
11882  *
11883  * XXX KDM for now, we're setting unit attention for all initiators.
11884  */
11885 static void
11886 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11887 {
11888 	struct ctl_io_hdr *xioh;
11889 	int i;
11890 
11891 	mtx_lock(&lun->lun_lock);
11892 	/* Abort tasks. */
11893 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11894 		xioh->flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11895 		ctl_try_unblock_io(lun, (union ctl_io *)xioh, FALSE);
11896 	}
11897 	/* Clear CA. */
11898 	for (i = 0; i < ctl_max_ports; i++) {
11899 		free(lun->pending_sense[i], M_CTL);
11900 		lun->pending_sense[i] = NULL;
11901 	}
11902 	/* Clear reservation. */
11903 	lun->flags &= ~CTL_LUN_RESERVED;
11904 	/* Clear prevent media removal. */
11905 	if (lun->prevent) {
11906 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11907 			ctl_clear_mask(lun->prevent, i);
11908 		lun->prevent_count = 0;
11909 	}
11910 	/* Clear TPC status */
11911 	ctl_tpc_lun_clear(lun, -1);
11912 	/* Establish UA. */
11913 #if 0
11914 	ctl_est_ua_all(lun, initidx, ua_type);
11915 #else
11916 	ctl_est_ua_all(lun, -1, ua_type);
11917 #endif
11918 	mtx_unlock(&lun->lun_lock);
11919 }
11920 
11921 static int
11922 ctl_lun_reset(union ctl_io *io)
11923 {
11924 	struct ctl_softc *softc = CTL_SOFTC(io);
11925 	struct ctl_lun *lun;
11926 	uint32_t targ_lun, initidx;
11927 
11928 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11929 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11930 	mtx_lock(&softc->ctl_lock);
11931 	if (targ_lun >= ctl_max_luns ||
11932 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11933 		mtx_unlock(&softc->ctl_lock);
11934 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11935 		return (1);
11936 	}
11937 	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11938 	mtx_unlock(&softc->ctl_lock);
11939 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11940 
11941 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11942 		union ctl_ha_msg msg_info;
11943 
11944 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11945 		msg_info.hdr.nexus = io->io_hdr.nexus;
11946 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11947 		msg_info.hdr.original_sc = NULL;
11948 		msg_info.hdr.serializing_sc = NULL;
11949 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11950 		    sizeof(msg_info.task), M_WAITOK);
11951 	}
11952 	return (0);
11953 }
11954 
11955 static void
11956 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11957     int other_sc)
11958 {
11959 	struct ctl_io_hdr *xioh;
11960 
11961 	mtx_assert(&lun->lun_lock, MA_OWNED);
11962 
11963 	/*
11964 	 * Run through the OOA queue and attempt to find the given I/O.
11965 	 * The target port, initiator ID, tag type and tag number have to
11966 	 * match the values that we got from the initiator.  If we have an
11967 	 * untagged command to abort, simply abort the first untagged command
11968 	 * we come to.  We only allow one untagged command at a time of course.
11969 	 */
11970 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11971 		union ctl_io *xio = (union ctl_io *)xioh;
11972 		if ((targ_port == UINT32_MAX ||
11973 		     targ_port == xioh->nexus.targ_port) &&
11974 		    (init_id == UINT32_MAX ||
11975 		     init_id == xioh->nexus.initid)) {
11976 			if (targ_port != xioh->nexus.targ_port ||
11977 			    init_id != xioh->nexus.initid)
11978 				xioh->flags |= CTL_FLAG_ABORT_STATUS;
11979 			xioh->flags |= CTL_FLAG_ABORT;
11980 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11981 				union ctl_ha_msg msg_info;
11982 
11983 				msg_info.hdr.nexus = xioh->nexus;
11984 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11985 				msg_info.task.tag_num = xio->scsiio.tag_num;
11986 				msg_info.task.tag_type = xio->scsiio.tag_type;
11987 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11988 				msg_info.hdr.original_sc = NULL;
11989 				msg_info.hdr.serializing_sc = NULL;
11990 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11991 				    sizeof(msg_info.task), M_NOWAIT);
11992 			}
11993 			ctl_try_unblock_io(lun, xio, FALSE);
11994 		}
11995 	}
11996 }
11997 
11998 static int
11999 ctl_abort_task_set(union ctl_io *io)
12000 {
12001 	struct ctl_softc *softc = CTL_SOFTC(io);
12002 	struct ctl_lun *lun;
12003 	uint32_t targ_lun;
12004 
12005 	/*
12006 	 * Look up the LUN.
12007 	 */
12008 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12009 	mtx_lock(&softc->ctl_lock);
12010 	if (targ_lun >= ctl_max_luns ||
12011 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12012 		mtx_unlock(&softc->ctl_lock);
12013 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12014 		return (1);
12015 	}
12016 
12017 	mtx_lock(&lun->lun_lock);
12018 	mtx_unlock(&softc->ctl_lock);
12019 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12020 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12021 		    io->io_hdr.nexus.initid,
12022 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12023 	} else { /* CTL_TASK_CLEAR_TASK_SET */
12024 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12025 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12026 	}
12027 	mtx_unlock(&lun->lun_lock);
12028 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12029 	return (0);
12030 }
12031 
12032 static void
12033 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
12034     ctl_ua_type ua_type)
12035 {
12036 	struct ctl_lun *lun;
12037 	struct scsi_sense_data *ps;
12038 	uint32_t p, i;
12039 
12040 	p = initidx / CTL_MAX_INIT_PER_PORT;
12041 	i = initidx % CTL_MAX_INIT_PER_PORT;
12042 	mtx_lock(&softc->ctl_lock);
12043 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12044 		mtx_lock(&lun->lun_lock);
12045 		/* Abort tasks. */
12046 		ctl_abort_tasks_lun(lun, p, i, 1);
12047 		/* Clear CA. */
12048 		ps = lun->pending_sense[p];
12049 		if (ps != NULL)
12050 			ps[i].error_code = 0;
12051 		/* Clear reservation. */
12052 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12053 			lun->flags &= ~CTL_LUN_RESERVED;
12054 		/* Clear prevent media removal. */
12055 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
12056 			ctl_clear_mask(lun->prevent, initidx);
12057 			lun->prevent_count--;
12058 		}
12059 		/* Clear TPC status */
12060 		ctl_tpc_lun_clear(lun, initidx);
12061 		/* Establish UA. */
12062 		ctl_est_ua(lun, initidx, ua_type);
12063 		mtx_unlock(&lun->lun_lock);
12064 	}
12065 	mtx_unlock(&softc->ctl_lock);
12066 }
12067 
12068 static int
12069 ctl_i_t_nexus_reset(union ctl_io *io)
12070 {
12071 	struct ctl_softc *softc = CTL_SOFTC(io);
12072 	uint32_t initidx;
12073 
12074 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12075 		union ctl_ha_msg msg_info;
12076 
12077 		msg_info.hdr.nexus = io->io_hdr.nexus;
12078 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12079 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12080 		msg_info.hdr.original_sc = NULL;
12081 		msg_info.hdr.serializing_sc = NULL;
12082 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12083 		    sizeof(msg_info.task), M_WAITOK);
12084 	}
12085 
12086 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12087 	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
12088 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12089 	return (0);
12090 }
12091 
12092 static int
12093 ctl_abort_task(union ctl_io *io)
12094 {
12095 	struct ctl_softc *softc = CTL_SOFTC(io);
12096 	struct ctl_io_hdr *xioh;
12097 	struct ctl_lun *lun;
12098 	uint32_t targ_lun;
12099 
12100 	/*
12101 	 * Look up the LUN.
12102 	 */
12103 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12104 	mtx_lock(&softc->ctl_lock);
12105 	if (targ_lun >= ctl_max_luns ||
12106 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12107 		mtx_unlock(&softc->ctl_lock);
12108 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12109 		return (1);
12110 	}
12111 
12112 	mtx_lock(&lun->lun_lock);
12113 	mtx_unlock(&softc->ctl_lock);
12114 	/*
12115 	 * Run through the OOA queue and attempt to find the given I/O.
12116 	 * The target port, initiator ID, tag type and tag number have to
12117 	 * match the values that we got from the initiator.  If we have an
12118 	 * untagged command to abort, simply abort the first untagged command
12119 	 * we come to.  We only allow one untagged command at a time of course.
12120 	 */
12121 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12122 		union ctl_io *xio = (union ctl_io *)xioh;
12123 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12124 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12125 		 || (xioh->flags & CTL_FLAG_ABORT))
12126 			continue;
12127 
12128 		/*
12129 		 * If the abort says that the task is untagged, the
12130 		 * task in the queue must be untagged.  Otherwise,
12131 		 * we just check to see whether the tag numbers
12132 		 * match.  This is because the QLogic firmware
12133 		 * doesn't pass back the tag type in an abort
12134 		 * request.
12135 		 */
12136 #if 0
12137 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12138 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12139 		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12140 #else
12141 		/*
12142 		 * XXX KDM we've got problems with FC, because it
12143 		 * doesn't send down a tag type with aborts.  So we
12144 		 * can only really go by the tag number...
12145 		 * This may cause problems with parallel SCSI.
12146 		 * Need to figure that out!!
12147 		 */
12148 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12149 #endif
12150 			xioh->flags |= CTL_FLAG_ABORT;
12151 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12152 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12153 				union ctl_ha_msg msg_info;
12154 
12155 				msg_info.hdr.nexus = io->io_hdr.nexus;
12156 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12157 				msg_info.task.tag_num = io->taskio.tag_num;
12158 				msg_info.task.tag_type = io->taskio.tag_type;
12159 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12160 				msg_info.hdr.original_sc = NULL;
12161 				msg_info.hdr.serializing_sc = NULL;
12162 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12163 				    sizeof(msg_info.task), M_NOWAIT);
12164 			}
12165 			ctl_try_unblock_io(lun, xio, FALSE);
12166 		}
12167 	}
12168 	mtx_unlock(&lun->lun_lock);
12169 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12170 	return (0);
12171 }
12172 
12173 static int
12174 ctl_query_task(union ctl_io *io, int task_set)
12175 {
12176 	struct ctl_softc *softc = CTL_SOFTC(io);
12177 	struct ctl_io_hdr *xioh;
12178 	struct ctl_lun *lun;
12179 	int found = 0;
12180 	uint32_t targ_lun;
12181 
12182 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12183 	mtx_lock(&softc->ctl_lock);
12184 	if (targ_lun >= ctl_max_luns ||
12185 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12186 		mtx_unlock(&softc->ctl_lock);
12187 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12188 		return (1);
12189 	}
12190 	mtx_lock(&lun->lun_lock);
12191 	mtx_unlock(&softc->ctl_lock);
12192 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12193 		union ctl_io *xio = (union ctl_io *)xioh;
12194 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12195 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12196 		 || (xioh->flags & CTL_FLAG_ABORT))
12197 			continue;
12198 
12199 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12200 			found = 1;
12201 			break;
12202 		}
12203 	}
12204 	mtx_unlock(&lun->lun_lock);
12205 	if (found)
12206 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12207 	else
12208 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12209 	return (0);
12210 }
12211 
12212 static int
12213 ctl_query_async_event(union ctl_io *io)
12214 {
12215 	struct ctl_softc *softc = CTL_SOFTC(io);
12216 	struct ctl_lun *lun;
12217 	ctl_ua_type ua;
12218 	uint32_t targ_lun, initidx;
12219 
12220 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12221 	mtx_lock(&softc->ctl_lock);
12222 	if (targ_lun >= ctl_max_luns ||
12223 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12224 		mtx_unlock(&softc->ctl_lock);
12225 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12226 		return (1);
12227 	}
12228 	mtx_lock(&lun->lun_lock);
12229 	mtx_unlock(&softc->ctl_lock);
12230 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12231 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12232 	mtx_unlock(&lun->lun_lock);
12233 	if (ua != CTL_UA_NONE)
12234 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12235 	else
12236 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12237 	return (0);
12238 }
12239 
12240 static void
12241 ctl_run_task(union ctl_io *io)
12242 {
12243 	int retval = 1;
12244 
12245 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12246 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12247 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12248 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12249 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12250 	switch (io->taskio.task_action) {
12251 	case CTL_TASK_ABORT_TASK:
12252 		retval = ctl_abort_task(io);
12253 		break;
12254 	case CTL_TASK_ABORT_TASK_SET:
12255 	case CTL_TASK_CLEAR_TASK_SET:
12256 		retval = ctl_abort_task_set(io);
12257 		break;
12258 	case CTL_TASK_CLEAR_ACA:
12259 		break;
12260 	case CTL_TASK_I_T_NEXUS_RESET:
12261 		retval = ctl_i_t_nexus_reset(io);
12262 		break;
12263 	case CTL_TASK_LUN_RESET:
12264 		retval = ctl_lun_reset(io);
12265 		break;
12266 	case CTL_TASK_TARGET_RESET:
12267 	case CTL_TASK_BUS_RESET:
12268 		retval = ctl_target_reset(io);
12269 		break;
12270 	case CTL_TASK_PORT_LOGIN:
12271 		break;
12272 	case CTL_TASK_PORT_LOGOUT:
12273 		break;
12274 	case CTL_TASK_QUERY_TASK:
12275 		retval = ctl_query_task(io, 0);
12276 		break;
12277 	case CTL_TASK_QUERY_TASK_SET:
12278 		retval = ctl_query_task(io, 1);
12279 		break;
12280 	case CTL_TASK_QUERY_ASYNC_EVENT:
12281 		retval = ctl_query_async_event(io);
12282 		break;
12283 	default:
12284 		printf("%s: got unknown task management event %d\n",
12285 		       __func__, io->taskio.task_action);
12286 		break;
12287 	}
12288 	if (retval == 0)
12289 		io->io_hdr.status = CTL_SUCCESS;
12290 	else
12291 		io->io_hdr.status = CTL_ERROR;
12292 	ctl_done(io);
12293 }
12294 
12295 /*
12296  * For HA operation.  Handle commands that come in from the other
12297  * controller.
12298  */
12299 static void
12300 ctl_handle_isc(union ctl_io *io)
12301 {
12302 	struct ctl_softc *softc = CTL_SOFTC(io);
12303 	struct ctl_lun *lun;
12304 	const struct ctl_cmd_entry *entry;
12305 	uint32_t targ_lun;
12306 
12307 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12308 	switch (io->io_hdr.msg_type) {
12309 	case CTL_MSG_SERIALIZE:
12310 		ctl_serialize_other_sc_cmd(&io->scsiio);
12311 		break;
12312 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12313 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12314 		if (targ_lun >= ctl_max_luns ||
12315 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12316 			ctl_done(io);
12317 			break;
12318 		}
12319 		mtx_lock(&lun->lun_lock);
12320 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12321 			mtx_unlock(&lun->lun_lock);
12322 			ctl_done(io);
12323 			break;
12324 		}
12325 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12326 		mtx_unlock(&lun->lun_lock);
12327 		ctl_enqueue_rtr(io);
12328 		break;
12329 	case CTL_MSG_FINISH_IO:
12330 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12331 			ctl_done(io);
12332 			break;
12333 		}
12334 		if (targ_lun >= ctl_max_luns ||
12335 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12336 			ctl_free_io(io);
12337 			break;
12338 		}
12339 		mtx_lock(&lun->lun_lock);
12340 		ctl_try_unblock_others(lun, io, TRUE);
12341 		LIST_REMOVE(&io->io_hdr, ooa_links);
12342 		mtx_unlock(&lun->lun_lock);
12343 		ctl_free_io(io);
12344 		break;
12345 	case CTL_MSG_PERS_ACTION:
12346 		ctl_hndl_per_res_out_on_other_sc(io);
12347 		ctl_free_io(io);
12348 		break;
12349 	case CTL_MSG_BAD_JUJU:
12350 		ctl_done(io);
12351 		break;
12352 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12353 		ctl_datamove_remote(io);
12354 		break;
12355 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12356 		ctl_datamove_done(io, false);
12357 		break;
12358 	case CTL_MSG_FAILOVER:
12359 		ctl_failover_lun(io);
12360 		ctl_free_io(io);
12361 		break;
12362 	default:
12363 		printf("%s: Invalid message type %d\n",
12364 		       __func__, io->io_hdr.msg_type);
12365 		ctl_free_io(io);
12366 		break;
12367 	}
12368 
12369 }
12370 
12371 /*
12372  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12373  * there is no match.
12374  */
12375 static ctl_lun_error_pattern
12376 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12377 {
12378 	const struct ctl_cmd_entry *entry;
12379 	ctl_lun_error_pattern filtered_pattern, pattern;
12380 
12381 	pattern = desc->error_pattern;
12382 
12383 	/*
12384 	 * XXX KDM we need more data passed into this function to match a
12385 	 * custom pattern, and we actually need to implement custom pattern
12386 	 * matching.
12387 	 */
12388 	if (pattern & CTL_LUN_PAT_CMD)
12389 		return (CTL_LUN_PAT_CMD);
12390 
12391 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12392 		return (CTL_LUN_PAT_ANY);
12393 
12394 	entry = ctl_get_cmd_entry(ctsio, NULL);
12395 
12396 	filtered_pattern = entry->pattern & pattern;
12397 
12398 	/*
12399 	 * If the user requested specific flags in the pattern (e.g.
12400 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12401 	 * flags.
12402 	 *
12403 	 * If the user did not specify any flags, it doesn't matter whether
12404 	 * or not the command supports the flags.
12405 	 */
12406 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12407 	     (pattern & ~CTL_LUN_PAT_MASK))
12408 		return (CTL_LUN_PAT_NONE);
12409 
12410 	/*
12411 	 * If the user asked for a range check, see if the requested LBA
12412 	 * range overlaps with this command's LBA range.
12413 	 */
12414 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12415 		uint64_t lba1;
12416 		uint64_t len1;
12417 		ctl_action action;
12418 		int retval;
12419 
12420 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12421 		if (retval != 0)
12422 			return (CTL_LUN_PAT_NONE);
12423 
12424 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12425 					      desc->lba_range.len, FALSE);
12426 		/*
12427 		 * A "pass" means that the LBA ranges don't overlap, so
12428 		 * this doesn't match the user's range criteria.
12429 		 */
12430 		if (action == CTL_ACTION_PASS)
12431 			return (CTL_LUN_PAT_NONE);
12432 	}
12433 
12434 	return (filtered_pattern);
12435 }
12436 
12437 static void
12438 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12439 {
12440 	struct ctl_error_desc *desc, *desc2;
12441 
12442 	mtx_assert(&lun->lun_lock, MA_OWNED);
12443 
12444 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12445 		ctl_lun_error_pattern pattern;
12446 		/*
12447 		 * Check to see whether this particular command matches
12448 		 * the pattern in the descriptor.
12449 		 */
12450 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12451 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12452 			continue;
12453 
12454 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12455 		case CTL_LUN_INJ_ABORTED:
12456 			ctl_set_aborted(&io->scsiio);
12457 			break;
12458 		case CTL_LUN_INJ_MEDIUM_ERR:
12459 			ctl_set_medium_error(&io->scsiio,
12460 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12461 			     CTL_FLAG_DATA_OUT);
12462 			break;
12463 		case CTL_LUN_INJ_UA:
12464 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12465 			 * OCCURRED */
12466 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12467 			break;
12468 		case CTL_LUN_INJ_CUSTOM:
12469 			/*
12470 			 * We're assuming the user knows what he is doing.
12471 			 * Just copy the sense information without doing
12472 			 * checks.
12473 			 */
12474 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12475 			      MIN(sizeof(desc->custom_sense),
12476 				  sizeof(io->scsiio.sense_data)));
12477 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12478 			io->scsiio.sense_len = SSD_FULL_SIZE;
12479 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12480 			break;
12481 		case CTL_LUN_INJ_NONE:
12482 		default:
12483 			/*
12484 			 * If this is an error injection type we don't know
12485 			 * about, clear the continuous flag (if it is set)
12486 			 * so it will get deleted below.
12487 			 */
12488 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12489 			break;
12490 		}
12491 		/*
12492 		 * By default, each error injection action is a one-shot
12493 		 */
12494 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12495 			continue;
12496 
12497 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12498 
12499 		free(desc, M_CTL);
12500 	}
12501 }
12502 
12503 #ifdef CTL_IO_DELAY
12504 static void
12505 ctl_datamove_timer_wakeup(void *arg)
12506 {
12507 	union ctl_io *io;
12508 
12509 	io = (union ctl_io *)arg;
12510 
12511 	ctl_datamove(io);
12512 }
12513 #endif /* CTL_IO_DELAY */
12514 
12515 static void
12516 ctl_datamove_done_process(union ctl_io *io)
12517 {
12518 #ifdef CTL_TIME_IO
12519 	struct bintime cur_bt;
12520 #endif
12521 
12522 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
12523 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
12524 
12525 #ifdef CTL_TIME_IO
12526 	getbinuptime(&cur_bt);
12527 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12528 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12529 #endif
12530 	io->io_hdr.num_dmas++;
12531 
12532 	if ((io->io_hdr.port_status != 0) &&
12533 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
12534 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
12535 		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
12536 		    /*retry_count*/ io->io_hdr.port_status);
12537 	} else if (io->scsiio.kern_data_resid != 0 &&
12538 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
12539 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
12540 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
12541 		ctl_set_invalid_field_ciu(&io->scsiio);
12542 	} else if (ctl_debug & CTL_DEBUG_CDB_DATA)
12543 		ctl_data_print(io);
12544 }
12545 
12546 void
12547 ctl_datamove_done(union ctl_io *io, bool samethr)
12548 {
12549 
12550 	ctl_datamove_done_process(io);
12551 	io->scsiio.be_move_done(io, samethr);
12552 }
12553 
12554 void
12555 ctl_datamove(union ctl_io *io)
12556 {
12557 	void (*fe_datamove)(union ctl_io *io);
12558 
12559 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12560 
12561 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12562 
12563 	/* No data transferred yet.  Frontend must update this when done. */
12564 	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12565 
12566 #ifdef CTL_TIME_IO
12567 	getbinuptime(&io->io_hdr.dma_start_bt);
12568 #endif /* CTL_TIME_IO */
12569 
12570 #ifdef CTL_IO_DELAY
12571 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12572 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12573 	} else {
12574 		struct ctl_lun *lun;
12575 
12576 		lun = CTL_LUN(io);
12577 		if ((lun != NULL)
12578 		 && (lun->delay_info.datamove_delay > 0)) {
12579 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12580 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12581 			callout_reset(&io->io_hdr.delay_callout,
12582 				      lun->delay_info.datamove_delay * hz,
12583 				      ctl_datamove_timer_wakeup, io);
12584 			if (lun->delay_info.datamove_type ==
12585 			    CTL_DELAY_TYPE_ONESHOT)
12586 				lun->delay_info.datamove_delay = 0;
12587 			return;
12588 		}
12589 	}
12590 #endif
12591 
12592 	/*
12593 	 * This command has been aborted.  Set the port status, so we fail
12594 	 * the data move.
12595 	 */
12596 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12597 		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12598 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12599 		       io->io_hdr.nexus.targ_port,
12600 		       io->io_hdr.nexus.targ_lun);
12601 		io->io_hdr.port_status = 31337;
12602 		ctl_datamove_done_process(io);
12603 		io->scsiio.be_move_done(io, true);
12604 		return;
12605 	}
12606 
12607 	/* Don't confuse frontend with zero length data move. */
12608 	if (io->scsiio.kern_data_len == 0) {
12609 		ctl_datamove_done_process(io);
12610 		io->scsiio.be_move_done(io, true);
12611 		return;
12612 	}
12613 
12614 	fe_datamove = CTL_PORT(io)->fe_datamove;
12615 	fe_datamove(io);
12616 }
12617 
12618 static void
12619 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12620 {
12621 	union ctl_ha_msg msg;
12622 #ifdef CTL_TIME_IO
12623 	struct bintime cur_bt;
12624 #endif
12625 
12626 	memset(&msg, 0, sizeof(msg));
12627 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12628 	msg.hdr.original_sc = io;
12629 	msg.hdr.serializing_sc = io->io_hdr.remote_io;
12630 	msg.hdr.nexus = io->io_hdr.nexus;
12631 	msg.hdr.status = io->io_hdr.status;
12632 	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12633 	msg.scsi.tag_num = io->scsiio.tag_num;
12634 	msg.scsi.tag_type = io->scsiio.tag_type;
12635 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12636 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12637 	       io->scsiio.sense_len);
12638 	msg.scsi.sense_len = io->scsiio.sense_len;
12639 	msg.scsi.port_status = io->io_hdr.port_status;
12640 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12641 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12642 		ctl_failover_io(io, /*have_lock*/ have_lock);
12643 		return;
12644 	}
12645 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12646 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12647 	    msg.scsi.sense_len, M_WAITOK);
12648 
12649 #ifdef CTL_TIME_IO
12650 	getbinuptime(&cur_bt);
12651 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12652 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12653 #endif
12654 	io->io_hdr.num_dmas++;
12655 }
12656 
12657 /*
12658  * The DMA to the remote side is done, now we need to tell the other side
12659  * we're done so it can continue with its data movement.
12660  */
12661 static void
12662 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12663 {
12664 	union ctl_io *io;
12665 	uint32_t i;
12666 
12667 	io = rq->context;
12668 
12669 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12670 		printf("%s: ISC DMA write failed with error %d", __func__,
12671 		       rq->ret);
12672 		ctl_set_internal_failure(&io->scsiio,
12673 					 /*sks_valid*/ 1,
12674 					 /*retry_count*/ rq->ret);
12675 	}
12676 
12677 	ctl_dt_req_free(rq);
12678 
12679 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12680 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12681 	free(CTL_RSGL(io), M_CTL);
12682 	CTL_RSGL(io) = NULL;
12683 	CTL_LSGL(io) = NULL;
12684 
12685 	/*
12686 	 * The data is in local and remote memory, so now we need to send
12687 	 * status (good or back) back to the other side.
12688 	 */
12689 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12690 }
12691 
12692 /*
12693  * We've moved the data from the host/controller into local memory.  Now we
12694  * need to push it over to the remote controller's memory.
12695  */
12696 static int
12697 ctl_datamove_remote_dm_write_cb(union ctl_io *io, bool samethr)
12698 {
12699 	int retval;
12700 
12701 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12702 					  ctl_datamove_remote_write_cb);
12703 	return (retval);
12704 }
12705 
12706 static void
12707 ctl_datamove_remote_write(union ctl_io *io)
12708 {
12709 	int retval;
12710 	void (*fe_datamove)(union ctl_io *io);
12711 
12712 	/*
12713 	 * - Get the data from the host/HBA into local memory.
12714 	 * - DMA memory from the local controller to the remote controller.
12715 	 * - Send status back to the remote controller.
12716 	 */
12717 
12718 	retval = ctl_datamove_remote_sgl_setup(io);
12719 	if (retval != 0)
12720 		return;
12721 
12722 	/* Switch the pointer over so the FETD knows what to do */
12723 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12724 
12725 	/*
12726 	 * Use a custom move done callback, since we need to send completion
12727 	 * back to the other controller, not to the backend on this side.
12728 	 */
12729 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12730 
12731 	fe_datamove = CTL_PORT(io)->fe_datamove;
12732 	fe_datamove(io);
12733 }
12734 
12735 static int
12736 ctl_datamove_remote_dm_read_cb(union ctl_io *io, bool samethr)
12737 {
12738 	uint32_t i;
12739 
12740 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12741 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12742 	free(CTL_RSGL(io), M_CTL);
12743 	CTL_RSGL(io) = NULL;
12744 	CTL_LSGL(io) = NULL;
12745 
12746 	/*
12747 	 * The read is done, now we need to send status (good or bad) back
12748 	 * to the other side.
12749 	 */
12750 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12751 
12752 	return (0);
12753 }
12754 
12755 static void
12756 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12757 {
12758 	union ctl_io *io;
12759 	void (*fe_datamove)(union ctl_io *io);
12760 
12761 	io = rq->context;
12762 
12763 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12764 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12765 		       rq->ret);
12766 		ctl_set_internal_failure(&io->scsiio,
12767 					 /*sks_valid*/ 1,
12768 					 /*retry_count*/ rq->ret);
12769 	}
12770 
12771 	ctl_dt_req_free(rq);
12772 
12773 	/* Switch the pointer over so the FETD knows what to do */
12774 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12775 
12776 	/*
12777 	 * Use a custom move done callback, since we need to send completion
12778 	 * back to the other controller, not to the backend on this side.
12779 	 */
12780 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12781 
12782 	/* XXX KDM add checks like the ones in ctl_datamove? */
12783 
12784 	fe_datamove = CTL_PORT(io)->fe_datamove;
12785 	fe_datamove(io);
12786 }
12787 
12788 static int
12789 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12790 {
12791 	struct ctl_sg_entry *local_sglist;
12792 	uint32_t len_to_go;
12793 	int retval;
12794 	int i;
12795 
12796 	retval = 0;
12797 	local_sglist = CTL_LSGL(io);
12798 	len_to_go = io->scsiio.kern_data_len;
12799 
12800 	/*
12801 	 * The difficult thing here is that the size of the various
12802 	 * S/G segments may be different than the size from the
12803 	 * remote controller.  That'll make it harder when DMAing
12804 	 * the data back to the other side.
12805 	 */
12806 	for (i = 0; len_to_go > 0; i++) {
12807 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12808 		local_sglist[i].addr =
12809 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12810 
12811 		len_to_go -= local_sglist[i].len;
12812 	}
12813 	/*
12814 	 * Reset the number of S/G entries accordingly.  The original
12815 	 * number of S/G entries is available in rem_sg_entries.
12816 	 */
12817 	io->scsiio.kern_sg_entries = i;
12818 
12819 	return (retval);
12820 }
12821 
12822 static int
12823 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12824 			 ctl_ha_dt_cb callback)
12825 {
12826 	struct ctl_ha_dt_req *rq;
12827 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12828 	uint32_t local_used, remote_used, total_used;
12829 	int i, j, isc_ret;
12830 
12831 	rq = ctl_dt_req_alloc();
12832 
12833 	/*
12834 	 * If we failed to allocate the request, and if the DMA didn't fail
12835 	 * anyway, set busy status.  This is just a resource allocation
12836 	 * failure.
12837 	 */
12838 	if ((rq == NULL)
12839 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12840 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12841 		ctl_set_busy(&io->scsiio);
12842 
12843 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12844 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12845 		if (rq != NULL)
12846 			ctl_dt_req_free(rq);
12847 
12848 		/*
12849 		 * The data move failed.  We need to return status back
12850 		 * to the other controller.  No point in trying to DMA
12851 		 * data to the remote controller.
12852 		 */
12853 
12854 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12855 
12856 		return (1);
12857 	}
12858 
12859 	local_sglist = CTL_LSGL(io);
12860 	remote_sglist = CTL_RSGL(io);
12861 	local_used = 0;
12862 	remote_used = 0;
12863 	total_used = 0;
12864 
12865 	/*
12866 	 * Pull/push the data over the wire from/to the other controller.
12867 	 * This takes into account the possibility that the local and
12868 	 * remote sglists may not be identical in terms of the size of
12869 	 * the elements and the number of elements.
12870 	 *
12871 	 * One fundamental assumption here is that the length allocated for
12872 	 * both the local and remote sglists is identical.  Otherwise, we've
12873 	 * essentially got a coding error of some sort.
12874 	 */
12875 	isc_ret = CTL_HA_STATUS_SUCCESS;
12876 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12877 		uint32_t cur_len;
12878 		uint8_t *tmp_ptr;
12879 
12880 		rq->command = command;
12881 		rq->context = io;
12882 
12883 		/*
12884 		 * Both pointers should be aligned.  But it is possible
12885 		 * that the allocation length is not.  They should both
12886 		 * also have enough slack left over at the end, though,
12887 		 * to round up to the next 8 byte boundary.
12888 		 */
12889 		cur_len = MIN(local_sglist[i].len - local_used,
12890 			      remote_sglist[j].len - remote_used);
12891 		rq->size = cur_len;
12892 
12893 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12894 		tmp_ptr += local_used;
12895 
12896 #if 0
12897 		/* Use physical addresses when talking to ISC hardware */
12898 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12899 			/* XXX KDM use busdma */
12900 			rq->local = vtophys(tmp_ptr);
12901 		} else
12902 			rq->local = tmp_ptr;
12903 #else
12904 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12905 		    ("HA does not support BUS_ADDR"));
12906 		rq->local = tmp_ptr;
12907 #endif
12908 
12909 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12910 		tmp_ptr += remote_used;
12911 		rq->remote = tmp_ptr;
12912 
12913 		rq->callback = NULL;
12914 
12915 		local_used += cur_len;
12916 		if (local_used >= local_sglist[i].len) {
12917 			i++;
12918 			local_used = 0;
12919 		}
12920 
12921 		remote_used += cur_len;
12922 		if (remote_used >= remote_sglist[j].len) {
12923 			j++;
12924 			remote_used = 0;
12925 		}
12926 		total_used += cur_len;
12927 
12928 		if (total_used >= io->scsiio.kern_data_len)
12929 			rq->callback = callback;
12930 
12931 		isc_ret = ctl_dt_single(rq);
12932 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12933 			break;
12934 	}
12935 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12936 		rq->ret = isc_ret;
12937 		callback(rq);
12938 	}
12939 
12940 	return (0);
12941 }
12942 
12943 static void
12944 ctl_datamove_remote_read(union ctl_io *io)
12945 {
12946 	int retval;
12947 	uint32_t i;
12948 
12949 	/*
12950 	 * This will send an error to the other controller in the case of a
12951 	 * failure.
12952 	 */
12953 	retval = ctl_datamove_remote_sgl_setup(io);
12954 	if (retval != 0)
12955 		return;
12956 
12957 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12958 					  ctl_datamove_remote_read_cb);
12959 	if (retval != 0) {
12960 		/*
12961 		 * Make sure we free memory if there was an error..  The
12962 		 * ctl_datamove_remote_xfer() function will send the
12963 		 * datamove done message, or call the callback with an
12964 		 * error if there is a problem.
12965 		 */
12966 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12967 			free(CTL_LSGLT(io)[i].addr, M_CTL);
12968 		free(CTL_RSGL(io), M_CTL);
12969 		CTL_RSGL(io) = NULL;
12970 		CTL_LSGL(io) = NULL;
12971 	}
12972 }
12973 
12974 /*
12975  * Process a datamove request from the other controller.  This is used for
12976  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12977  * first.  Once that is complete, the data gets DMAed into the remote
12978  * controller's memory.  For reads, we DMA from the remote controller's
12979  * memory into our memory first, and then move it out to the FETD.
12980  */
12981 static void
12982 ctl_datamove_remote(union ctl_io *io)
12983 {
12984 
12985 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12986 
12987 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12988 		ctl_failover_io(io, /*have_lock*/ 0);
12989 		return;
12990 	}
12991 
12992 	/*
12993 	 * Note that we look for an aborted I/O here, but don't do some of
12994 	 * the other checks that ctl_datamove() normally does.
12995 	 * We don't need to run the datamove delay code, since that should
12996 	 * have been done if need be on the other controller.
12997 	 */
12998 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12999 		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13000 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13001 		       io->io_hdr.nexus.targ_port,
13002 		       io->io_hdr.nexus.targ_lun);
13003 		io->io_hdr.port_status = 31338;
13004 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13005 		return;
13006 	}
13007 
13008 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13009 		ctl_datamove_remote_write(io);
13010 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13011 		ctl_datamove_remote_read(io);
13012 	else {
13013 		io->io_hdr.port_status = 31339;
13014 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13015 	}
13016 }
13017 
13018 static void
13019 ctl_process_done(union ctl_io *io)
13020 {
13021 	struct ctl_softc *softc = CTL_SOFTC(io);
13022 	struct ctl_port *port = CTL_PORT(io);
13023 	struct ctl_lun *lun = CTL_LUN(io);
13024 	void (*fe_done)(union ctl_io *io);
13025 	union ctl_ha_msg msg;
13026 
13027 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13028 	fe_done = port->fe_done;
13029 
13030 #ifdef CTL_TIME_IO
13031 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13032 		char str[256];
13033 		char path_str[64];
13034 		struct sbuf sb;
13035 
13036 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13037 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13038 
13039 		sbuf_cat(&sb, path_str);
13040 		switch (io->io_hdr.io_type) {
13041 		case CTL_IO_SCSI:
13042 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13043 			sbuf_printf(&sb, "\n");
13044 			sbuf_cat(&sb, path_str);
13045 			sbuf_printf(&sb, "Tag: 0x%04x/%d, Prio: %d\n",
13046 				    io->scsiio.tag_num, io->scsiio.tag_type,
13047 				    io->scsiio.priority);
13048 			break;
13049 		case CTL_IO_TASK:
13050 			sbuf_printf(&sb, "Task Action: %d Tag: 0x%04x/%d\n",
13051 				    io->taskio.task_action,
13052 				    io->taskio.tag_num, io->taskio.tag_type);
13053 			break;
13054 		default:
13055 			panic("%s: Invalid CTL I/O type %d\n",
13056 			    __func__, io->io_hdr.io_type);
13057 		}
13058 		sbuf_cat(&sb, path_str);
13059 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13060 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13061 		sbuf_finish(&sb);
13062 		printf("%s", sbuf_data(&sb));
13063 	}
13064 #endif /* CTL_TIME_IO */
13065 
13066 	switch (io->io_hdr.io_type) {
13067 	case CTL_IO_SCSI:
13068 		break;
13069 	case CTL_IO_TASK:
13070 		if (ctl_debug & CTL_DEBUG_INFO)
13071 			ctl_io_error_print(io, NULL);
13072 		fe_done(io);
13073 		return;
13074 	default:
13075 		panic("%s: Invalid CTL I/O type %d\n",
13076 		    __func__, io->io_hdr.io_type);
13077 	}
13078 
13079 	if (lun == NULL) {
13080 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13081 				 io->io_hdr.nexus.targ_mapped_lun));
13082 		goto bailout;
13083 	}
13084 
13085 	mtx_lock(&lun->lun_lock);
13086 
13087 	/*
13088 	 * Check to see if we have any informational exception and status
13089 	 * of this command can be modified to report it in form of either
13090 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13091 	 */
13092 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13093 	    io->io_hdr.status == CTL_SUCCESS &&
13094 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13095 		uint8_t mrie = lun->MODE_IE.mrie;
13096 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13097 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13098 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13099 		     mrie == SIEP_MRIE_REC_UNCOND ||
13100 		     mrie == SIEP_MRIE_NO_SENSE) &&
13101 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13102 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13103 			ctl_set_sense(&io->scsiio,
13104 			      /*current_error*/ 1,
13105 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13106 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13107 			      /*asc*/ lun->ie_asc,
13108 			      /*ascq*/ lun->ie_ascq,
13109 			      SSD_ELEM_NONE);
13110 			lun->ie_reported = 1;
13111 		}
13112 	} else if (lun->ie_reported < 0)
13113 		lun->ie_reported = 0;
13114 
13115 	/*
13116 	 * Check to see if we have any errors to inject here.  We only
13117 	 * inject errors for commands that don't already have errors set.
13118 	 */
13119 	if (!STAILQ_EMPTY(&lun->error_list) &&
13120 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13121 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13122 		ctl_inject_error(lun, io);
13123 
13124 	/*
13125 	 * XXX KDM how do we treat commands that aren't completed
13126 	 * successfully?
13127 	 *
13128 	 * XXX KDM should we also track I/O latency?
13129 	 */
13130 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13131 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13132 		int type;
13133 #ifdef CTL_TIME_IO
13134 		struct bintime bt;
13135 
13136 		getbinuptime(&bt);
13137 		bintime_sub(&bt, &io->io_hdr.start_bt);
13138 #endif
13139 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13140 		    CTL_FLAG_DATA_IN)
13141 			type = CTL_STATS_READ;
13142 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13143 		    CTL_FLAG_DATA_OUT)
13144 			type = CTL_STATS_WRITE;
13145 		else
13146 			type = CTL_STATS_NO_IO;
13147 
13148 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
13149 		lun->stats.operations[type] ++;
13150 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13151 #ifdef CTL_TIME_IO
13152 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13153 		bintime_add(&lun->stats.time[type], &bt);
13154 #endif
13155 
13156 		mtx_lock(&port->port_lock);
13157 		port->stats.bytes[type] += io->scsiio.kern_total_len;
13158 		port->stats.operations[type] ++;
13159 		port->stats.dmas[type] += io->io_hdr.num_dmas;
13160 #ifdef CTL_TIME_IO
13161 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13162 		bintime_add(&port->stats.time[type], &bt);
13163 #endif
13164 		mtx_unlock(&port->port_lock);
13165 	}
13166 
13167 	/*
13168 	 * Run through the blocked queue of this I/O and see if anything
13169 	 * can be unblocked, now that this I/O is done and will be removed.
13170 	 * We need to do it before removal to have OOA position to start.
13171 	 */
13172 	ctl_try_unblock_others(lun, io, TRUE);
13173 
13174 	/*
13175 	 * Remove this from the OOA queue.
13176 	 */
13177 	LIST_REMOVE(&io->io_hdr, ooa_links);
13178 #ifdef CTL_TIME_IO
13179 	if (LIST_EMPTY(&lun->ooa_queue))
13180 		lun->last_busy = getsbinuptime();
13181 #endif
13182 
13183 	/*
13184 	 * If the LUN has been invalidated, free it if there is nothing
13185 	 * left on its OOA queue.
13186 	 */
13187 	if ((lun->flags & CTL_LUN_INVALID)
13188 	 && LIST_EMPTY(&lun->ooa_queue)) {
13189 		mtx_unlock(&lun->lun_lock);
13190 		ctl_free_lun(lun);
13191 	} else
13192 		mtx_unlock(&lun->lun_lock);
13193 
13194 bailout:
13195 
13196 	/*
13197 	 * If this command has been aborted, make sure we set the status
13198 	 * properly.  The FETD is responsible for freeing the I/O and doing
13199 	 * whatever it needs to do to clean up its state.
13200 	 */
13201 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13202 		ctl_set_task_aborted(&io->scsiio);
13203 
13204 	/*
13205 	 * If enabled, print command error status.
13206 	 */
13207 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13208 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13209 		ctl_io_error_print(io, NULL);
13210 
13211 	/*
13212 	 * Tell the FETD or the other shelf controller we're done with this
13213 	 * command.  Note that only SCSI commands get to this point.  Task
13214 	 * management commands are completed above.
13215 	 */
13216 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13217 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13218 		memset(&msg, 0, sizeof(msg));
13219 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13220 		msg.hdr.serializing_sc = io->io_hdr.remote_io;
13221 		msg.hdr.nexus = io->io_hdr.nexus;
13222 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13223 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13224 		    M_WAITOK);
13225 	}
13226 
13227 	fe_done(io);
13228 }
13229 
13230 /*
13231  * Front end should call this if it doesn't do autosense.  When the request
13232  * sense comes back in from the initiator, we'll dequeue this and send it.
13233  */
13234 int
13235 ctl_queue_sense(union ctl_io *io)
13236 {
13237 	struct ctl_softc *softc = CTL_SOFTC(io);
13238 	struct ctl_port *port = CTL_PORT(io);
13239 	struct ctl_lun *lun;
13240 	struct scsi_sense_data *ps;
13241 	uint32_t initidx, p, targ_lun;
13242 
13243 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13244 
13245 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13246 
13247 	/*
13248 	 * LUN lookup will likely move to the ctl_work_thread() once we
13249 	 * have our new queueing infrastructure (that doesn't put things on
13250 	 * a per-LUN queue initially).  That is so that we can handle
13251 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13252 	 * can't deal with that right now.
13253 	 * If we don't have a LUN for this, just toss the sense information.
13254 	 */
13255 	mtx_lock(&softc->ctl_lock);
13256 	if (targ_lun >= ctl_max_luns ||
13257 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13258 		mtx_unlock(&softc->ctl_lock);
13259 		goto bailout;
13260 	}
13261 	mtx_lock(&lun->lun_lock);
13262 	mtx_unlock(&softc->ctl_lock);
13263 
13264 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13265 	p = initidx / CTL_MAX_INIT_PER_PORT;
13266 	if (lun->pending_sense[p] == NULL) {
13267 		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13268 		    M_CTL, M_NOWAIT | M_ZERO);
13269 	}
13270 	if ((ps = lun->pending_sense[p]) != NULL) {
13271 		ps += initidx % CTL_MAX_INIT_PER_PORT;
13272 		memset(ps, 0, sizeof(*ps));
13273 		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13274 	}
13275 	mtx_unlock(&lun->lun_lock);
13276 
13277 bailout:
13278 	ctl_free_io(io);
13279 	return (CTL_RETVAL_COMPLETE);
13280 }
13281 
13282 /*
13283  * Primary command inlet from frontend ports.  All SCSI and task I/O
13284  * requests must go through this function.
13285  */
13286 int
13287 ctl_queue(union ctl_io *io)
13288 {
13289 	struct ctl_port *port = CTL_PORT(io);
13290 
13291 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13292 
13293 #ifdef CTL_TIME_IO
13294 	io->io_hdr.start_time = time_uptime;
13295 	getbinuptime(&io->io_hdr.start_bt);
13296 #endif /* CTL_TIME_IO */
13297 
13298 	/* Map FE-specific LUN ID into global one. */
13299 	io->io_hdr.nexus.targ_mapped_lun =
13300 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13301 
13302 	switch (io->io_hdr.io_type) {
13303 	case CTL_IO_SCSI:
13304 	case CTL_IO_TASK:
13305 		if (ctl_debug & CTL_DEBUG_CDB)
13306 			ctl_io_print(io);
13307 		ctl_enqueue_incoming(io);
13308 		break;
13309 	default:
13310 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13311 		return (EINVAL);
13312 	}
13313 
13314 	return (CTL_RETVAL_COMPLETE);
13315 }
13316 
13317 int
13318 ctl_run(union ctl_io *io)
13319 {
13320 	struct ctl_port *port = CTL_PORT(io);
13321 
13322 	CTL_DEBUG_PRINT(("ctl_run cdb[0]=%02X\n", io->scsiio.cdb[0]));
13323 
13324 #ifdef CTL_TIME_IO
13325 	io->io_hdr.start_time = time_uptime;
13326 	getbinuptime(&io->io_hdr.start_bt);
13327 #endif /* CTL_TIME_IO */
13328 
13329 	/* Map FE-specific LUN ID into global one. */
13330 	io->io_hdr.nexus.targ_mapped_lun =
13331 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13332 
13333 	switch (io->io_hdr.io_type) {
13334 	case CTL_IO_SCSI:
13335 		if (ctl_debug & CTL_DEBUG_CDB)
13336 			ctl_io_print(io);
13337 		ctl_scsiio_precheck(&io->scsiio);
13338 		break;
13339 	case CTL_IO_TASK:
13340 		if (ctl_debug & CTL_DEBUG_CDB)
13341 			ctl_io_print(io);
13342 		ctl_run_task(io);
13343 		break;
13344 	default:
13345 		printf("ctl_run: unknown I/O type %d\n", io->io_hdr.io_type);
13346 		return (EINVAL);
13347 	}
13348 
13349 	return (CTL_RETVAL_COMPLETE);
13350 }
13351 
13352 #ifdef CTL_IO_DELAY
13353 static void
13354 ctl_done_timer_wakeup(void *arg)
13355 {
13356 	union ctl_io *io;
13357 
13358 	io = (union ctl_io *)arg;
13359 	ctl_done(io);
13360 }
13361 #endif /* CTL_IO_DELAY */
13362 
13363 void
13364 ctl_serseq_done(union ctl_io *io)
13365 {
13366 	struct ctl_lun *lun = CTL_LUN(io);
13367 
13368 	/* This is racy, but should not be a problem. */
13369 	if (!TAILQ_EMPTY(&io->io_hdr.blocked_queue)) {
13370 		mtx_lock(&lun->lun_lock);
13371 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13372 		ctl_try_unblock_others(lun, io, FALSE);
13373 		mtx_unlock(&lun->lun_lock);
13374 	} else
13375 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13376 }
13377 
13378 void
13379 ctl_done(union ctl_io *io)
13380 {
13381 
13382 	/*
13383 	 * Enable this to catch duplicate completion issues.
13384 	 */
13385 #if 0
13386 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13387 		printf("%s: type %d msg %d cdb %x iptl: "
13388 		       "%u:%u:%u tag 0x%04x "
13389 		       "flag %#x status %x\n",
13390 			__func__,
13391 			io->io_hdr.io_type,
13392 			io->io_hdr.msg_type,
13393 			io->scsiio.cdb[0],
13394 			io->io_hdr.nexus.initid,
13395 			io->io_hdr.nexus.targ_port,
13396 			io->io_hdr.nexus.targ_lun,
13397 			(io->io_hdr.io_type ==
13398 			CTL_IO_TASK) ?
13399 			io->taskio.tag_num :
13400 			io->scsiio.tag_num,
13401 		        io->io_hdr.flags,
13402 			io->io_hdr.status);
13403 	} else
13404 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13405 #endif
13406 
13407 	/*
13408 	 * This is an internal copy of an I/O, and should not go through
13409 	 * the normal done processing logic.
13410 	 */
13411 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13412 		return;
13413 
13414 #ifdef CTL_IO_DELAY
13415 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13416 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13417 	} else {
13418 		struct ctl_lun *lun = CTL_LUN(io);
13419 
13420 		if ((lun != NULL)
13421 		 && (lun->delay_info.done_delay > 0)) {
13422 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13423 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13424 			callout_reset(&io->io_hdr.delay_callout,
13425 				      lun->delay_info.done_delay * hz,
13426 				      ctl_done_timer_wakeup, io);
13427 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13428 				lun->delay_info.done_delay = 0;
13429 			return;
13430 		}
13431 	}
13432 #endif /* CTL_IO_DELAY */
13433 
13434 	ctl_enqueue_done(io);
13435 }
13436 
13437 static void
13438 ctl_work_thread(void *arg)
13439 {
13440 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13441 	struct ctl_softc *softc = thr->ctl_softc;
13442 	union ctl_io *io;
13443 	int retval;
13444 
13445 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13446 	thread_lock(curthread);
13447 	sched_prio(curthread, PUSER - 1);
13448 	thread_unlock(curthread);
13449 
13450 	while (!softc->shutdown) {
13451 		/*
13452 		 * We handle the queues in this order:
13453 		 * - ISC
13454 		 * - done queue (to free up resources, unblock other commands)
13455 		 * - incoming queue
13456 		 * - RtR queue
13457 		 *
13458 		 * If those queues are empty, we break out of the loop and
13459 		 * go to sleep.
13460 		 */
13461 		mtx_lock(&thr->queue_lock);
13462 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13463 		if (io != NULL) {
13464 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13465 			mtx_unlock(&thr->queue_lock);
13466 			ctl_handle_isc(io);
13467 			continue;
13468 		}
13469 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13470 		if (io != NULL) {
13471 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13472 			/* clear any blocked commands, call fe_done */
13473 			mtx_unlock(&thr->queue_lock);
13474 			ctl_process_done(io);
13475 			continue;
13476 		}
13477 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13478 		if (io != NULL) {
13479 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13480 			mtx_unlock(&thr->queue_lock);
13481 			if (io->io_hdr.io_type == CTL_IO_TASK)
13482 				ctl_run_task(io);
13483 			else
13484 				ctl_scsiio_precheck(&io->scsiio);
13485 			continue;
13486 		}
13487 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13488 		if (io != NULL) {
13489 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13490 			mtx_unlock(&thr->queue_lock);
13491 			retval = ctl_scsiio(&io->scsiio);
13492 			if (retval != CTL_RETVAL_COMPLETE)
13493 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13494 			continue;
13495 		}
13496 
13497 		/* Sleep until we have something to do. */
13498 		mtx_sleep(thr, &thr->queue_lock, PDROP, "-", 0);
13499 	}
13500 	thr->thread = NULL;
13501 	kthread_exit();
13502 }
13503 
13504 static void
13505 ctl_thresh_thread(void *arg)
13506 {
13507 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13508 	struct ctl_lun *lun;
13509 	struct ctl_logical_block_provisioning_page *page;
13510 	const char *attr;
13511 	union ctl_ha_msg msg;
13512 	uint64_t thres, val;
13513 	int i, e, set;
13514 
13515 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13516 	thread_lock(curthread);
13517 	sched_prio(curthread, PUSER - 1);
13518 	thread_unlock(curthread);
13519 
13520 	while (!softc->shutdown) {
13521 		mtx_lock(&softc->ctl_lock);
13522 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13523 			if ((lun->flags & CTL_LUN_DISABLED) ||
13524 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13525 			    lun->backend->lun_attr == NULL)
13526 				continue;
13527 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13528 			    softc->ha_mode == CTL_HA_MODE_XFER)
13529 				continue;
13530 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13531 				continue;
13532 			e = 0;
13533 			page = &lun->MODE_LBP;
13534 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13535 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13536 					continue;
13537 				thres = scsi_4btoul(page->descr[i].count);
13538 				thres <<= CTL_LBP_EXPONENT;
13539 				switch (page->descr[i].resource) {
13540 				case 0x01:
13541 					attr = "blocksavail";
13542 					break;
13543 				case 0x02:
13544 					attr = "blocksused";
13545 					break;
13546 				case 0xf1:
13547 					attr = "poolblocksavail";
13548 					break;
13549 				case 0xf2:
13550 					attr = "poolblocksused";
13551 					break;
13552 				default:
13553 					continue;
13554 				}
13555 				mtx_unlock(&softc->ctl_lock); // XXX
13556 				val = lun->backend->lun_attr(lun->be_lun, attr);
13557 				mtx_lock(&softc->ctl_lock);
13558 				if (val == UINT64_MAX)
13559 					continue;
13560 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13561 				    == SLBPPD_ARMING_INC)
13562 					e = (val >= thres);
13563 				else
13564 					e = (val <= thres);
13565 				if (e)
13566 					break;
13567 			}
13568 			mtx_lock(&lun->lun_lock);
13569 			if (e) {
13570 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13571 				    (uint8_t *)page, lun->ua_tpt_info);
13572 				if (lun->lasttpt == 0 ||
13573 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13574 					lun->lasttpt = time_uptime;
13575 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13576 					set = 1;
13577 				} else
13578 					set = 0;
13579 			} else {
13580 				lun->lasttpt = 0;
13581 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13582 				set = -1;
13583 			}
13584 			mtx_unlock(&lun->lun_lock);
13585 			if (set != 0 &&
13586 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13587 				/* Send msg to other side. */
13588 				bzero(&msg.ua, sizeof(msg.ua));
13589 				msg.hdr.msg_type = CTL_MSG_UA;
13590 				msg.hdr.nexus.initid = -1;
13591 				msg.hdr.nexus.targ_port = -1;
13592 				msg.hdr.nexus.targ_lun = lun->lun;
13593 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13594 				msg.ua.ua_all = 1;
13595 				msg.ua.ua_set = (set > 0);
13596 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13597 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13598 				mtx_unlock(&softc->ctl_lock); // XXX
13599 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13600 				    sizeof(msg.ua), M_WAITOK);
13601 				mtx_lock(&softc->ctl_lock);
13602 			}
13603 		}
13604 		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13605 		    PDROP, "-", CTL_LBP_PERIOD * hz);
13606 	}
13607 	softc->thresh_thread = NULL;
13608 	kthread_exit();
13609 }
13610 
13611 static void
13612 ctl_enqueue_incoming(union ctl_io *io)
13613 {
13614 	struct ctl_softc *softc = CTL_SOFTC(io);
13615 	struct ctl_thread *thr;
13616 	u_int idx;
13617 
13618 	idx = (io->io_hdr.nexus.targ_port * 127 +
13619 	       io->io_hdr.nexus.initid) % worker_threads;
13620 	thr = &softc->threads[idx];
13621 	mtx_lock(&thr->queue_lock);
13622 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13623 	mtx_unlock(&thr->queue_lock);
13624 	wakeup(thr);
13625 }
13626 
13627 static void
13628 ctl_enqueue_rtr(union ctl_io *io)
13629 {
13630 	struct ctl_softc *softc = CTL_SOFTC(io);
13631 	struct ctl_thread *thr;
13632 
13633 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13634 	mtx_lock(&thr->queue_lock);
13635 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13636 	mtx_unlock(&thr->queue_lock);
13637 	wakeup(thr);
13638 }
13639 
13640 static void
13641 ctl_enqueue_done(union ctl_io *io)
13642 {
13643 	struct ctl_softc *softc = CTL_SOFTC(io);
13644 	struct ctl_thread *thr;
13645 
13646 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13647 	mtx_lock(&thr->queue_lock);
13648 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13649 	mtx_unlock(&thr->queue_lock);
13650 	wakeup(thr);
13651 }
13652 
13653 static void
13654 ctl_enqueue_isc(union ctl_io *io)
13655 {
13656 	struct ctl_softc *softc = CTL_SOFTC(io);
13657 	struct ctl_thread *thr;
13658 
13659 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13660 	mtx_lock(&thr->queue_lock);
13661 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13662 	mtx_unlock(&thr->queue_lock);
13663 	wakeup(thr);
13664 }
13665 
13666 /*
13667  *  vim: ts=8
13668  */
13669