xref: /freebsd/sys/cam/ctl/ctl.c (revision 3c4ba5f55438f7afd4f4b0b56f88f2bb505fd6a6)
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		1024
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 & 0xff);
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->tag_type = io->scsiio.tag_type;
2495 		entry->lun_num = lun->lun;
2496 #ifdef CTL_TIME_IO
2497 		entry->start_bt = io->io_hdr.start_bt;
2498 #endif
2499 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2500 		entry->cdb_len = io->scsiio.cdb_len;
2501 		if (io->io_hdr.blocker != NULL)
2502 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2503 
2504 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2505 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2506 
2507 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2508 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2509 
2510 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2511 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2512 
2513 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2514 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2515 
2516 		if (io->io_hdr.flags & CTL_FLAG_STATUS_QUEUED)
2517 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_QUEUED;
2518 
2519 		if (io->io_hdr.flags & CTL_FLAG_STATUS_SENT)
2520 			entry->cmd_flags |= CTL_OOACMD_FLAG_STATUS_SENT;
2521 		(*cur_fill_num)++;
2522 	}
2523 	mtx_unlock(&lun->lun_lock);
2524 }
2525 
2526 /*
2527  * Escape characters that are illegal or not recommended in XML.
2528  */
2529 int
2530 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2531 {
2532 	char *end = str + size;
2533 	int retval;
2534 
2535 	retval = 0;
2536 
2537 	for (; *str && str < end; str++) {
2538 		switch (*str) {
2539 		case '&':
2540 			retval = sbuf_printf(sb, "&amp;");
2541 			break;
2542 		case '>':
2543 			retval = sbuf_printf(sb, "&gt;");
2544 			break;
2545 		case '<':
2546 			retval = sbuf_printf(sb, "&lt;");
2547 			break;
2548 		default:
2549 			retval = sbuf_putc(sb, *str);
2550 			break;
2551 		}
2552 
2553 		if (retval != 0)
2554 			break;
2555 	}
2556 
2557 	return (retval);
2558 }
2559 
2560 static void
2561 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2562 {
2563 	struct scsi_vpd_id_descriptor *desc;
2564 	int i;
2565 
2566 	if (id == NULL || id->len < 4)
2567 		return;
2568 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2569 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2570 	case SVPD_ID_TYPE_T10:
2571 		sbuf_printf(sb, "t10.");
2572 		break;
2573 	case SVPD_ID_TYPE_EUI64:
2574 		sbuf_printf(sb, "eui.");
2575 		break;
2576 	case SVPD_ID_TYPE_NAA:
2577 		sbuf_printf(sb, "naa.");
2578 		break;
2579 	case SVPD_ID_TYPE_SCSI_NAME:
2580 		break;
2581 	}
2582 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2583 	case SVPD_ID_CODESET_BINARY:
2584 		for (i = 0; i < desc->length; i++)
2585 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2586 		break;
2587 	case SVPD_ID_CODESET_ASCII:
2588 		sbuf_printf(sb, "%.*s", (int)desc->length,
2589 		    (char *)desc->identifier);
2590 		break;
2591 	case SVPD_ID_CODESET_UTF8:
2592 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2593 		break;
2594 	}
2595 }
2596 
2597 static int
2598 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2599 	  struct thread *td)
2600 {
2601 	struct ctl_softc *softc = dev->si_drv1;
2602 	struct ctl_port *port;
2603 	struct ctl_lun *lun;
2604 	int retval;
2605 
2606 	retval = 0;
2607 
2608 	switch (cmd) {
2609 	case CTL_IO:
2610 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2611 		break;
2612 	case CTL_ENABLE_PORT:
2613 	case CTL_DISABLE_PORT:
2614 	case CTL_SET_PORT_WWNS: {
2615 		struct ctl_port *port;
2616 		struct ctl_port_entry *entry;
2617 
2618 		entry = (struct ctl_port_entry *)addr;
2619 
2620 		mtx_lock(&softc->ctl_lock);
2621 		STAILQ_FOREACH(port, &softc->port_list, links) {
2622 			int action, done;
2623 
2624 			if (port->targ_port < softc->port_min ||
2625 			    port->targ_port >= softc->port_max)
2626 				continue;
2627 
2628 			action = 0;
2629 			done = 0;
2630 			if ((entry->port_type == CTL_PORT_NONE)
2631 			 && (entry->targ_port == port->targ_port)) {
2632 				/*
2633 				 * If the user only wants to enable or
2634 				 * disable or set WWNs on a specific port,
2635 				 * do the operation and we're done.
2636 				 */
2637 				action = 1;
2638 				done = 1;
2639 			} else if (entry->port_type & port->port_type) {
2640 				/*
2641 				 * Compare the user's type mask with the
2642 				 * particular frontend type to see if we
2643 				 * have a match.
2644 				 */
2645 				action = 1;
2646 				done = 0;
2647 
2648 				/*
2649 				 * Make sure the user isn't trying to set
2650 				 * WWNs on multiple ports at the same time.
2651 				 */
2652 				if (cmd == CTL_SET_PORT_WWNS) {
2653 					printf("%s: Can't set WWNs on "
2654 					       "multiple ports\n", __func__);
2655 					retval = EINVAL;
2656 					break;
2657 				}
2658 			}
2659 			if (action == 0)
2660 				continue;
2661 
2662 			/*
2663 			 * XXX KDM we have to drop the lock here, because
2664 			 * the online/offline operations can potentially
2665 			 * block.  We need to reference count the frontends
2666 			 * so they can't go away,
2667 			 */
2668 			if (cmd == CTL_ENABLE_PORT) {
2669 				mtx_unlock(&softc->ctl_lock);
2670 				ctl_port_online(port);
2671 				mtx_lock(&softc->ctl_lock);
2672 			} else if (cmd == CTL_DISABLE_PORT) {
2673 				mtx_unlock(&softc->ctl_lock);
2674 				ctl_port_offline(port);
2675 				mtx_lock(&softc->ctl_lock);
2676 			} else if (cmd == CTL_SET_PORT_WWNS) {
2677 				ctl_port_set_wwns(port,
2678 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2679 				    1 : 0, entry->wwnn,
2680 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2681 				    1 : 0, entry->wwpn);
2682 			}
2683 			if (done != 0)
2684 				break;
2685 		}
2686 		mtx_unlock(&softc->ctl_lock);
2687 		break;
2688 	}
2689 	case CTL_GET_OOA: {
2690 		struct ctl_ooa *ooa_hdr;
2691 		struct ctl_ooa_entry *entries;
2692 		uint32_t cur_fill_num;
2693 
2694 		ooa_hdr = (struct ctl_ooa *)addr;
2695 
2696 		if ((ooa_hdr->alloc_len == 0)
2697 		 || (ooa_hdr->alloc_num == 0)) {
2698 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2699 			       "must be non-zero\n", __func__,
2700 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2701 			retval = EINVAL;
2702 			break;
2703 		}
2704 
2705 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2706 		    sizeof(struct ctl_ooa_entry))) {
2707 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2708 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2709 			       __func__, ooa_hdr->alloc_len,
2710 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2711 			retval = EINVAL;
2712 			break;
2713 		}
2714 
2715 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2716 		if (entries == NULL) {
2717 			printf("%s: could not allocate %d bytes for OOA "
2718 			       "dump\n", __func__, ooa_hdr->alloc_len);
2719 			retval = ENOMEM;
2720 			break;
2721 		}
2722 
2723 		mtx_lock(&softc->ctl_lock);
2724 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2725 		    (ooa_hdr->lun_num >= ctl_max_luns ||
2726 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2727 			mtx_unlock(&softc->ctl_lock);
2728 			free(entries, M_CTL);
2729 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2730 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2731 			retval = EINVAL;
2732 			break;
2733 		}
2734 
2735 		cur_fill_num = 0;
2736 
2737 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2738 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2739 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2740 				    ooa_hdr, entries);
2741 			}
2742 		} else {
2743 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2744 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2745 			    entries);
2746 		}
2747 		mtx_unlock(&softc->ctl_lock);
2748 
2749 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2750 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2751 			sizeof(struct ctl_ooa_entry);
2752 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2753 		if (retval != 0) {
2754 			printf("%s: error copying out %d bytes for OOA dump\n",
2755 			       __func__, ooa_hdr->fill_len);
2756 		}
2757 
2758 		getbinuptime(&ooa_hdr->cur_bt);
2759 
2760 		if (cur_fill_num > ooa_hdr->alloc_num) {
2761 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2762 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2763 		} else {
2764 			ooa_hdr->dropped_num = 0;
2765 			ooa_hdr->status = CTL_OOA_OK;
2766 		}
2767 
2768 		free(entries, M_CTL);
2769 		break;
2770 	}
2771 	case CTL_DELAY_IO: {
2772 		struct ctl_io_delay_info *delay_info;
2773 
2774 		delay_info = (struct ctl_io_delay_info *)addr;
2775 
2776 #ifdef CTL_IO_DELAY
2777 		mtx_lock(&softc->ctl_lock);
2778 		if (delay_info->lun_id >= ctl_max_luns ||
2779 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2780 			mtx_unlock(&softc->ctl_lock);
2781 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2782 			break;
2783 		}
2784 		mtx_lock(&lun->lun_lock);
2785 		mtx_unlock(&softc->ctl_lock);
2786 		delay_info->status = CTL_DELAY_STATUS_OK;
2787 		switch (delay_info->delay_type) {
2788 		case CTL_DELAY_TYPE_CONT:
2789 		case CTL_DELAY_TYPE_ONESHOT:
2790 			break;
2791 		default:
2792 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2793 			break;
2794 		}
2795 		switch (delay_info->delay_loc) {
2796 		case CTL_DELAY_LOC_DATAMOVE:
2797 			lun->delay_info.datamove_type = delay_info->delay_type;
2798 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2799 			break;
2800 		case CTL_DELAY_LOC_DONE:
2801 			lun->delay_info.done_type = delay_info->delay_type;
2802 			lun->delay_info.done_delay = delay_info->delay_secs;
2803 			break;
2804 		default:
2805 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2806 			break;
2807 		}
2808 		mtx_unlock(&lun->lun_lock);
2809 #else
2810 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2811 #endif /* CTL_IO_DELAY */
2812 		break;
2813 	}
2814 	case CTL_ERROR_INJECT: {
2815 		struct ctl_error_desc *err_desc, *new_err_desc;
2816 
2817 		err_desc = (struct ctl_error_desc *)addr;
2818 
2819 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2820 				      M_WAITOK | M_ZERO);
2821 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2822 
2823 		mtx_lock(&softc->ctl_lock);
2824 		if (err_desc->lun_id >= ctl_max_luns ||
2825 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2826 			mtx_unlock(&softc->ctl_lock);
2827 			free(new_err_desc, M_CTL);
2828 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2829 			       __func__, (uintmax_t)err_desc->lun_id);
2830 			retval = EINVAL;
2831 			break;
2832 		}
2833 		mtx_lock(&lun->lun_lock);
2834 		mtx_unlock(&softc->ctl_lock);
2835 
2836 		/*
2837 		 * We could do some checking here to verify the validity
2838 		 * of the request, but given the complexity of error
2839 		 * injection requests, the checking logic would be fairly
2840 		 * complex.
2841 		 *
2842 		 * For now, if the request is invalid, it just won't get
2843 		 * executed and might get deleted.
2844 		 */
2845 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2846 
2847 		/*
2848 		 * XXX KDM check to make sure the serial number is unique,
2849 		 * in case we somehow manage to wrap.  That shouldn't
2850 		 * happen for a very long time, but it's the right thing to
2851 		 * do.
2852 		 */
2853 		new_err_desc->serial = lun->error_serial;
2854 		err_desc->serial = lun->error_serial;
2855 		lun->error_serial++;
2856 
2857 		mtx_unlock(&lun->lun_lock);
2858 		break;
2859 	}
2860 	case CTL_ERROR_INJECT_DELETE: {
2861 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2862 		int delete_done;
2863 
2864 		delete_desc = (struct ctl_error_desc *)addr;
2865 		delete_done = 0;
2866 
2867 		mtx_lock(&softc->ctl_lock);
2868 		if (delete_desc->lun_id >= ctl_max_luns ||
2869 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2870 			mtx_unlock(&softc->ctl_lock);
2871 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2872 			       __func__, (uintmax_t)delete_desc->lun_id);
2873 			retval = EINVAL;
2874 			break;
2875 		}
2876 		mtx_lock(&lun->lun_lock);
2877 		mtx_unlock(&softc->ctl_lock);
2878 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2879 			if (desc->serial != delete_desc->serial)
2880 				continue;
2881 
2882 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2883 				      links);
2884 			free(desc, M_CTL);
2885 			delete_done = 1;
2886 		}
2887 		mtx_unlock(&lun->lun_lock);
2888 		if (delete_done == 0) {
2889 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2890 			       "error serial %ju on LUN %u\n", __func__,
2891 			       delete_desc->serial, delete_desc->lun_id);
2892 			retval = EINVAL;
2893 			break;
2894 		}
2895 		break;
2896 	}
2897 	case CTL_DUMP_STRUCTS: {
2898 		int j, k;
2899 		struct ctl_port *port;
2900 		struct ctl_frontend *fe;
2901 
2902 		mtx_lock(&softc->ctl_lock);
2903 		printf("CTL Persistent Reservation information start:\n");
2904 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2905 			mtx_lock(&lun->lun_lock);
2906 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2907 				mtx_unlock(&lun->lun_lock);
2908 				continue;
2909 			}
2910 
2911 			for (j = 0; j < ctl_max_ports; j++) {
2912 				if (lun->pr_keys[j] == NULL)
2913 					continue;
2914 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2915 					if (lun->pr_keys[j][k] == 0)
2916 						continue;
2917 					printf("  LUN %ju port %d iid %d key "
2918 					       "%#jx\n", lun->lun, j, k,
2919 					       (uintmax_t)lun->pr_keys[j][k]);
2920 				}
2921 			}
2922 			mtx_unlock(&lun->lun_lock);
2923 		}
2924 		printf("CTL Persistent Reservation information end\n");
2925 		printf("CTL Ports:\n");
2926 		STAILQ_FOREACH(port, &softc->port_list, links) {
2927 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2928 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2929 			       port->frontend->name, port->port_type,
2930 			       port->physical_port, port->virtual_port,
2931 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2932 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2933 				if (port->wwpn_iid[j].in_use == 0 &&
2934 				    port->wwpn_iid[j].wwpn == 0 &&
2935 				    port->wwpn_iid[j].name == NULL)
2936 					continue;
2937 
2938 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2939 				    j, port->wwpn_iid[j].in_use,
2940 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2941 				    port->wwpn_iid[j].name);
2942 			}
2943 		}
2944 		printf("CTL Port information end\n");
2945 		mtx_unlock(&softc->ctl_lock);
2946 		/*
2947 		 * XXX KDM calling this without a lock.  We'd likely want
2948 		 * to drop the lock before calling the frontend's dump
2949 		 * routine anyway.
2950 		 */
2951 		printf("CTL Frontends:\n");
2952 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2953 			printf("  Frontend '%s'\n", fe->name);
2954 			if (fe->fe_dump != NULL)
2955 				fe->fe_dump();
2956 		}
2957 		printf("CTL Frontend information end\n");
2958 		break;
2959 	}
2960 	case CTL_LUN_REQ: {
2961 		struct ctl_lun_req *lun_req;
2962 		struct ctl_backend_driver *backend;
2963 		void *packed;
2964 		nvlist_t *tmp_args_nvl;
2965 		size_t packed_len;
2966 
2967 		lun_req = (struct ctl_lun_req *)addr;
2968 		tmp_args_nvl = lun_req->args_nvl;
2969 
2970 		backend = ctl_backend_find(lun_req->backend);
2971 		if (backend == NULL) {
2972 			lun_req->status = CTL_LUN_ERROR;
2973 			snprintf(lun_req->error_str,
2974 				 sizeof(lun_req->error_str),
2975 				 "Backend \"%s\" not found.",
2976 				 lun_req->backend);
2977 			break;
2978 		}
2979 
2980 		if (lun_req->args != NULL) {
2981 			if (lun_req->args_len > CTL_MAX_ARGS_LEN) {
2982 				lun_req->status = CTL_LUN_ERROR;
2983 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2984 				    "Too big args.");
2985 				break;
2986 			}
2987 			packed = malloc(lun_req->args_len, M_CTL, M_WAITOK);
2988 			if (copyin(lun_req->args, packed, lun_req->args_len) != 0) {
2989 				free(packed, M_CTL);
2990 				lun_req->status = CTL_LUN_ERROR;
2991 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2992 				    "Cannot copyin args.");
2993 				break;
2994 			}
2995 			lun_req->args_nvl = nvlist_unpack(packed,
2996 			    lun_req->args_len, 0);
2997 			free(packed, M_CTL);
2998 
2999 			if (lun_req->args_nvl == NULL) {
3000 				lun_req->status = CTL_LUN_ERROR;
3001 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
3002 				    "Cannot unpack args nvlist.");
3003 				break;
3004 			}
3005 		} else
3006 			lun_req->args_nvl = nvlist_create(0);
3007 
3008 		lun_req->result_nvl = NULL;
3009 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3010 		nvlist_destroy(lun_req->args_nvl);
3011 		lun_req->args_nvl = tmp_args_nvl;
3012 
3013 		if (lun_req->result_nvl != NULL) {
3014 			if (lun_req->result != NULL) {
3015 				packed = nvlist_pack(lun_req->result_nvl,
3016 				    &packed_len);
3017 				if (packed == NULL) {
3018 					lun_req->status = CTL_LUN_ERROR;
3019 					snprintf(lun_req->error_str,
3020 					    sizeof(lun_req->error_str),
3021 					    "Cannot pack result nvlist.");
3022 					break;
3023 				}
3024 
3025 				if (packed_len > lun_req->result_len) {
3026 					lun_req->status = CTL_LUN_ERROR;
3027 					snprintf(lun_req->error_str,
3028 					    sizeof(lun_req->error_str),
3029 					    "Result nvlist too large.");
3030 					free(packed, M_NVLIST);
3031 					break;
3032 				}
3033 
3034 				if (copyout(packed, lun_req->result, packed_len)) {
3035 					lun_req->status = CTL_LUN_ERROR;
3036 					snprintf(lun_req->error_str,
3037 					    sizeof(lun_req->error_str),
3038 					    "Cannot copyout() the result.");
3039 					free(packed, M_NVLIST);
3040 					break;
3041 				}
3042 
3043 				lun_req->result_len = packed_len;
3044 				free(packed, M_NVLIST);
3045 			}
3046 
3047 			nvlist_destroy(lun_req->result_nvl);
3048 		}
3049 		break;
3050 	}
3051 	case CTL_LUN_LIST: {
3052 		struct sbuf *sb;
3053 		struct ctl_lun_list *list;
3054 		const char *name, *value;
3055 		void *cookie;
3056 		int type;
3057 
3058 		list = (struct ctl_lun_list *)addr;
3059 
3060 		/*
3061 		 * Allocate a fixed length sbuf here, based on the length
3062 		 * of the user's buffer.  We could allocate an auto-extending
3063 		 * buffer, and then tell the user how much larger our
3064 		 * amount of data is than his buffer, but that presents
3065 		 * some problems:
3066 		 *
3067 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3068 		 *     we can't hold a lock while calling them with an
3069 		 *     auto-extending buffer.
3070  		 *
3071 		 * 2.  There is not currently a LUN reference counting
3072 		 *     mechanism, outside of outstanding transactions on
3073 		 *     the LUN's OOA queue.  So a LUN could go away on us
3074 		 *     while we're getting the LUN number, backend-specific
3075 		 *     information, etc.  Thus, given the way things
3076 		 *     currently work, we need to hold the CTL lock while
3077 		 *     grabbing LUN information.
3078 		 *
3079 		 * So, from the user's standpoint, the best thing to do is
3080 		 * allocate what he thinks is a reasonable buffer length,
3081 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3082 		 * double the buffer length and try again.  (And repeat
3083 		 * that until he succeeds.)
3084 		 */
3085 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3086 		if (sb == NULL) {
3087 			list->status = CTL_LUN_LIST_ERROR;
3088 			snprintf(list->error_str, sizeof(list->error_str),
3089 				 "Unable to allocate %d bytes for LUN list",
3090 				 list->alloc_len);
3091 			break;
3092 		}
3093 
3094 		sbuf_printf(sb, "<ctllunlist>\n");
3095 
3096 		mtx_lock(&softc->ctl_lock);
3097 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3098 			mtx_lock(&lun->lun_lock);
3099 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3100 					     (uintmax_t)lun->lun);
3101 
3102 			/*
3103 			 * Bail out as soon as we see that we've overfilled
3104 			 * the buffer.
3105 			 */
3106 			if (retval != 0)
3107 				break;
3108 
3109 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3110 					     "</backend_type>\n",
3111 					     (lun->backend == NULL) ?  "none" :
3112 					     lun->backend->name);
3113 
3114 			if (retval != 0)
3115 				break;
3116 
3117 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3118 					     lun->be_lun->lun_type);
3119 
3120 			if (retval != 0)
3121 				break;
3122 
3123 			if (lun->backend == NULL) {
3124 				retval = sbuf_printf(sb, "</lun>\n");
3125 				if (retval != 0)
3126 					break;
3127 				continue;
3128 			}
3129 
3130 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3131 					     (lun->be_lun->maxlba > 0) ?
3132 					     lun->be_lun->maxlba + 1 : 0);
3133 
3134 			if (retval != 0)
3135 				break;
3136 
3137 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3138 					     lun->be_lun->blocksize);
3139 
3140 			if (retval != 0)
3141 				break;
3142 
3143 			retval = sbuf_printf(sb, "\t<serial_number>");
3144 
3145 			if (retval != 0)
3146 				break;
3147 
3148 			retval = ctl_sbuf_printf_esc(sb,
3149 			    lun->be_lun->serial_num,
3150 			    sizeof(lun->be_lun->serial_num));
3151 
3152 			if (retval != 0)
3153 				break;
3154 
3155 			retval = sbuf_printf(sb, "</serial_number>\n");
3156 
3157 			if (retval != 0)
3158 				break;
3159 
3160 			retval = sbuf_printf(sb, "\t<device_id>");
3161 
3162 			if (retval != 0)
3163 				break;
3164 
3165 			retval = ctl_sbuf_printf_esc(sb,
3166 			    lun->be_lun->device_id,
3167 			    sizeof(lun->be_lun->device_id));
3168 
3169 			if (retval != 0)
3170 				break;
3171 
3172 			retval = sbuf_printf(sb, "</device_id>\n");
3173 
3174 			if (retval != 0)
3175 				break;
3176 
3177 			if (lun->backend->lun_info != NULL) {
3178 				retval = lun->backend->lun_info(lun->be_lun, sb);
3179 				if (retval != 0)
3180 					break;
3181 			}
3182 
3183 			cookie = NULL;
3184 			while ((name = nvlist_next(lun->be_lun->options, &type,
3185 			    &cookie)) != NULL) {
3186 				sbuf_printf(sb, "\t<%s>", name);
3187 
3188 				if (type == NV_TYPE_STRING) {
3189 					value = dnvlist_get_string(
3190 					    lun->be_lun->options, name, NULL);
3191 					if (value != NULL)
3192 						sbuf_printf(sb, "%s", value);
3193 				}
3194 
3195 				sbuf_printf(sb, "</%s>\n", name);
3196 			}
3197 
3198 			retval = sbuf_printf(sb, "</lun>\n");
3199 
3200 			if (retval != 0)
3201 				break;
3202 			mtx_unlock(&lun->lun_lock);
3203 		}
3204 		if (lun != NULL)
3205 			mtx_unlock(&lun->lun_lock);
3206 		mtx_unlock(&softc->ctl_lock);
3207 
3208 		if ((retval != 0)
3209 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3210 			retval = 0;
3211 			sbuf_delete(sb);
3212 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3213 			snprintf(list->error_str, sizeof(list->error_str),
3214 				 "Out of space, %d bytes is too small",
3215 				 list->alloc_len);
3216 			break;
3217 		}
3218 
3219 		sbuf_finish(sb);
3220 
3221 		retval = copyout(sbuf_data(sb), list->lun_xml,
3222 				 sbuf_len(sb) + 1);
3223 
3224 		list->fill_len = sbuf_len(sb) + 1;
3225 		list->status = CTL_LUN_LIST_OK;
3226 		sbuf_delete(sb);
3227 		break;
3228 	}
3229 	case CTL_ISCSI: {
3230 		struct ctl_iscsi *ci;
3231 		struct ctl_frontend *fe;
3232 
3233 		ci = (struct ctl_iscsi *)addr;
3234 
3235 		fe = ctl_frontend_find("iscsi");
3236 		if (fe == NULL) {
3237 			ci->status = CTL_ISCSI_ERROR;
3238 			snprintf(ci->error_str, sizeof(ci->error_str),
3239 			    "Frontend \"iscsi\" not found.");
3240 			break;
3241 		}
3242 
3243 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3244 		break;
3245 	}
3246 	case CTL_PORT_REQ: {
3247 		struct ctl_req *req;
3248 		struct ctl_frontend *fe;
3249 		void *packed;
3250 		nvlist_t *tmp_args_nvl;
3251 		size_t packed_len;
3252 
3253 		req = (struct ctl_req *)addr;
3254 		tmp_args_nvl = req->args_nvl;
3255 
3256 		fe = ctl_frontend_find(req->driver);
3257 		if (fe == NULL) {
3258 			req->status = CTL_LUN_ERROR;
3259 			snprintf(req->error_str, sizeof(req->error_str),
3260 			    "Frontend \"%s\" not found.", req->driver);
3261 			break;
3262 		}
3263 
3264 		if (req->args != NULL) {
3265 			if (req->args_len > CTL_MAX_ARGS_LEN) {
3266 				req->status = CTL_LUN_ERROR;
3267 				snprintf(req->error_str, sizeof(req->error_str),
3268 				    "Too big args.");
3269 				break;
3270 			}
3271 			packed = malloc(req->args_len, M_CTL, M_WAITOK);
3272 			if (copyin(req->args, packed, req->args_len) != 0) {
3273 				free(packed, M_CTL);
3274 				req->status = CTL_LUN_ERROR;
3275 				snprintf(req->error_str, sizeof(req->error_str),
3276 				    "Cannot copyin args.");
3277 				break;
3278 			}
3279 			req->args_nvl = nvlist_unpack(packed,
3280 			    req->args_len, 0);
3281 			free(packed, M_CTL);
3282 
3283 			if (req->args_nvl == NULL) {
3284 				req->status = CTL_LUN_ERROR;
3285 				snprintf(req->error_str, sizeof(req->error_str),
3286 				    "Cannot unpack args nvlist.");
3287 				break;
3288 			}
3289 		} else
3290 			req->args_nvl = nvlist_create(0);
3291 
3292 		req->result_nvl = NULL;
3293 		if (fe->ioctl)
3294 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3295 		else
3296 			retval = ENODEV;
3297 
3298 		nvlist_destroy(req->args_nvl);
3299 		req->args_nvl = tmp_args_nvl;
3300 
3301 		if (req->result_nvl != NULL) {
3302 			if (req->result != NULL) {
3303 				packed = nvlist_pack(req->result_nvl,
3304 				    &packed_len);
3305 				if (packed == NULL) {
3306 					req->status = CTL_LUN_ERROR;
3307 					snprintf(req->error_str,
3308 					    sizeof(req->error_str),
3309 					    "Cannot pack result nvlist.");
3310 					break;
3311 				}
3312 
3313 				if (packed_len > req->result_len) {
3314 					req->status = CTL_LUN_ERROR;
3315 					snprintf(req->error_str,
3316 					    sizeof(req->error_str),
3317 					    "Result nvlist too large.");
3318 					free(packed, M_NVLIST);
3319 					break;
3320 				}
3321 
3322 				if (copyout(packed, req->result, packed_len)) {
3323 					req->status = CTL_LUN_ERROR;
3324 					snprintf(req->error_str,
3325 					    sizeof(req->error_str),
3326 					    "Cannot copyout() the result.");
3327 					free(packed, M_NVLIST);
3328 					break;
3329 				}
3330 
3331 				req->result_len = packed_len;
3332 				free(packed, M_NVLIST);
3333 			}
3334 
3335 			nvlist_destroy(req->result_nvl);
3336 		}
3337 		break;
3338 	}
3339 	case CTL_PORT_LIST: {
3340 		struct sbuf *sb;
3341 		struct ctl_port *port;
3342 		struct ctl_lun_list *list;
3343 		const char *name, *value;
3344 		void *cookie;
3345 		int j, type;
3346 		uint32_t plun;
3347 
3348 		list = (struct ctl_lun_list *)addr;
3349 
3350 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3351 		if (sb == NULL) {
3352 			list->status = CTL_LUN_LIST_ERROR;
3353 			snprintf(list->error_str, sizeof(list->error_str),
3354 				 "Unable to allocate %d bytes for LUN list",
3355 				 list->alloc_len);
3356 			break;
3357 		}
3358 
3359 		sbuf_printf(sb, "<ctlportlist>\n");
3360 
3361 		mtx_lock(&softc->ctl_lock);
3362 		STAILQ_FOREACH(port, &softc->port_list, links) {
3363 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3364 					     (uintmax_t)port->targ_port);
3365 
3366 			/*
3367 			 * Bail out as soon as we see that we've overfilled
3368 			 * the buffer.
3369 			 */
3370 			if (retval != 0)
3371 				break;
3372 
3373 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3374 			    "</frontend_type>\n", port->frontend->name);
3375 			if (retval != 0)
3376 				break;
3377 
3378 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3379 					     port->port_type);
3380 			if (retval != 0)
3381 				break;
3382 
3383 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3384 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3385 			if (retval != 0)
3386 				break;
3387 
3388 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3389 			    port->port_name);
3390 			if (retval != 0)
3391 				break;
3392 
3393 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3394 			    port->physical_port);
3395 			if (retval != 0)
3396 				break;
3397 
3398 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3399 			    port->virtual_port);
3400 			if (retval != 0)
3401 				break;
3402 
3403 			if (port->target_devid != NULL) {
3404 				sbuf_printf(sb, "\t<target>");
3405 				ctl_id_sbuf(port->target_devid, sb);
3406 				sbuf_printf(sb, "</target>\n");
3407 			}
3408 
3409 			if (port->port_devid != NULL) {
3410 				sbuf_printf(sb, "\t<port>");
3411 				ctl_id_sbuf(port->port_devid, sb);
3412 				sbuf_printf(sb, "</port>\n");
3413 			}
3414 
3415 			if (port->port_info != NULL) {
3416 				retval = port->port_info(port->onoff_arg, sb);
3417 				if (retval != 0)
3418 					break;
3419 			}
3420 
3421 			cookie = NULL;
3422 			while ((name = nvlist_next(port->options, &type,
3423 			    &cookie)) != NULL) {
3424 				sbuf_printf(sb, "\t<%s>", name);
3425 
3426 				if (type == NV_TYPE_STRING) {
3427 					value = dnvlist_get_string(port->options,
3428 					    name, NULL);
3429 					if (value != NULL)
3430 						sbuf_printf(sb, "%s", value);
3431 				}
3432 
3433 				sbuf_printf(sb, "</%s>\n", name);
3434 			}
3435 
3436 			if (port->lun_map != NULL) {
3437 				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3438 				for (j = 0; j < port->lun_map_size; j++) {
3439 					plun = ctl_lun_map_from_port(port, j);
3440 					if (plun == UINT32_MAX)
3441 						continue;
3442 					sbuf_printf(sb,
3443 					    "\t<lun id=\"%u\">%u</lun>\n",
3444 					    j, plun);
3445 				}
3446 			}
3447 
3448 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3449 				if (port->wwpn_iid[j].in_use == 0 ||
3450 				    (port->wwpn_iid[j].wwpn == 0 &&
3451 				     port->wwpn_iid[j].name == NULL))
3452 					continue;
3453 
3454 				if (port->wwpn_iid[j].name != NULL)
3455 					retval = sbuf_printf(sb,
3456 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3457 					    j, port->wwpn_iid[j].name);
3458 				else
3459 					retval = sbuf_printf(sb,
3460 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3461 					    j, port->wwpn_iid[j].wwpn);
3462 				if (retval != 0)
3463 					break;
3464 			}
3465 			if (retval != 0)
3466 				break;
3467 
3468 			retval = sbuf_printf(sb, "</targ_port>\n");
3469 			if (retval != 0)
3470 				break;
3471 		}
3472 		mtx_unlock(&softc->ctl_lock);
3473 
3474 		if ((retval != 0)
3475 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3476 			retval = 0;
3477 			sbuf_delete(sb);
3478 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3479 			snprintf(list->error_str, sizeof(list->error_str),
3480 				 "Out of space, %d bytes is too small",
3481 				 list->alloc_len);
3482 			break;
3483 		}
3484 
3485 		sbuf_finish(sb);
3486 
3487 		retval = copyout(sbuf_data(sb), list->lun_xml,
3488 				 sbuf_len(sb) + 1);
3489 
3490 		list->fill_len = sbuf_len(sb) + 1;
3491 		list->status = CTL_LUN_LIST_OK;
3492 		sbuf_delete(sb);
3493 		break;
3494 	}
3495 	case CTL_LUN_MAP: {
3496 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3497 		struct ctl_port *port;
3498 
3499 		mtx_lock(&softc->ctl_lock);
3500 		if (lm->port < softc->port_min ||
3501 		    lm->port >= softc->port_max ||
3502 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3503 			mtx_unlock(&softc->ctl_lock);
3504 			return (ENXIO);
3505 		}
3506 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3507 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3508 				if (ctl_lun_map_to_port(port, lun->lun) ==
3509 				    UINT32_MAX)
3510 					continue;
3511 				mtx_lock(&lun->lun_lock);
3512 				ctl_est_ua_port(lun, lm->port, -1,
3513 				    CTL_UA_LUN_CHANGE);
3514 				mtx_unlock(&lun->lun_lock);
3515 			}
3516 		}
3517 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3518 		if (lm->plun != UINT32_MAX) {
3519 			if (lm->lun == UINT32_MAX)
3520 				retval = ctl_lun_map_unset(port, lm->plun);
3521 			else if (lm->lun < ctl_max_luns &&
3522 			    softc->ctl_luns[lm->lun] != NULL)
3523 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3524 			else
3525 				return (ENXIO);
3526 		} else {
3527 			if (lm->lun == UINT32_MAX)
3528 				retval = ctl_lun_map_deinit(port);
3529 			else
3530 				retval = ctl_lun_map_init(port);
3531 		}
3532 		if (port->status & CTL_PORT_STATUS_ONLINE)
3533 			ctl_isc_announce_port(port);
3534 		break;
3535 	}
3536 	case CTL_GET_LUN_STATS: {
3537 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3538 		int i;
3539 
3540 		/*
3541 		 * XXX KDM no locking here.  If the LUN list changes,
3542 		 * things can blow up.
3543 		 */
3544 		i = 0;
3545 		stats->status = CTL_SS_OK;
3546 		stats->fill_len = 0;
3547 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3548 			if (lun->lun < stats->first_item)
3549 				continue;
3550 			if (stats->fill_len + sizeof(lun->stats) >
3551 			    stats->alloc_len) {
3552 				stats->status = CTL_SS_NEED_MORE_SPACE;
3553 				break;
3554 			}
3555 			retval = copyout(&lun->stats, &stats->stats[i++],
3556 					 sizeof(lun->stats));
3557 			if (retval != 0)
3558 				break;
3559 			stats->fill_len += sizeof(lun->stats);
3560 		}
3561 		stats->num_items = softc->num_luns;
3562 		stats->flags = CTL_STATS_FLAG_NONE;
3563 #ifdef CTL_TIME_IO
3564 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3565 #endif
3566 		getnanouptime(&stats->timestamp);
3567 		break;
3568 	}
3569 	case CTL_GET_PORT_STATS: {
3570 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3571 		int i;
3572 
3573 		/*
3574 		 * XXX KDM no locking here.  If the LUN list changes,
3575 		 * things can blow up.
3576 		 */
3577 		i = 0;
3578 		stats->status = CTL_SS_OK;
3579 		stats->fill_len = 0;
3580 		STAILQ_FOREACH(port, &softc->port_list, links) {
3581 			if (port->targ_port < stats->first_item)
3582 				continue;
3583 			if (stats->fill_len + sizeof(port->stats) >
3584 			    stats->alloc_len) {
3585 				stats->status = CTL_SS_NEED_MORE_SPACE;
3586 				break;
3587 			}
3588 			retval = copyout(&port->stats, &stats->stats[i++],
3589 					 sizeof(port->stats));
3590 			if (retval != 0)
3591 				break;
3592 			stats->fill_len += sizeof(port->stats);
3593 		}
3594 		stats->num_items = softc->num_ports;
3595 		stats->flags = CTL_STATS_FLAG_NONE;
3596 #ifdef CTL_TIME_IO
3597 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3598 #endif
3599 		getnanouptime(&stats->timestamp);
3600 		break;
3601 	}
3602 	default: {
3603 		/* XXX KDM should we fix this? */
3604 #if 0
3605 		struct ctl_backend_driver *backend;
3606 		unsigned int type;
3607 		int found;
3608 
3609 		found = 0;
3610 
3611 		/*
3612 		 * We encode the backend type as the ioctl type for backend
3613 		 * ioctls.  So parse it out here, and then search for a
3614 		 * backend of this type.
3615 		 */
3616 		type = _IOC_TYPE(cmd);
3617 
3618 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3619 			if (backend->type == type) {
3620 				found = 1;
3621 				break;
3622 			}
3623 		}
3624 		if (found == 0) {
3625 			printf("ctl: unknown ioctl command %#lx or backend "
3626 			       "%d\n", cmd, type);
3627 			retval = EINVAL;
3628 			break;
3629 		}
3630 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3631 #endif
3632 		retval = ENOTTY;
3633 		break;
3634 	}
3635 	}
3636 	return (retval);
3637 }
3638 
3639 uint32_t
3640 ctl_get_initindex(struct ctl_nexus *nexus)
3641 {
3642 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3643 }
3644 
3645 int
3646 ctl_lun_map_init(struct ctl_port *port)
3647 {
3648 	struct ctl_softc *softc = port->ctl_softc;
3649 	struct ctl_lun *lun;
3650 	int size = ctl_lun_map_size;
3651 	uint32_t i;
3652 
3653 	if (port->lun_map == NULL || port->lun_map_size < size) {
3654 		port->lun_map_size = 0;
3655 		free(port->lun_map, M_CTL);
3656 		port->lun_map = malloc(size * sizeof(uint32_t),
3657 		    M_CTL, M_NOWAIT);
3658 	}
3659 	if (port->lun_map == NULL)
3660 		return (ENOMEM);
3661 	for (i = 0; i < size; i++)
3662 		port->lun_map[i] = UINT32_MAX;
3663 	port->lun_map_size = size;
3664 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3665 		if (port->lun_disable != NULL) {
3666 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3667 				port->lun_disable(port->targ_lun_arg, lun->lun);
3668 		}
3669 		ctl_isc_announce_port(port);
3670 	}
3671 	return (0);
3672 }
3673 
3674 int
3675 ctl_lun_map_deinit(struct ctl_port *port)
3676 {
3677 	struct ctl_softc *softc = port->ctl_softc;
3678 	struct ctl_lun *lun;
3679 
3680 	if (port->lun_map == NULL)
3681 		return (0);
3682 	port->lun_map_size = 0;
3683 	free(port->lun_map, M_CTL);
3684 	port->lun_map = NULL;
3685 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3686 		if (port->lun_enable != NULL) {
3687 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3688 				port->lun_enable(port->targ_lun_arg, lun->lun);
3689 		}
3690 		ctl_isc_announce_port(port);
3691 	}
3692 	return (0);
3693 }
3694 
3695 int
3696 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3697 {
3698 	int status;
3699 	uint32_t old;
3700 
3701 	if (port->lun_map == NULL) {
3702 		status = ctl_lun_map_init(port);
3703 		if (status != 0)
3704 			return (status);
3705 	}
3706 	if (plun >= port->lun_map_size)
3707 		return (EINVAL);
3708 	old = port->lun_map[plun];
3709 	port->lun_map[plun] = glun;
3710 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3711 		if (port->lun_enable != NULL)
3712 			port->lun_enable(port->targ_lun_arg, plun);
3713 		ctl_isc_announce_port(port);
3714 	}
3715 	return (0);
3716 }
3717 
3718 int
3719 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3720 {
3721 	uint32_t old;
3722 
3723 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3724 		return (0);
3725 	old = port->lun_map[plun];
3726 	port->lun_map[plun] = UINT32_MAX;
3727 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3728 		if (port->lun_disable != NULL)
3729 			port->lun_disable(port->targ_lun_arg, plun);
3730 		ctl_isc_announce_port(port);
3731 	}
3732 	return (0);
3733 }
3734 
3735 uint32_t
3736 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3737 {
3738 
3739 	if (port == NULL)
3740 		return (UINT32_MAX);
3741 	if (port->lun_map == NULL)
3742 		return (lun_id);
3743 	if (lun_id > port->lun_map_size)
3744 		return (UINT32_MAX);
3745 	return (port->lun_map[lun_id]);
3746 }
3747 
3748 uint32_t
3749 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3750 {
3751 	uint32_t i;
3752 
3753 	if (port == NULL)
3754 		return (UINT32_MAX);
3755 	if (port->lun_map == NULL)
3756 		return (lun_id);
3757 	for (i = 0; i < port->lun_map_size; i++) {
3758 		if (port->lun_map[i] == lun_id)
3759 			return (i);
3760 	}
3761 	return (UINT32_MAX);
3762 }
3763 
3764 uint32_t
3765 ctl_decode_lun(uint64_t encoded)
3766 {
3767 	uint8_t lun[8];
3768 	uint32_t result = 0xffffffff;
3769 
3770 	be64enc(lun, encoded);
3771 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3772 	case RPL_LUNDATA_ATYP_PERIPH:
3773 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3774 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3775 			result = lun[1];
3776 		break;
3777 	case RPL_LUNDATA_ATYP_FLAT:
3778 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3779 		    lun[6] == 0 && lun[7] == 0)
3780 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3781 		break;
3782 	case RPL_LUNDATA_ATYP_EXTLUN:
3783 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3784 		case 0x02:
3785 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3786 			case 0x00:
3787 				result = lun[1];
3788 				break;
3789 			case 0x10:
3790 				result = (lun[1] << 16) + (lun[2] << 8) +
3791 				    lun[3];
3792 				break;
3793 			case 0x20:
3794 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3795 					result = (lun[2] << 24) +
3796 					    (lun[3] << 16) + (lun[4] << 8) +
3797 					    lun[5];
3798 				break;
3799 			}
3800 			break;
3801 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3802 			result = 0xffffffff;
3803 			break;
3804 		}
3805 		break;
3806 	}
3807 	return (result);
3808 }
3809 
3810 uint64_t
3811 ctl_encode_lun(uint32_t decoded)
3812 {
3813 	uint64_t l = decoded;
3814 
3815 	if (l <= 0xff)
3816 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3817 	if (l <= 0x3fff)
3818 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3819 	if (l <= 0xffffff)
3820 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3821 		    (l << 32));
3822 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3823 }
3824 
3825 int
3826 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3827 {
3828 	int i;
3829 
3830 	for (i = first; i < last; i++) {
3831 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3832 			return (i);
3833 	}
3834 	return (-1);
3835 }
3836 
3837 int
3838 ctl_set_mask(uint32_t *mask, uint32_t bit)
3839 {
3840 	uint32_t chunk, piece;
3841 
3842 	chunk = bit >> 5;
3843 	piece = bit % (sizeof(uint32_t) * 8);
3844 
3845 	if ((mask[chunk] & (1 << piece)) != 0)
3846 		return (-1);
3847 	else
3848 		mask[chunk] |= (1 << piece);
3849 
3850 	return (0);
3851 }
3852 
3853 int
3854 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3855 {
3856 	uint32_t chunk, piece;
3857 
3858 	chunk = bit >> 5;
3859 	piece = bit % (sizeof(uint32_t) * 8);
3860 
3861 	if ((mask[chunk] & (1 << piece)) == 0)
3862 		return (-1);
3863 	else
3864 		mask[chunk] &= ~(1 << piece);
3865 
3866 	return (0);
3867 }
3868 
3869 int
3870 ctl_is_set(uint32_t *mask, uint32_t bit)
3871 {
3872 	uint32_t chunk, piece;
3873 
3874 	chunk = bit >> 5;
3875 	piece = bit % (sizeof(uint32_t) * 8);
3876 
3877 	if ((mask[chunk] & (1 << piece)) == 0)
3878 		return (0);
3879 	else
3880 		return (1);
3881 }
3882 
3883 static uint64_t
3884 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3885 {
3886 	uint64_t *t;
3887 
3888 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3889 	if (t == NULL)
3890 		return (0);
3891 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3892 }
3893 
3894 static void
3895 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3896 {
3897 	uint64_t *t;
3898 
3899 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3900 	if (t == NULL)
3901 		return;
3902 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3903 }
3904 
3905 static void
3906 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3907 {
3908 	uint64_t *p;
3909 	u_int i;
3910 
3911 	i = residx/CTL_MAX_INIT_PER_PORT;
3912 	if (lun->pr_keys[i] != NULL)
3913 		return;
3914 	mtx_unlock(&lun->lun_lock);
3915 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3916 	    M_WAITOK | M_ZERO);
3917 	mtx_lock(&lun->lun_lock);
3918 	if (lun->pr_keys[i] == NULL)
3919 		lun->pr_keys[i] = p;
3920 	else
3921 		free(p, M_CTL);
3922 }
3923 
3924 static void
3925 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3926 {
3927 	uint64_t *t;
3928 
3929 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3930 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3931 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3932 }
3933 
3934 /*
3935  * ctl_softc, pool_name, total_ctl_io are passed in.
3936  * npool is passed out.
3937  */
3938 int
3939 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3940 		uint32_t total_ctl_io, void **npool)
3941 {
3942 	struct ctl_io_pool *pool;
3943 
3944 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3945 					    M_NOWAIT | M_ZERO);
3946 	if (pool == NULL)
3947 		return (ENOMEM);
3948 
3949 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3950 	pool->ctl_softc = ctl_softc;
3951 #ifdef IO_POOLS
3952 	pool->zone = uma_zsecond_create(pool->name, NULL,
3953 	    NULL, NULL, NULL, ctl_softc->io_zone);
3954 	/* uma_prealloc(pool->zone, total_ctl_io); */
3955 #else
3956 	pool->zone = ctl_softc->io_zone;
3957 #endif
3958 
3959 	*npool = pool;
3960 	return (0);
3961 }
3962 
3963 void
3964 ctl_pool_free(struct ctl_io_pool *pool)
3965 {
3966 
3967 	if (pool == NULL)
3968 		return;
3969 
3970 #ifdef IO_POOLS
3971 	uma_zdestroy(pool->zone);
3972 #endif
3973 	free(pool, M_CTL);
3974 }
3975 
3976 union ctl_io *
3977 ctl_alloc_io(void *pool_ref)
3978 {
3979 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3980 	union ctl_io *io;
3981 
3982 	io = uma_zalloc(pool->zone, M_WAITOK);
3983 	if (io != NULL) {
3984 		io->io_hdr.pool = pool_ref;
3985 		CTL_SOFTC(io) = pool->ctl_softc;
3986 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3987 	}
3988 	return (io);
3989 }
3990 
3991 union ctl_io *
3992 ctl_alloc_io_nowait(void *pool_ref)
3993 {
3994 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3995 	union ctl_io *io;
3996 
3997 	io = uma_zalloc(pool->zone, M_NOWAIT);
3998 	if (io != NULL) {
3999 		io->io_hdr.pool = pool_ref;
4000 		CTL_SOFTC(io) = pool->ctl_softc;
4001 		TAILQ_INIT(&io->io_hdr.blocked_queue);
4002 	}
4003 	return (io);
4004 }
4005 
4006 void
4007 ctl_free_io(union ctl_io *io)
4008 {
4009 	struct ctl_io_pool *pool;
4010 
4011 	if (io == NULL)
4012 		return;
4013 
4014 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
4015 	uma_zfree(pool->zone, io);
4016 }
4017 
4018 void
4019 ctl_zero_io(union ctl_io *io)
4020 {
4021 	struct ctl_io_pool *pool;
4022 
4023 	if (io == NULL)
4024 		return;
4025 
4026 	/*
4027 	 * May need to preserve linked list pointers at some point too.
4028 	 */
4029 	pool = io->io_hdr.pool;
4030 	memset(io, 0, sizeof(*io));
4031 	io->io_hdr.pool = pool;
4032 	CTL_SOFTC(io) = pool->ctl_softc;
4033 	TAILQ_INIT(&io->io_hdr.blocked_queue);
4034 }
4035 
4036 int
4037 ctl_expand_number(const char *buf, uint64_t *num)
4038 {
4039 	char *endptr;
4040 	uint64_t number;
4041 	unsigned shift;
4042 
4043 	number = strtoq(buf, &endptr, 0);
4044 
4045 	switch (tolower((unsigned char)*endptr)) {
4046 	case 'e':
4047 		shift = 60;
4048 		break;
4049 	case 'p':
4050 		shift = 50;
4051 		break;
4052 	case 't':
4053 		shift = 40;
4054 		break;
4055 	case 'g':
4056 		shift = 30;
4057 		break;
4058 	case 'm':
4059 		shift = 20;
4060 		break;
4061 	case 'k':
4062 		shift = 10;
4063 		break;
4064 	case 'b':
4065 	case '\0': /* No unit. */
4066 		*num = number;
4067 		return (0);
4068 	default:
4069 		/* Unrecognized unit. */
4070 		return (-1);
4071 	}
4072 
4073 	if ((number << shift) >> shift != number) {
4074 		/* Overflow */
4075 		return (-1);
4076 	}
4077 	*num = number << shift;
4078 	return (0);
4079 }
4080 
4081 /*
4082  * This routine could be used in the future to load default and/or saved
4083  * mode page parameters for a particuar lun.
4084  */
4085 static int
4086 ctl_init_page_index(struct ctl_lun *lun)
4087 {
4088 	int i, page_code;
4089 	struct ctl_page_index *page_index;
4090 	const char *value;
4091 	uint64_t ival;
4092 
4093 	memcpy(&lun->mode_pages.index, page_index_template,
4094 	       sizeof(page_index_template));
4095 
4096 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4097 		page_index = &lun->mode_pages.index[i];
4098 		if (lun->be_lun->lun_type == T_DIRECT &&
4099 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4100 			continue;
4101 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4102 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4103 			continue;
4104 		if (lun->be_lun->lun_type == T_CDROM &&
4105 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4106 			continue;
4107 
4108 		page_code = page_index->page_code & SMPH_PC_MASK;
4109 		switch (page_code) {
4110 		case SMS_RW_ERROR_RECOVERY_PAGE: {
4111 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4112 			    ("subpage %#x for page %#x is incorrect!",
4113 			    page_index->subpage, page_code));
4114 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4115 			       &rw_er_page_default,
4116 			       sizeof(rw_er_page_default));
4117 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4118 			       &rw_er_page_changeable,
4119 			       sizeof(rw_er_page_changeable));
4120 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4121 			       &rw_er_page_default,
4122 			       sizeof(rw_er_page_default));
4123 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4124 			       &rw_er_page_default,
4125 			       sizeof(rw_er_page_default));
4126 			page_index->page_data =
4127 				(uint8_t *)lun->mode_pages.rw_er_page;
4128 			break;
4129 		}
4130 		case SMS_FORMAT_DEVICE_PAGE: {
4131 			struct scsi_format_page *format_page;
4132 
4133 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4134 			    ("subpage %#x for page %#x is incorrect!",
4135 			    page_index->subpage, page_code));
4136 
4137 			/*
4138 			 * Sectors per track are set above.  Bytes per
4139 			 * sector need to be set here on a per-LUN basis.
4140 			 */
4141 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4142 			       &format_page_default,
4143 			       sizeof(format_page_default));
4144 			memcpy(&lun->mode_pages.format_page[
4145 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4146 			       sizeof(format_page_changeable));
4147 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4148 			       &format_page_default,
4149 			       sizeof(format_page_default));
4150 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4151 			       &format_page_default,
4152 			       sizeof(format_page_default));
4153 
4154 			format_page = &lun->mode_pages.format_page[
4155 				CTL_PAGE_CURRENT];
4156 			scsi_ulto2b(lun->be_lun->blocksize,
4157 				    format_page->bytes_per_sector);
4158 
4159 			format_page = &lun->mode_pages.format_page[
4160 				CTL_PAGE_DEFAULT];
4161 			scsi_ulto2b(lun->be_lun->blocksize,
4162 				    format_page->bytes_per_sector);
4163 
4164 			format_page = &lun->mode_pages.format_page[
4165 				CTL_PAGE_SAVED];
4166 			scsi_ulto2b(lun->be_lun->blocksize,
4167 				    format_page->bytes_per_sector);
4168 
4169 			page_index->page_data =
4170 				(uint8_t *)lun->mode_pages.format_page;
4171 			break;
4172 		}
4173 		case SMS_RIGID_DISK_PAGE: {
4174 			struct scsi_rigid_disk_page *rigid_disk_page;
4175 			uint32_t sectors_per_cylinder;
4176 			uint64_t cylinders;
4177 #ifndef	__XSCALE__
4178 			int shift;
4179 #endif /* !__XSCALE__ */
4180 
4181 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4182 			    ("subpage %#x for page %#x is incorrect!",
4183 			    page_index->subpage, page_code));
4184 
4185 			/*
4186 			 * Rotation rate and sectors per track are set
4187 			 * above.  We calculate the cylinders here based on
4188 			 * capacity.  Due to the number of heads and
4189 			 * sectors per track we're using, smaller arrays
4190 			 * may turn out to have 0 cylinders.  Linux and
4191 			 * FreeBSD don't pay attention to these mode pages
4192 			 * to figure out capacity, but Solaris does.  It
4193 			 * seems to deal with 0 cylinders just fine, and
4194 			 * works out a fake geometry based on the capacity.
4195 			 */
4196 			memcpy(&lun->mode_pages.rigid_disk_page[
4197 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4198 			       sizeof(rigid_disk_page_default));
4199 			memcpy(&lun->mode_pages.rigid_disk_page[
4200 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4201 			       sizeof(rigid_disk_page_changeable));
4202 
4203 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4204 				CTL_DEFAULT_HEADS;
4205 
4206 			/*
4207 			 * The divide method here will be more accurate,
4208 			 * probably, but results in floating point being
4209 			 * used in the kernel on i386 (__udivdi3()).  On the
4210 			 * XScale, though, __udivdi3() is implemented in
4211 			 * software.
4212 			 *
4213 			 * The shift method for cylinder calculation is
4214 			 * accurate if sectors_per_cylinder is a power of
4215 			 * 2.  Otherwise it might be slightly off -- you
4216 			 * might have a bit of a truncation problem.
4217 			 */
4218 #ifdef	__XSCALE__
4219 			cylinders = (lun->be_lun->maxlba + 1) /
4220 				sectors_per_cylinder;
4221 #else
4222 			for (shift = 31; shift > 0; shift--) {
4223 				if (sectors_per_cylinder & (1 << shift))
4224 					break;
4225 			}
4226 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4227 #endif
4228 
4229 			/*
4230 			 * We've basically got 3 bytes, or 24 bits for the
4231 			 * cylinder size in the mode page.  If we're over,
4232 			 * just round down to 2^24.
4233 			 */
4234 			if (cylinders > 0xffffff)
4235 				cylinders = 0xffffff;
4236 
4237 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4238 				CTL_PAGE_DEFAULT];
4239 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4240 
4241 			if ((value = dnvlist_get_string(lun->be_lun->options,
4242 			    "rpm", NULL)) != NULL) {
4243 				scsi_ulto2b(strtol(value, NULL, 0),
4244 				     rigid_disk_page->rotation_rate);
4245 			}
4246 
4247 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4248 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4249 			       sizeof(rigid_disk_page_default));
4250 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4251 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4252 			       sizeof(rigid_disk_page_default));
4253 
4254 			page_index->page_data =
4255 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4256 			break;
4257 		}
4258 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4259 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4260 			    ("subpage %#x for page %#x is incorrect!",
4261 			    page_index->subpage, page_code));
4262 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4263 			       &verify_er_page_default,
4264 			       sizeof(verify_er_page_default));
4265 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4266 			       &verify_er_page_changeable,
4267 			       sizeof(verify_er_page_changeable));
4268 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4269 			       &verify_er_page_default,
4270 			       sizeof(verify_er_page_default));
4271 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4272 			       &verify_er_page_default,
4273 			       sizeof(verify_er_page_default));
4274 			page_index->page_data =
4275 				(uint8_t *)lun->mode_pages.verify_er_page;
4276 			break;
4277 		}
4278 		case SMS_CACHING_PAGE: {
4279 			struct scsi_caching_page *caching_page;
4280 
4281 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4282 			    ("subpage %#x for page %#x is incorrect!",
4283 			    page_index->subpage, page_code));
4284 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4285 			       &caching_page_default,
4286 			       sizeof(caching_page_default));
4287 			memcpy(&lun->mode_pages.caching_page[
4288 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4289 			       sizeof(caching_page_changeable));
4290 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4291 			       &caching_page_default,
4292 			       sizeof(caching_page_default));
4293 			caching_page = &lun->mode_pages.caching_page[
4294 			    CTL_PAGE_SAVED];
4295 			value = dnvlist_get_string(lun->be_lun->options,
4296 			    "writecache", NULL);
4297 			if (value != NULL && strcmp(value, "off") == 0)
4298 				caching_page->flags1 &= ~SCP_WCE;
4299 			value = dnvlist_get_string(lun->be_lun->options,
4300 			    "readcache", NULL);
4301 			if (value != NULL && strcmp(value, "off") == 0)
4302 				caching_page->flags1 |= SCP_RCD;
4303 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4304 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4305 			       sizeof(caching_page_default));
4306 			page_index->page_data =
4307 				(uint8_t *)lun->mode_pages.caching_page;
4308 			break;
4309 		}
4310 		case SMS_CONTROL_MODE_PAGE: {
4311 			switch (page_index->subpage) {
4312 			case SMS_SUBPAGE_PAGE_0: {
4313 				struct scsi_control_page *control_page;
4314 
4315 				memcpy(&lun->mode_pages.control_page[
4316 				    CTL_PAGE_DEFAULT],
4317 				       &control_page_default,
4318 				       sizeof(control_page_default));
4319 				memcpy(&lun->mode_pages.control_page[
4320 				    CTL_PAGE_CHANGEABLE],
4321 				       &control_page_changeable,
4322 				       sizeof(control_page_changeable));
4323 				memcpy(&lun->mode_pages.control_page[
4324 				    CTL_PAGE_SAVED],
4325 				       &control_page_default,
4326 				       sizeof(control_page_default));
4327 				control_page = &lun->mode_pages.control_page[
4328 				    CTL_PAGE_SAVED];
4329 				value = dnvlist_get_string(lun->be_lun->options,
4330 				    "reordering", NULL);
4331 				if (value != NULL &&
4332 				    strcmp(value, "unrestricted") == 0) {
4333 					control_page->queue_flags &=
4334 					    ~SCP_QUEUE_ALG_MASK;
4335 					control_page->queue_flags |=
4336 					    SCP_QUEUE_ALG_UNRESTRICTED;
4337 				}
4338 				memcpy(&lun->mode_pages.control_page[
4339 				    CTL_PAGE_CURRENT],
4340 				       &lun->mode_pages.control_page[
4341 				    CTL_PAGE_SAVED],
4342 				       sizeof(control_page_default));
4343 				page_index->page_data =
4344 				    (uint8_t *)lun->mode_pages.control_page;
4345 				break;
4346 			}
4347 			case 0x01:
4348 				memcpy(&lun->mode_pages.control_ext_page[
4349 				    CTL_PAGE_DEFAULT],
4350 				       &control_ext_page_default,
4351 				       sizeof(control_ext_page_default));
4352 				memcpy(&lun->mode_pages.control_ext_page[
4353 				    CTL_PAGE_CHANGEABLE],
4354 				       &control_ext_page_changeable,
4355 				       sizeof(control_ext_page_changeable));
4356 				memcpy(&lun->mode_pages.control_ext_page[
4357 				    CTL_PAGE_SAVED],
4358 				       &control_ext_page_default,
4359 				       sizeof(control_ext_page_default));
4360 				memcpy(&lun->mode_pages.control_ext_page[
4361 				    CTL_PAGE_CURRENT],
4362 				       &lun->mode_pages.control_ext_page[
4363 				    CTL_PAGE_SAVED],
4364 				       sizeof(control_ext_page_default));
4365 				page_index->page_data =
4366 				    (uint8_t *)lun->mode_pages.control_ext_page;
4367 				break;
4368 			default:
4369 				panic("subpage %#x for page %#x is incorrect!",
4370 				      page_index->subpage, page_code);
4371 			}
4372 			break;
4373 		}
4374 		case SMS_INFO_EXCEPTIONS_PAGE: {
4375 			switch (page_index->subpage) {
4376 			case SMS_SUBPAGE_PAGE_0:
4377 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4378 				       &ie_page_default,
4379 				       sizeof(ie_page_default));
4380 				memcpy(&lun->mode_pages.ie_page[
4381 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4382 				       sizeof(ie_page_changeable));
4383 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4384 				       &ie_page_default,
4385 				       sizeof(ie_page_default));
4386 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4387 				       &ie_page_default,
4388 				       sizeof(ie_page_default));
4389 				page_index->page_data =
4390 					(uint8_t *)lun->mode_pages.ie_page;
4391 				break;
4392 			case 0x02: {
4393 				struct ctl_logical_block_provisioning_page *page;
4394 
4395 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4396 				       &lbp_page_default,
4397 				       sizeof(lbp_page_default));
4398 				memcpy(&lun->mode_pages.lbp_page[
4399 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4400 				       sizeof(lbp_page_changeable));
4401 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4402 				       &lbp_page_default,
4403 				       sizeof(lbp_page_default));
4404 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4405 				value = dnvlist_get_string(lun->be_lun->options,
4406 				    "avail-threshold", NULL);
4407 				if (value != NULL &&
4408 				    ctl_expand_number(value, &ival) == 0) {
4409 					page->descr[0].flags |= SLBPPD_ENABLED |
4410 					    SLBPPD_ARMING_DEC;
4411 					if (lun->be_lun->blocksize)
4412 						ival /= lun->be_lun->blocksize;
4413 					else
4414 						ival /= 512;
4415 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4416 					    page->descr[0].count);
4417 				}
4418 				value = dnvlist_get_string(lun->be_lun->options,
4419 				    "used-threshold", NULL);
4420 				if (value != NULL &&
4421 				    ctl_expand_number(value, &ival) == 0) {
4422 					page->descr[1].flags |= SLBPPD_ENABLED |
4423 					    SLBPPD_ARMING_INC;
4424 					if (lun->be_lun->blocksize)
4425 						ival /= lun->be_lun->blocksize;
4426 					else
4427 						ival /= 512;
4428 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4429 					    page->descr[1].count);
4430 				}
4431 				value = dnvlist_get_string(lun->be_lun->options,
4432 				    "pool-avail-threshold", NULL);
4433 				if (value != NULL &&
4434 				    ctl_expand_number(value, &ival) == 0) {
4435 					page->descr[2].flags |= SLBPPD_ENABLED |
4436 					    SLBPPD_ARMING_DEC;
4437 					if (lun->be_lun->blocksize)
4438 						ival /= lun->be_lun->blocksize;
4439 					else
4440 						ival /= 512;
4441 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4442 					    page->descr[2].count);
4443 				}
4444 				value = dnvlist_get_string(lun->be_lun->options,
4445 				    "pool-used-threshold", NULL);
4446 				if (value != NULL &&
4447 				    ctl_expand_number(value, &ival) == 0) {
4448 					page->descr[3].flags |= SLBPPD_ENABLED |
4449 					    SLBPPD_ARMING_INC;
4450 					if (lun->be_lun->blocksize)
4451 						ival /= lun->be_lun->blocksize;
4452 					else
4453 						ival /= 512;
4454 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4455 					    page->descr[3].count);
4456 				}
4457 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4458 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4459 				       sizeof(lbp_page_default));
4460 				page_index->page_data =
4461 					(uint8_t *)lun->mode_pages.lbp_page;
4462 				break;
4463 			}
4464 			default:
4465 				panic("subpage %#x for page %#x is incorrect!",
4466 				      page_index->subpage, page_code);
4467 			}
4468 			break;
4469 		}
4470 		case SMS_CDDVD_CAPS_PAGE:{
4471 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4472 			    ("subpage %#x for page %#x is incorrect!",
4473 			    page_index->subpage, page_code));
4474 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4475 			       &cddvd_page_default,
4476 			       sizeof(cddvd_page_default));
4477 			memcpy(&lun->mode_pages.cddvd_page[
4478 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4479 			       sizeof(cddvd_page_changeable));
4480 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4481 			       &cddvd_page_default,
4482 			       sizeof(cddvd_page_default));
4483 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4484 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4485 			       sizeof(cddvd_page_default));
4486 			page_index->page_data =
4487 				(uint8_t *)lun->mode_pages.cddvd_page;
4488 			break;
4489 		}
4490 		default:
4491 			panic("invalid page code value %#x", page_code);
4492 		}
4493 	}
4494 
4495 	return (CTL_RETVAL_COMPLETE);
4496 }
4497 
4498 static int
4499 ctl_init_log_page_index(struct ctl_lun *lun)
4500 {
4501 	struct ctl_page_index *page_index;
4502 	int i, j, k, prev;
4503 
4504 	memcpy(&lun->log_pages.index, log_page_index_template,
4505 	       sizeof(log_page_index_template));
4506 
4507 	prev = -1;
4508 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4509 		page_index = &lun->log_pages.index[i];
4510 		if (lun->be_lun->lun_type == T_DIRECT &&
4511 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4512 			continue;
4513 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4514 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4515 			continue;
4516 		if (lun->be_lun->lun_type == T_CDROM &&
4517 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4518 			continue;
4519 
4520 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4521 		    lun->backend->lun_attr == NULL)
4522 			continue;
4523 
4524 		if (page_index->page_code != prev) {
4525 			lun->log_pages.pages_page[j] = page_index->page_code;
4526 			prev = page_index->page_code;
4527 			j++;
4528 		}
4529 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4530 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4531 		k++;
4532 	}
4533 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4534 	lun->log_pages.index[0].page_len = j;
4535 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4536 	lun->log_pages.index[1].page_len = k * 2;
4537 	lun->log_pages.index[2].page_data = (uint8_t *)&lun->log_pages.temp_page;
4538 	lun->log_pages.index[2].page_len = sizeof(lun->log_pages.temp_page);
4539 	lun->log_pages.index[3].page_data = &lun->log_pages.lbp_page[0];
4540 	lun->log_pages.index[3].page_len = 12*CTL_NUM_LBP_PARAMS;
4541 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.stat_page;
4542 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.stat_page);
4543 	lun->log_pages.index[5].page_data = (uint8_t *)&lun->log_pages.ie_page;
4544 	lun->log_pages.index[5].page_len = sizeof(lun->log_pages.ie_page);
4545 
4546 	return (CTL_RETVAL_COMPLETE);
4547 }
4548 
4549 static int
4550 hex2bin(const char *str, uint8_t *buf, int buf_size)
4551 {
4552 	int i;
4553 	u_char c;
4554 
4555 	memset(buf, 0, buf_size);
4556 	while (isspace(str[0]))
4557 		str++;
4558 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4559 		str += 2;
4560 	buf_size *= 2;
4561 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4562 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4563 			str++;
4564 		c = str[i];
4565 		if (isdigit(c))
4566 			c -= '0';
4567 		else if (isalpha(c))
4568 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4569 		else
4570 			break;
4571 		if (c >= 16)
4572 			break;
4573 		if ((i & 1) == 0)
4574 			buf[i / 2] |= (c << 4);
4575 		else
4576 			buf[i / 2] |= c;
4577 	}
4578 	return ((i + 1) / 2);
4579 }
4580 
4581 /*
4582  * Add LUN.
4583  *
4584  * Returns 0 for success, non-zero (errno) for failure.
4585  */
4586 int
4587 ctl_add_lun(struct ctl_be_lun *be_lun)
4588 {
4589 	struct ctl_softc *ctl_softc = control_softc;
4590 	struct ctl_lun *nlun, *lun;
4591 	struct scsi_vpd_id_descriptor *desc;
4592 	struct scsi_vpd_id_t10 *t10id;
4593 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4594 	int lun_number;
4595 	int devidlen, idlen1, idlen2 = 0, len;
4596 
4597 	/*
4598 	 * We support only Direct Access, CD-ROM or Processor LUN types.
4599 	 */
4600 	switch (be_lun->lun_type) {
4601 	case T_DIRECT:
4602 	case T_PROCESSOR:
4603 	case T_CDROM:
4604 		break;
4605 	case T_SEQUENTIAL:
4606 	case T_CHANGER:
4607 	default:
4608 		return (EINVAL);
4609 	}
4610 	lun = malloc(sizeof(*lun), M_CTL, M_WAITOK | M_ZERO);
4611 
4612 	lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4613 	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4614 	lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4615 	    M_DEVBUF, M_WAITOK | M_ZERO);
4616 	lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4617 	    M_DEVBUF, M_WAITOK | M_ZERO);
4618 
4619 	/* Generate LUN ID. */
4620 	devidlen = max(CTL_DEVID_MIN_LEN,
4621 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4622 	idlen1 = sizeof(*t10id) + devidlen;
4623 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4624 	scsiname = dnvlist_get_string(be_lun->options, "scsiname", NULL);
4625 	if (scsiname != NULL) {
4626 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4627 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4628 	}
4629 	eui = dnvlist_get_string(be_lun->options, "eui", NULL);
4630 	if (eui != NULL) {
4631 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4632 	}
4633 	naa = dnvlist_get_string(be_lun->options, "naa", NULL);
4634 	if (naa != NULL) {
4635 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4636 	}
4637 	uuid = dnvlist_get_string(be_lun->options, "uuid", NULL);
4638 	if (uuid != NULL) {
4639 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4640 	}
4641 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4642 	    M_CTL, M_WAITOK | M_ZERO);
4643 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4644 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4645 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4646 	desc->length = idlen1;
4647 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4648 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4649 	if ((vendor = dnvlist_get_string(be_lun->options, "vendor", NULL)) == NULL) {
4650 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4651 	} else {
4652 		strncpy(t10id->vendor, vendor,
4653 		    min(sizeof(t10id->vendor), strlen(vendor)));
4654 	}
4655 	strncpy((char *)t10id->vendor_spec_id,
4656 	    (char *)be_lun->device_id, devidlen);
4657 	if (scsiname != NULL) {
4658 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4659 		    desc->length);
4660 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4661 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4662 		    SVPD_ID_TYPE_SCSI_NAME;
4663 		desc->length = idlen2;
4664 		strlcpy(desc->identifier, scsiname, idlen2);
4665 	}
4666 	if (eui != NULL) {
4667 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4668 		    desc->length);
4669 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4670 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4671 		    SVPD_ID_TYPE_EUI64;
4672 		desc->length = hex2bin(eui, desc->identifier, 16);
4673 		desc->length = desc->length > 12 ? 16 :
4674 		    (desc->length > 8 ? 12 : 8);
4675 		len -= 16 - desc->length;
4676 	}
4677 	if (naa != NULL) {
4678 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4679 		    desc->length);
4680 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4681 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4682 		    SVPD_ID_TYPE_NAA;
4683 		desc->length = hex2bin(naa, desc->identifier, 16);
4684 		desc->length = desc->length > 8 ? 16 : 8;
4685 		len -= 16 - desc->length;
4686 	}
4687 	if (uuid != NULL) {
4688 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4689 		    desc->length);
4690 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4691 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4692 		    SVPD_ID_TYPE_UUID;
4693 		desc->identifier[0] = 0x10;
4694 		hex2bin(uuid, &desc->identifier[2], 16);
4695 		desc->length = 18;
4696 	}
4697 	lun->lun_devid->len = len;
4698 
4699 	mtx_lock(&ctl_softc->ctl_lock);
4700 	/*
4701 	 * See if the caller requested a particular LUN number.  If so, see
4702 	 * if it is available.  Otherwise, allocate the first available LUN.
4703 	 */
4704 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4705 		if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4706 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4707 			mtx_unlock(&ctl_softc->ctl_lock);
4708 			if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4709 				printf("ctl: requested LUN ID %d is higher "
4710 				       "than ctl_max_luns - 1 (%d)\n",
4711 				       be_lun->req_lun_id, ctl_max_luns - 1);
4712 			} else {
4713 				/*
4714 				 * XXX KDM return an error, or just assign
4715 				 * another LUN ID in this case??
4716 				 */
4717 				printf("ctl: requested LUN ID %d is already "
4718 				       "in use\n", be_lun->req_lun_id);
4719 			}
4720 fail:
4721 			free(lun->lun_devid, M_CTL);
4722 			free(lun, M_CTL);
4723 			return (ENOSPC);
4724 		}
4725 		lun_number = be_lun->req_lun_id;
4726 	} else {
4727 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4728 		if (lun_number == -1) {
4729 			mtx_unlock(&ctl_softc->ctl_lock);
4730 			printf("ctl: can't allocate LUN, out of LUNs\n");
4731 			goto fail;
4732 		}
4733 	}
4734 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4735 	mtx_unlock(&ctl_softc->ctl_lock);
4736 
4737 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4738 	lun->lun = lun_number;
4739 	lun->be_lun = be_lun;
4740 	/*
4741 	 * The processor LUN is always enabled.  Disk LUNs come on line
4742 	 * disabled, and must be enabled by the backend.
4743 	 */
4744 	lun->flags |= CTL_LUN_DISABLED;
4745 	lun->backend = be_lun->be;
4746 	be_lun->ctl_lun = lun;
4747 	be_lun->lun_id = lun_number;
4748 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4749 		lun->flags |= CTL_LUN_EJECTED;
4750 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4751 		lun->flags |= CTL_LUN_NO_MEDIA;
4752 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4753 		lun->flags |= CTL_LUN_STOPPED;
4754 
4755 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4756 		lun->flags |= CTL_LUN_PRIMARY_SC;
4757 
4758 	value = dnvlist_get_string(be_lun->options, "removable", NULL);
4759 	if (value != NULL) {
4760 		if (strcmp(value, "on") == 0)
4761 			lun->flags |= CTL_LUN_REMOVABLE;
4762 	} else if (be_lun->lun_type == T_CDROM)
4763 		lun->flags |= CTL_LUN_REMOVABLE;
4764 
4765 	lun->ctl_softc = ctl_softc;
4766 #ifdef CTL_TIME_IO
4767 	lun->last_busy = getsbinuptime();
4768 #endif
4769 	LIST_INIT(&lun->ooa_queue);
4770 	STAILQ_INIT(&lun->error_list);
4771 	lun->ie_reported = 1;
4772 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4773 	ctl_tpc_lun_init(lun);
4774 	if (lun->flags & CTL_LUN_REMOVABLE) {
4775 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4776 		    M_CTL, M_WAITOK);
4777 	}
4778 
4779 	/*
4780 	 * Initialize the mode and log page index.
4781 	 */
4782 	ctl_init_page_index(lun);
4783 	ctl_init_log_page_index(lun);
4784 
4785 	/* Setup statistics gathering */
4786 	lun->stats.item = lun_number;
4787 
4788 	/*
4789 	 * Now, before we insert this lun on the lun list, set the lun
4790 	 * inventory changed UA for all other luns.
4791 	 */
4792 	mtx_lock(&ctl_softc->ctl_lock);
4793 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4794 		mtx_lock(&nlun->lun_lock);
4795 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4796 		mtx_unlock(&nlun->lun_lock);
4797 	}
4798 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4799 	ctl_softc->ctl_luns[lun_number] = lun;
4800 	ctl_softc->num_luns++;
4801 	mtx_unlock(&ctl_softc->ctl_lock);
4802 
4803 	/*
4804 	 * We successfully added the LUN, attempt to enable it.
4805 	 */
4806 	if (ctl_enable_lun(lun) != 0) {
4807 		printf("%s: ctl_enable_lun() failed!\n", __func__);
4808 		mtx_lock(&ctl_softc->ctl_lock);
4809 		STAILQ_REMOVE(&ctl_softc->lun_list, lun, ctl_lun, links);
4810 		ctl_clear_mask(ctl_softc->ctl_lun_mask, lun_number);
4811 		ctl_softc->ctl_luns[lun_number] = NULL;
4812 		ctl_softc->num_luns--;
4813 		mtx_unlock(&ctl_softc->ctl_lock);
4814 		free(lun->lun_devid, M_CTL);
4815 		free(lun, M_CTL);
4816 		return (EIO);
4817 	}
4818 
4819 	return (0);
4820 }
4821 
4822 /*
4823  * Free LUN that has no active requests.
4824  */
4825 static int
4826 ctl_free_lun(struct ctl_lun *lun)
4827 {
4828 	struct ctl_softc *softc = lun->ctl_softc;
4829 	struct ctl_lun *nlun;
4830 	int i;
4831 
4832 	KASSERT(LIST_EMPTY(&lun->ooa_queue),
4833 	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4834 
4835 	mtx_lock(&softc->ctl_lock);
4836 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4837 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4838 	softc->ctl_luns[lun->lun] = NULL;
4839 	softc->num_luns--;
4840 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4841 		mtx_lock(&nlun->lun_lock);
4842 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4843 		mtx_unlock(&nlun->lun_lock);
4844 	}
4845 	mtx_unlock(&softc->ctl_lock);
4846 
4847 	/*
4848 	 * Tell the backend to free resources, if this LUN has a backend.
4849 	 */
4850 	lun->be_lun->lun_shutdown(lun->be_lun);
4851 
4852 	lun->ie_reportcnt = UINT32_MAX;
4853 	callout_drain(&lun->ie_callout);
4854 	ctl_tpc_lun_shutdown(lun);
4855 	mtx_destroy(&lun->lun_lock);
4856 	free(lun->lun_devid, M_CTL);
4857 	for (i = 0; i < ctl_max_ports; i++)
4858 		free(lun->pending_ua[i], M_CTL);
4859 	free(lun->pending_ua, M_DEVBUF);
4860 	for (i = 0; i < ctl_max_ports; i++)
4861 		free(lun->pr_keys[i], M_CTL);
4862 	free(lun->pr_keys, M_DEVBUF);
4863 	free(lun->write_buffer, M_CTL);
4864 	free(lun->prevent, M_CTL);
4865 	free(lun, M_CTL);
4866 
4867 	return (0);
4868 }
4869 
4870 static int
4871 ctl_enable_lun(struct ctl_lun *lun)
4872 {
4873 	struct ctl_softc *softc;
4874 	struct ctl_port *port, *nport;
4875 	int retval;
4876 
4877 	softc = lun->ctl_softc;
4878 
4879 	mtx_lock(&softc->ctl_lock);
4880 	mtx_lock(&lun->lun_lock);
4881 	KASSERT((lun->flags & CTL_LUN_DISABLED) != 0,
4882 	    ("%s: LUN not disabled", __func__));
4883 	lun->flags &= ~CTL_LUN_DISABLED;
4884 	mtx_unlock(&lun->lun_lock);
4885 
4886 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4887 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4888 		    port->lun_map != NULL || port->lun_enable == NULL)
4889 			continue;
4890 
4891 		/*
4892 		 * Drop the lock while we call the FETD's enable routine.
4893 		 * This can lead to a callback into CTL (at least in the
4894 		 * case of the internal initiator frontend.
4895 		 */
4896 		mtx_unlock(&softc->ctl_lock);
4897 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4898 		mtx_lock(&softc->ctl_lock);
4899 		if (retval != 0) {
4900 			printf("%s: FETD %s port %d returned error "
4901 			       "%d for lun_enable on lun %jd\n",
4902 			       __func__, port->port_name, port->targ_port,
4903 			       retval, (intmax_t)lun->lun);
4904 		}
4905 	}
4906 
4907 	mtx_unlock(&softc->ctl_lock);
4908 	ctl_isc_announce_lun(lun);
4909 
4910 	return (0);
4911 }
4912 
4913 static int
4914 ctl_disable_lun(struct ctl_lun *lun)
4915 {
4916 	struct ctl_softc *softc;
4917 	struct ctl_port *port;
4918 	int retval;
4919 
4920 	softc = lun->ctl_softc;
4921 
4922 	mtx_lock(&softc->ctl_lock);
4923 	mtx_lock(&lun->lun_lock);
4924 	KASSERT((lun->flags & CTL_LUN_DISABLED) == 0,
4925 	    ("%s: LUN not enabled", __func__));
4926 	lun->flags |= CTL_LUN_DISABLED;
4927 	mtx_unlock(&lun->lun_lock);
4928 
4929 	STAILQ_FOREACH(port, &softc->port_list, links) {
4930 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4931 		    port->lun_map != NULL || port->lun_disable == NULL)
4932 			continue;
4933 
4934 		/*
4935 		 * Drop the lock before we call the frontend's disable
4936 		 * routine, to avoid lock order reversals.
4937 		 *
4938 		 * XXX KDM what happens if the frontend list changes while
4939 		 * we're traversing it?  It's unlikely, but should be handled.
4940 		 */
4941 		mtx_unlock(&softc->ctl_lock);
4942 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4943 		mtx_lock(&softc->ctl_lock);
4944 		if (retval != 0) {
4945 			printf("%s: FETD %s port %d returned error "
4946 			       "%d for lun_disable on lun %jd\n",
4947 			       __func__, port->port_name, port->targ_port,
4948 			       retval, (intmax_t)lun->lun);
4949 		}
4950 	}
4951 
4952 	mtx_unlock(&softc->ctl_lock);
4953 	ctl_isc_announce_lun(lun);
4954 
4955 	return (0);
4956 }
4957 
4958 int
4959 ctl_start_lun(struct ctl_be_lun *be_lun)
4960 {
4961 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4962 
4963 	mtx_lock(&lun->lun_lock);
4964 	lun->flags &= ~CTL_LUN_STOPPED;
4965 	mtx_unlock(&lun->lun_lock);
4966 	return (0);
4967 }
4968 
4969 int
4970 ctl_stop_lun(struct ctl_be_lun *be_lun)
4971 {
4972 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4973 
4974 	mtx_lock(&lun->lun_lock);
4975 	lun->flags |= CTL_LUN_STOPPED;
4976 	mtx_unlock(&lun->lun_lock);
4977 	return (0);
4978 }
4979 
4980 int
4981 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4982 {
4983 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4984 
4985 	mtx_lock(&lun->lun_lock);
4986 	lun->flags |= CTL_LUN_NO_MEDIA;
4987 	mtx_unlock(&lun->lun_lock);
4988 	return (0);
4989 }
4990 
4991 int
4992 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4993 {
4994 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4995 	union ctl_ha_msg msg;
4996 
4997 	mtx_lock(&lun->lun_lock);
4998 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4999 	if (lun->flags & CTL_LUN_REMOVABLE)
5000 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
5001 	mtx_unlock(&lun->lun_lock);
5002 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
5003 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5004 		bzero(&msg.ua, sizeof(msg.ua));
5005 		msg.hdr.msg_type = CTL_MSG_UA;
5006 		msg.hdr.nexus.initid = -1;
5007 		msg.hdr.nexus.targ_port = -1;
5008 		msg.hdr.nexus.targ_lun = lun->lun;
5009 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5010 		msg.ua.ua_all = 1;
5011 		msg.ua.ua_set = 1;
5012 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
5013 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5014 		    M_WAITOK);
5015 	}
5016 	return (0);
5017 }
5018 
5019 int
5020 ctl_lun_ejected(struct ctl_be_lun *be_lun)
5021 {
5022 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5023 
5024 	mtx_lock(&lun->lun_lock);
5025 	lun->flags |= CTL_LUN_EJECTED;
5026 	mtx_unlock(&lun->lun_lock);
5027 	return (0);
5028 }
5029 
5030 int
5031 ctl_lun_primary(struct ctl_be_lun *be_lun)
5032 {
5033 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5034 
5035 	mtx_lock(&lun->lun_lock);
5036 	lun->flags |= CTL_LUN_PRIMARY_SC;
5037 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5038 	mtx_unlock(&lun->lun_lock);
5039 	ctl_isc_announce_lun(lun);
5040 	return (0);
5041 }
5042 
5043 int
5044 ctl_lun_secondary(struct ctl_be_lun *be_lun)
5045 {
5046 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5047 
5048 	mtx_lock(&lun->lun_lock);
5049 	lun->flags &= ~CTL_LUN_PRIMARY_SC;
5050 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5051 	mtx_unlock(&lun->lun_lock);
5052 	ctl_isc_announce_lun(lun);
5053 	return (0);
5054 }
5055 
5056 /*
5057  * Remove LUN.  If there are active requests, wait for completion.
5058  *
5059  * Returns 0 for success, non-zero (errno) for failure.
5060  * Completion is reported to backed via the lun_shutdown() method.
5061  */
5062 int
5063 ctl_remove_lun(struct ctl_be_lun *be_lun)
5064 {
5065 	struct ctl_lun *lun;
5066 
5067 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5068 
5069 	ctl_disable_lun(lun);
5070 
5071 	mtx_lock(&lun->lun_lock);
5072 	lun->flags |= CTL_LUN_INVALID;
5073 
5074 	/*
5075 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5076 	 * If we have something in the OOA queue, we'll free it when the
5077 	 * last I/O completes.
5078 	 */
5079 	if (LIST_EMPTY(&lun->ooa_queue)) {
5080 		mtx_unlock(&lun->lun_lock);
5081 		ctl_free_lun(lun);
5082 	} else
5083 		mtx_unlock(&lun->lun_lock);
5084 
5085 	return (0);
5086 }
5087 
5088 void
5089 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5090 {
5091 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5092 	union ctl_ha_msg msg;
5093 
5094 	mtx_lock(&lun->lun_lock);
5095 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5096 	mtx_unlock(&lun->lun_lock);
5097 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5098 		/* Send msg to other side. */
5099 		bzero(&msg.ua, sizeof(msg.ua));
5100 		msg.hdr.msg_type = CTL_MSG_UA;
5101 		msg.hdr.nexus.initid = -1;
5102 		msg.hdr.nexus.targ_port = -1;
5103 		msg.hdr.nexus.targ_lun = lun->lun;
5104 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5105 		msg.ua.ua_all = 1;
5106 		msg.ua.ua_set = 1;
5107 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5108 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5109 		    M_WAITOK);
5110 	}
5111 }
5112 
5113 /*
5114  * Backend "memory move is complete" callback for requests that never
5115  * make it down to say RAIDCore's configuration code.
5116  */
5117 int
5118 ctl_config_move_done(union ctl_io *io, bool samethr)
5119 {
5120 	int retval;
5121 
5122 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5123 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5124 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
5125 
5126 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5127 		ctl_data_print(io);
5128 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5129 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5130 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5131 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5132 		/*
5133 		 * XXX KDM just assuming a single pointer here, and not a
5134 		 * S/G list.  If we start using S/G lists for config data,
5135 		 * we'll need to know how to clean them up here as well.
5136 		 */
5137 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5138 			free(io->scsiio.kern_data_ptr, M_CTL);
5139 		ctl_done(io);
5140 		retval = CTL_RETVAL_COMPLETE;
5141 	} else {
5142 		/*
5143 		 * XXX KDM now we need to continue data movement.  Some
5144 		 * options:
5145 		 * - call ctl_scsiio() again?  We don't do this for data
5146 		 *   writes, because for those at least we know ahead of
5147 		 *   time where the write will go and how long it is.  For
5148 		 *   config writes, though, that information is largely
5149 		 *   contained within the write itself, thus we need to
5150 		 *   parse out the data again.
5151 		 *
5152 		 * - Call some other function once the data is in?
5153 		 */
5154 
5155 		/*
5156 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5157 		 * bits to see whether we're allocated or not.
5158 		 */
5159 		retval = ctl_scsiio(&io->scsiio);
5160 	}
5161 	return (retval);
5162 }
5163 
5164 /*
5165  * This gets called by a backend driver when it is done with a
5166  * data_submit method.
5167  */
5168 void
5169 ctl_data_submit_done(union ctl_io *io)
5170 {
5171 	/*
5172 	 * If the IO_CONT flag is set, we need to call the supplied
5173 	 * function to continue processing the I/O, instead of completing
5174 	 * the I/O just yet.
5175 	 *
5176 	 * If there is an error, though, we don't want to keep processing.
5177 	 * Instead, just send status back to the initiator.
5178 	 */
5179 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5180 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5181 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5182 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5183 		io->scsiio.io_cont(io);
5184 		return;
5185 	}
5186 	ctl_done(io);
5187 }
5188 
5189 /*
5190  * This gets called by a backend driver when it is done with a
5191  * configuration write.
5192  */
5193 void
5194 ctl_config_write_done(union ctl_io *io)
5195 {
5196 	uint8_t *buf;
5197 
5198 	/*
5199 	 * If the IO_CONT flag is set, we need to call the supplied
5200 	 * function to continue processing the I/O, instead of completing
5201 	 * the I/O just yet.
5202 	 *
5203 	 * If there is an error, though, we don't want to keep processing.
5204 	 * Instead, just send status back to the initiator.
5205 	 */
5206 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5207 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5208 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5209 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5210 		io->scsiio.io_cont(io);
5211 		return;
5212 	}
5213 	/*
5214 	 * Since a configuration write can be done for commands that actually
5215 	 * have data allocated, like write buffer, and commands that have
5216 	 * no data, like start/stop unit, we need to check here.
5217 	 */
5218 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5219 		buf = io->scsiio.kern_data_ptr;
5220 	else
5221 		buf = NULL;
5222 	ctl_done(io);
5223 	if (buf)
5224 		free(buf, M_CTL);
5225 }
5226 
5227 void
5228 ctl_config_read_done(union ctl_io *io)
5229 {
5230 	uint8_t *buf;
5231 
5232 	/*
5233 	 * If there is some error -- we are done, skip data transfer.
5234 	 */
5235 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5236 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5237 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5238 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5239 			buf = io->scsiio.kern_data_ptr;
5240 		else
5241 			buf = NULL;
5242 		ctl_done(io);
5243 		if (buf)
5244 			free(buf, M_CTL);
5245 		return;
5246 	}
5247 
5248 	/*
5249 	 * If the IO_CONT flag is set, we need to call the supplied
5250 	 * function to continue processing the I/O, instead of completing
5251 	 * the I/O just yet.
5252 	 */
5253 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5254 		io->scsiio.io_cont(io);
5255 		return;
5256 	}
5257 
5258 	ctl_datamove(io);
5259 }
5260 
5261 /*
5262  * SCSI release command.
5263  */
5264 int
5265 ctl_scsi_release(struct ctl_scsiio *ctsio)
5266 {
5267 	struct ctl_lun *lun = CTL_LUN(ctsio);
5268 	uint32_t residx;
5269 
5270 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5271 
5272 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5273 
5274 	/*
5275 	 * XXX KDM right now, we only support LUN reservation.  We don't
5276 	 * support 3rd party reservations, or extent reservations, which
5277 	 * might actually need the parameter list.  If we've gotten this
5278 	 * far, we've got a LUN reservation.  Anything else got kicked out
5279 	 * above.  So, according to SPC, ignore the length.
5280 	 */
5281 
5282 	mtx_lock(&lun->lun_lock);
5283 
5284 	/*
5285 	 * According to SPC, it is not an error for an intiator to attempt
5286 	 * to release a reservation on a LUN that isn't reserved, or that
5287 	 * is reserved by another initiator.  The reservation can only be
5288 	 * released, though, by the initiator who made it or by one of
5289 	 * several reset type events.
5290 	 */
5291 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5292 			lun->flags &= ~CTL_LUN_RESERVED;
5293 
5294 	mtx_unlock(&lun->lun_lock);
5295 
5296 	ctl_set_success(ctsio);
5297 	ctl_done((union ctl_io *)ctsio);
5298 	return (CTL_RETVAL_COMPLETE);
5299 }
5300 
5301 int
5302 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5303 {
5304 	struct ctl_lun *lun = CTL_LUN(ctsio);
5305 	uint32_t residx;
5306 
5307 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5308 
5309 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5310 
5311 	/*
5312 	 * XXX KDM right now, we only support LUN reservation.  We don't
5313 	 * support 3rd party reservations, or extent reservations, which
5314 	 * might actually need the parameter list.  If we've gotten this
5315 	 * far, we've got a LUN reservation.  Anything else got kicked out
5316 	 * above.  So, according to SPC, ignore the length.
5317 	 */
5318 
5319 	mtx_lock(&lun->lun_lock);
5320 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5321 		ctl_set_reservation_conflict(ctsio);
5322 		goto bailout;
5323 	}
5324 
5325 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5326 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5327 		ctl_set_success(ctsio);
5328 		goto bailout;
5329 	}
5330 
5331 	lun->flags |= CTL_LUN_RESERVED;
5332 	lun->res_idx = residx;
5333 	ctl_set_success(ctsio);
5334 
5335 bailout:
5336 	mtx_unlock(&lun->lun_lock);
5337 	ctl_done((union ctl_io *)ctsio);
5338 	return (CTL_RETVAL_COMPLETE);
5339 }
5340 
5341 int
5342 ctl_start_stop(struct ctl_scsiio *ctsio)
5343 {
5344 	struct ctl_lun *lun = CTL_LUN(ctsio);
5345 	struct scsi_start_stop_unit *cdb;
5346 	int retval;
5347 
5348 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5349 
5350 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5351 
5352 	if ((cdb->how & SSS_PC_MASK) == 0) {
5353 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5354 		    (cdb->how & SSS_START) == 0) {
5355 			uint32_t residx;
5356 
5357 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5358 			if (ctl_get_prkey(lun, residx) == 0 ||
5359 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5360 				ctl_set_reservation_conflict(ctsio);
5361 				ctl_done((union ctl_io *)ctsio);
5362 				return (CTL_RETVAL_COMPLETE);
5363 			}
5364 		}
5365 
5366 		if ((cdb->how & SSS_LOEJ) &&
5367 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5368 			ctl_set_invalid_field(ctsio,
5369 					      /*sks_valid*/ 1,
5370 					      /*command*/ 1,
5371 					      /*field*/ 4,
5372 					      /*bit_valid*/ 1,
5373 					      /*bit*/ 1);
5374 			ctl_done((union ctl_io *)ctsio);
5375 			return (CTL_RETVAL_COMPLETE);
5376 		}
5377 
5378 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5379 		    lun->prevent_count > 0) {
5380 			/* "Medium removal prevented" */
5381 			ctl_set_sense(ctsio, /*current_error*/ 1,
5382 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5383 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5384 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5385 			ctl_done((union ctl_io *)ctsio);
5386 			return (CTL_RETVAL_COMPLETE);
5387 		}
5388 	}
5389 
5390 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5391 	return (retval);
5392 }
5393 
5394 int
5395 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5396 {
5397 	struct ctl_lun *lun = CTL_LUN(ctsio);
5398 	struct scsi_prevent *cdb;
5399 	int retval;
5400 	uint32_t initidx;
5401 
5402 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5403 
5404 	cdb = (struct scsi_prevent *)ctsio->cdb;
5405 
5406 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5407 		ctl_set_invalid_opcode(ctsio);
5408 		ctl_done((union ctl_io *)ctsio);
5409 		return (CTL_RETVAL_COMPLETE);
5410 	}
5411 
5412 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5413 	mtx_lock(&lun->lun_lock);
5414 	if ((cdb->how & PR_PREVENT) &&
5415 	    ctl_is_set(lun->prevent, initidx) == 0) {
5416 		ctl_set_mask(lun->prevent, initidx);
5417 		lun->prevent_count++;
5418 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5419 	    ctl_is_set(lun->prevent, initidx)) {
5420 		ctl_clear_mask(lun->prevent, initidx);
5421 		lun->prevent_count--;
5422 	}
5423 	mtx_unlock(&lun->lun_lock);
5424 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5425 	return (retval);
5426 }
5427 
5428 /*
5429  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5430  * we don't really do anything with the LBA and length fields if the user
5431  * passes them in.  Instead we'll just flush out the cache for the entire
5432  * LUN.
5433  */
5434 int
5435 ctl_sync_cache(struct ctl_scsiio *ctsio)
5436 {
5437 	struct ctl_lun *lun = CTL_LUN(ctsio);
5438 	struct ctl_lba_len_flags *lbalen;
5439 	uint64_t starting_lba;
5440 	uint32_t block_count;
5441 	int retval;
5442 	uint8_t byte2;
5443 
5444 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5445 
5446 	retval = 0;
5447 
5448 	switch (ctsio->cdb[0]) {
5449 	case SYNCHRONIZE_CACHE: {
5450 		struct scsi_sync_cache *cdb;
5451 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5452 
5453 		starting_lba = scsi_4btoul(cdb->begin_lba);
5454 		block_count = scsi_2btoul(cdb->lb_count);
5455 		byte2 = cdb->byte2;
5456 		break;
5457 	}
5458 	case SYNCHRONIZE_CACHE_16: {
5459 		struct scsi_sync_cache_16 *cdb;
5460 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5461 
5462 		starting_lba = scsi_8btou64(cdb->begin_lba);
5463 		block_count = scsi_4btoul(cdb->lb_count);
5464 		byte2 = cdb->byte2;
5465 		break;
5466 	}
5467 	default:
5468 		ctl_set_invalid_opcode(ctsio);
5469 		ctl_done((union ctl_io *)ctsio);
5470 		goto bailout;
5471 		break; /* NOTREACHED */
5472 	}
5473 
5474 	/*
5475 	 * We check the LBA and length, but don't do anything with them.
5476 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5477 	 * get flushed.  This check will just help satisfy anyone who wants
5478 	 * to see an error for an out of range LBA.
5479 	 */
5480 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5481 		ctl_set_lba_out_of_range(ctsio,
5482 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5483 		ctl_done((union ctl_io *)ctsio);
5484 		goto bailout;
5485 	}
5486 
5487 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5488 	lbalen->lba = starting_lba;
5489 	lbalen->len = block_count;
5490 	lbalen->flags = byte2;
5491 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5492 
5493 bailout:
5494 	return (retval);
5495 }
5496 
5497 int
5498 ctl_format(struct ctl_scsiio *ctsio)
5499 {
5500 	struct scsi_format *cdb;
5501 	int length, defect_list_len;
5502 
5503 	CTL_DEBUG_PRINT(("ctl_format\n"));
5504 
5505 	cdb = (struct scsi_format *)ctsio->cdb;
5506 
5507 	length = 0;
5508 	if (cdb->byte2 & SF_FMTDATA) {
5509 		if (cdb->byte2 & SF_LONGLIST)
5510 			length = sizeof(struct scsi_format_header_long);
5511 		else
5512 			length = sizeof(struct scsi_format_header_short);
5513 	}
5514 
5515 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5516 	 && (length > 0)) {
5517 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5518 		ctsio->kern_data_len = length;
5519 		ctsio->kern_total_len = length;
5520 		ctsio->kern_rel_offset = 0;
5521 		ctsio->kern_sg_entries = 0;
5522 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5523 		ctsio->be_move_done = ctl_config_move_done;
5524 		ctl_datamove((union ctl_io *)ctsio);
5525 
5526 		return (CTL_RETVAL_COMPLETE);
5527 	}
5528 
5529 	defect_list_len = 0;
5530 
5531 	if (cdb->byte2 & SF_FMTDATA) {
5532 		if (cdb->byte2 & SF_LONGLIST) {
5533 			struct scsi_format_header_long *header;
5534 
5535 			header = (struct scsi_format_header_long *)
5536 				ctsio->kern_data_ptr;
5537 
5538 			defect_list_len = scsi_4btoul(header->defect_list_len);
5539 			if (defect_list_len != 0) {
5540 				ctl_set_invalid_field(ctsio,
5541 						      /*sks_valid*/ 1,
5542 						      /*command*/ 0,
5543 						      /*field*/ 2,
5544 						      /*bit_valid*/ 0,
5545 						      /*bit*/ 0);
5546 				goto bailout;
5547 			}
5548 		} else {
5549 			struct scsi_format_header_short *header;
5550 
5551 			header = (struct scsi_format_header_short *)
5552 				ctsio->kern_data_ptr;
5553 
5554 			defect_list_len = scsi_2btoul(header->defect_list_len);
5555 			if (defect_list_len != 0) {
5556 				ctl_set_invalid_field(ctsio,
5557 						      /*sks_valid*/ 1,
5558 						      /*command*/ 0,
5559 						      /*field*/ 2,
5560 						      /*bit_valid*/ 0,
5561 						      /*bit*/ 0);
5562 				goto bailout;
5563 			}
5564 		}
5565 	}
5566 
5567 	ctl_set_success(ctsio);
5568 bailout:
5569 
5570 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5571 		free(ctsio->kern_data_ptr, M_CTL);
5572 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5573 	}
5574 
5575 	ctl_done((union ctl_io *)ctsio);
5576 	return (CTL_RETVAL_COMPLETE);
5577 }
5578 
5579 int
5580 ctl_read_buffer(struct ctl_scsiio *ctsio)
5581 {
5582 	struct ctl_lun *lun = CTL_LUN(ctsio);
5583 	uint64_t buffer_offset;
5584 	uint32_t len;
5585 	uint8_t byte2;
5586 	static uint8_t descr[4];
5587 	static uint8_t echo_descr[4] = { 0 };
5588 
5589 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5590 
5591 	switch (ctsio->cdb[0]) {
5592 	case READ_BUFFER: {
5593 		struct scsi_read_buffer *cdb;
5594 
5595 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5596 		buffer_offset = scsi_3btoul(cdb->offset);
5597 		len = scsi_3btoul(cdb->length);
5598 		byte2 = cdb->byte2;
5599 		break;
5600 	}
5601 	case READ_BUFFER_16: {
5602 		struct scsi_read_buffer_16 *cdb;
5603 
5604 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5605 		buffer_offset = scsi_8btou64(cdb->offset);
5606 		len = scsi_4btoul(cdb->length);
5607 		byte2 = cdb->byte2;
5608 		break;
5609 	}
5610 	default: /* This shouldn't happen. */
5611 		ctl_set_invalid_opcode(ctsio);
5612 		ctl_done((union ctl_io *)ctsio);
5613 		return (CTL_RETVAL_COMPLETE);
5614 	}
5615 
5616 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5617 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5618 		ctl_set_invalid_field(ctsio,
5619 				      /*sks_valid*/ 1,
5620 				      /*command*/ 1,
5621 				      /*field*/ 6,
5622 				      /*bit_valid*/ 0,
5623 				      /*bit*/ 0);
5624 		ctl_done((union ctl_io *)ctsio);
5625 		return (CTL_RETVAL_COMPLETE);
5626 	}
5627 
5628 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5629 		descr[0] = 0;
5630 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5631 		ctsio->kern_data_ptr = descr;
5632 		len = min(len, sizeof(descr));
5633 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5634 		ctsio->kern_data_ptr = echo_descr;
5635 		len = min(len, sizeof(echo_descr));
5636 	} else {
5637 		if (lun->write_buffer == NULL) {
5638 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5639 			    M_CTL, M_WAITOK);
5640 		}
5641 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5642 	}
5643 	ctsio->kern_data_len = len;
5644 	ctsio->kern_total_len = len;
5645 	ctsio->kern_rel_offset = 0;
5646 	ctsio->kern_sg_entries = 0;
5647 	ctl_set_success(ctsio);
5648 	ctsio->be_move_done = ctl_config_move_done;
5649 	ctl_datamove((union ctl_io *)ctsio);
5650 	return (CTL_RETVAL_COMPLETE);
5651 }
5652 
5653 int
5654 ctl_write_buffer(struct ctl_scsiio *ctsio)
5655 {
5656 	struct ctl_lun *lun = CTL_LUN(ctsio);
5657 	struct scsi_write_buffer *cdb;
5658 	int buffer_offset, len;
5659 
5660 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5661 
5662 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5663 
5664 	len = scsi_3btoul(cdb->length);
5665 	buffer_offset = scsi_3btoul(cdb->offset);
5666 
5667 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5668 		ctl_set_invalid_field(ctsio,
5669 				      /*sks_valid*/ 1,
5670 				      /*command*/ 1,
5671 				      /*field*/ 6,
5672 				      /*bit_valid*/ 0,
5673 				      /*bit*/ 0);
5674 		ctl_done((union ctl_io *)ctsio);
5675 		return (CTL_RETVAL_COMPLETE);
5676 	}
5677 
5678 	/*
5679 	 * If we've got a kernel request that hasn't been malloced yet,
5680 	 * malloc it and tell the caller the data buffer is here.
5681 	 */
5682 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5683 		if (lun->write_buffer == NULL) {
5684 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5685 			    M_CTL, M_WAITOK);
5686 		}
5687 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5688 		ctsio->kern_data_len = len;
5689 		ctsio->kern_total_len = len;
5690 		ctsio->kern_rel_offset = 0;
5691 		ctsio->kern_sg_entries = 0;
5692 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5693 		ctsio->be_move_done = ctl_config_move_done;
5694 		ctl_datamove((union ctl_io *)ctsio);
5695 
5696 		return (CTL_RETVAL_COMPLETE);
5697 	}
5698 
5699 	ctl_set_success(ctsio);
5700 	ctl_done((union ctl_io *)ctsio);
5701 	return (CTL_RETVAL_COMPLETE);
5702 }
5703 
5704 static int
5705 ctl_write_same_cont(union ctl_io *io)
5706 {
5707 	struct ctl_lun *lun = CTL_LUN(io);
5708 	struct ctl_scsiio *ctsio;
5709 	struct ctl_lba_len_flags *lbalen;
5710 	int retval;
5711 
5712 	ctsio = &io->scsiio;
5713 	ctsio->io_hdr.status = CTL_STATUS_NONE;
5714 	lbalen = (struct ctl_lba_len_flags *)
5715 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5716 	lbalen->lba += lbalen->len;
5717 	if ((lun->be_lun->maxlba + 1) - lbalen->lba <= UINT32_MAX) {
5718 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
5719 		lbalen->len = (lun->be_lun->maxlba + 1) - lbalen->lba;
5720 	}
5721 
5722 	CTL_DEBUG_PRINT(("ctl_write_same_cont: calling config_write()\n"));
5723 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5724 	return (retval);
5725 }
5726 
5727 int
5728 ctl_write_same(struct ctl_scsiio *ctsio)
5729 {
5730 	struct ctl_lun *lun = CTL_LUN(ctsio);
5731 	struct ctl_lba_len_flags *lbalen;
5732 	const char *val;
5733 	uint64_t lba, ival;
5734 	uint32_t num_blocks;
5735 	int len, retval;
5736 	uint8_t byte2;
5737 
5738 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5739 
5740 	switch (ctsio->cdb[0]) {
5741 	case WRITE_SAME_10: {
5742 		struct scsi_write_same_10 *cdb;
5743 
5744 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5745 
5746 		lba = scsi_4btoul(cdb->addr);
5747 		num_blocks = scsi_2btoul(cdb->length);
5748 		byte2 = cdb->byte2;
5749 		break;
5750 	}
5751 	case WRITE_SAME_16: {
5752 		struct scsi_write_same_16 *cdb;
5753 
5754 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5755 
5756 		lba = scsi_8btou64(cdb->addr);
5757 		num_blocks = scsi_4btoul(cdb->length);
5758 		byte2 = cdb->byte2;
5759 		break;
5760 	}
5761 	default:
5762 		/*
5763 		 * We got a command we don't support.  This shouldn't
5764 		 * happen, commands should be filtered out above us.
5765 		 */
5766 		ctl_set_invalid_opcode(ctsio);
5767 		ctl_done((union ctl_io *)ctsio);
5768 
5769 		return (CTL_RETVAL_COMPLETE);
5770 		break; /* NOTREACHED */
5771 	}
5772 
5773 	/* ANCHOR flag can be used only together with UNMAP */
5774 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5775 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5776 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5777 		ctl_done((union ctl_io *)ctsio);
5778 		return (CTL_RETVAL_COMPLETE);
5779 	}
5780 
5781 	/*
5782 	 * The first check is to make sure we're in bounds, the second
5783 	 * check is to catch wrap-around problems.  If the lba + num blocks
5784 	 * is less than the lba, then we've wrapped around and the block
5785 	 * range is invalid anyway.
5786 	 */
5787 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5788 	 || ((lba + num_blocks) < lba)) {
5789 		ctl_set_lba_out_of_range(ctsio,
5790 		    MAX(lba, lun->be_lun->maxlba + 1));
5791 		ctl_done((union ctl_io *)ctsio);
5792 		return (CTL_RETVAL_COMPLETE);
5793 	}
5794 
5795 	/* Zero number of blocks means "to the last logical block" */
5796 	if (num_blocks == 0) {
5797 		ival = UINT64_MAX;
5798 		val = dnvlist_get_string(lun->be_lun->options,
5799 		    "write_same_max_lba", NULL);
5800 		if (val != NULL)
5801 			ctl_expand_number(val, &ival);
5802 		if ((lun->be_lun->maxlba + 1) - lba > ival) {
5803 			ctl_set_invalid_field(ctsio,
5804 			    /*sks_valid*/ 1, /*command*/ 1,
5805 			    /*field*/ ctsio->cdb[0] == WRITE_SAME_10 ? 7 : 10,
5806 			    /*bit_valid*/ 0, /*bit*/ 0);
5807 			ctl_done((union ctl_io *)ctsio);
5808 			return (CTL_RETVAL_COMPLETE);
5809 		}
5810 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5811 			ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
5812 			ctsio->io_cont = ctl_write_same_cont;
5813 			num_blocks = 1 << 31;
5814 		} else
5815 			num_blocks = (lun->be_lun->maxlba + 1) - lba;
5816 	}
5817 
5818 	len = lun->be_lun->blocksize;
5819 
5820 	/*
5821 	 * If we've got a kernel request that hasn't been malloced yet,
5822 	 * malloc it and tell the caller the data buffer is here.
5823 	 */
5824 	if ((byte2 & SWS_NDOB) == 0 &&
5825 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5826 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5827 		ctsio->kern_data_len = len;
5828 		ctsio->kern_total_len = len;
5829 		ctsio->kern_rel_offset = 0;
5830 		ctsio->kern_sg_entries = 0;
5831 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5832 		ctsio->be_move_done = ctl_config_move_done;
5833 		ctl_datamove((union ctl_io *)ctsio);
5834 
5835 		return (CTL_RETVAL_COMPLETE);
5836 	}
5837 
5838 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5839 	lbalen->lba = lba;
5840 	lbalen->len = num_blocks;
5841 	lbalen->flags = byte2;
5842 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5843 
5844 	return (retval);
5845 }
5846 
5847 int
5848 ctl_unmap(struct ctl_scsiio *ctsio)
5849 {
5850 	struct ctl_lun *lun = CTL_LUN(ctsio);
5851 	struct scsi_unmap *cdb;
5852 	struct ctl_ptr_len_flags *ptrlen;
5853 	struct scsi_unmap_header *hdr;
5854 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5855 	uint64_t lba;
5856 	uint32_t num_blocks;
5857 	int len, retval;
5858 	uint8_t byte2;
5859 
5860 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5861 
5862 	cdb = (struct scsi_unmap *)ctsio->cdb;
5863 	len = scsi_2btoul(cdb->length);
5864 	byte2 = cdb->byte2;
5865 
5866 	/*
5867 	 * If we've got a kernel request that hasn't been malloced yet,
5868 	 * malloc it and tell the caller the data buffer is here.
5869 	 */
5870 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5871 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5872 		ctsio->kern_data_len = len;
5873 		ctsio->kern_total_len = len;
5874 		ctsio->kern_rel_offset = 0;
5875 		ctsio->kern_sg_entries = 0;
5876 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5877 		ctsio->be_move_done = ctl_config_move_done;
5878 		ctl_datamove((union ctl_io *)ctsio);
5879 
5880 		return (CTL_RETVAL_COMPLETE);
5881 	}
5882 
5883 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5884 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5885 	if (len < sizeof (*hdr) ||
5886 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5887 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5888 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5889 		ctl_set_invalid_field(ctsio,
5890 				      /*sks_valid*/ 0,
5891 				      /*command*/ 0,
5892 				      /*field*/ 0,
5893 				      /*bit_valid*/ 0,
5894 				      /*bit*/ 0);
5895 		goto done;
5896 	}
5897 	len = scsi_2btoul(hdr->desc_length);
5898 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5899 	end = buf + len / sizeof(*buf);
5900 
5901 	endnz = buf;
5902 	for (range = buf; range < end; range++) {
5903 		lba = scsi_8btou64(range->lba);
5904 		num_blocks = scsi_4btoul(range->length);
5905 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5906 		 || ((lba + num_blocks) < lba)) {
5907 			ctl_set_lba_out_of_range(ctsio,
5908 			    MAX(lba, lun->be_lun->maxlba + 1));
5909 			ctl_done((union ctl_io *)ctsio);
5910 			return (CTL_RETVAL_COMPLETE);
5911 		}
5912 		if (num_blocks != 0)
5913 			endnz = range + 1;
5914 	}
5915 
5916 	/*
5917 	 * Block backend can not handle zero last range.
5918 	 * Filter it out and return if there is nothing left.
5919 	 */
5920 	len = (uint8_t *)endnz - (uint8_t *)buf;
5921 	if (len == 0) {
5922 		ctl_set_success(ctsio);
5923 		goto done;
5924 	}
5925 
5926 	mtx_lock(&lun->lun_lock);
5927 	ptrlen = (struct ctl_ptr_len_flags *)
5928 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5929 	ptrlen->ptr = (void *)buf;
5930 	ptrlen->len = len;
5931 	ptrlen->flags = byte2;
5932 	ctl_try_unblock_others(lun, (union ctl_io *)ctsio, FALSE);
5933 	mtx_unlock(&lun->lun_lock);
5934 
5935 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5936 	return (retval);
5937 
5938 done:
5939 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5940 		free(ctsio->kern_data_ptr, M_CTL);
5941 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5942 	}
5943 	ctl_done((union ctl_io *)ctsio);
5944 	return (CTL_RETVAL_COMPLETE);
5945 }
5946 
5947 int
5948 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5949 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5950 {
5951 	struct ctl_lun *lun = CTL_LUN(ctsio);
5952 	uint8_t *current_cp;
5953 	int set_ua;
5954 	uint32_t initidx;
5955 
5956 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5957 	set_ua = 0;
5958 
5959 	current_cp = (page_index->page_data + (page_index->page_len *
5960 	    CTL_PAGE_CURRENT));
5961 
5962 	mtx_lock(&lun->lun_lock);
5963 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5964 		memcpy(current_cp, page_ptr, page_index->page_len);
5965 		set_ua = 1;
5966 	}
5967 	if (set_ua != 0)
5968 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5969 	mtx_unlock(&lun->lun_lock);
5970 	if (set_ua) {
5971 		ctl_isc_announce_mode(lun,
5972 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5973 		    page_index->page_code, page_index->subpage);
5974 	}
5975 	return (CTL_RETVAL_COMPLETE);
5976 }
5977 
5978 static void
5979 ctl_ie_timer(void *arg)
5980 {
5981 	struct ctl_lun *lun = arg;
5982 	uint64_t t;
5983 
5984 	if (lun->ie_asc == 0)
5985 		return;
5986 
5987 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5988 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5989 	else
5990 		lun->ie_reported = 0;
5991 
5992 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5993 		lun->ie_reportcnt++;
5994 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5995 		if (t == 0 || t == UINT32_MAX)
5996 			t = 3000;  /* 5 min */
5997 		callout_schedule_sbt(&lun->ie_callout, SBT_1S / 10 * t,
5998 		    SBT_1S / 10, 0);
5999 	}
6000 }
6001 
6002 int
6003 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
6004 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6005 {
6006 	struct ctl_lun *lun = CTL_LUN(ctsio);
6007 	struct scsi_info_exceptions_page *pg;
6008 	uint64_t t;
6009 
6010 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
6011 
6012 	pg = (struct scsi_info_exceptions_page *)page_ptr;
6013 	mtx_lock(&lun->lun_lock);
6014 	if (pg->info_flags & SIEP_FLAGS_TEST) {
6015 		lun->ie_asc = 0x5d;
6016 		lun->ie_ascq = 0xff;
6017 		if (pg->mrie == SIEP_MRIE_UA) {
6018 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
6019 			lun->ie_reported = 1;
6020 		} else {
6021 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
6022 			lun->ie_reported = -1;
6023 		}
6024 		lun->ie_reportcnt = 1;
6025 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
6026 			lun->ie_reportcnt++;
6027 			t = scsi_4btoul(pg->interval_timer);
6028 			if (t == 0 || t == UINT32_MAX)
6029 				t = 3000;  /* 5 min */
6030 			callout_reset_sbt(&lun->ie_callout, SBT_1S / 10 * t,
6031 			    SBT_1S / 10, ctl_ie_timer, lun, 0);
6032 		}
6033 	} else {
6034 		lun->ie_asc = 0;
6035 		lun->ie_ascq = 0;
6036 		lun->ie_reported = 1;
6037 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
6038 		lun->ie_reportcnt = UINT32_MAX;
6039 		callout_stop(&lun->ie_callout);
6040 	}
6041 	mtx_unlock(&lun->lun_lock);
6042 	return (CTL_RETVAL_COMPLETE);
6043 }
6044 
6045 static int
6046 ctl_do_mode_select(union ctl_io *io)
6047 {
6048 	struct ctl_lun *lun = CTL_LUN(io);
6049 	struct scsi_mode_page_header *page_header;
6050 	struct ctl_page_index *page_index;
6051 	struct ctl_scsiio *ctsio;
6052 	int page_len, page_len_offset, page_len_size;
6053 	union ctl_modepage_info *modepage_info;
6054 	uint16_t *len_left, *len_used;
6055 	int retval, i;
6056 
6057 	ctsio = &io->scsiio;
6058 	page_index = NULL;
6059 	page_len = 0;
6060 
6061 	modepage_info = (union ctl_modepage_info *)
6062 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6063 	len_left = &modepage_info->header.len_left;
6064 	len_used = &modepage_info->header.len_used;
6065 
6066 do_next_page:
6067 
6068 	page_header = (struct scsi_mode_page_header *)
6069 		(ctsio->kern_data_ptr + *len_used);
6070 
6071 	if (*len_left == 0) {
6072 		free(ctsio->kern_data_ptr, M_CTL);
6073 		ctl_set_success(ctsio);
6074 		ctl_done((union ctl_io *)ctsio);
6075 		return (CTL_RETVAL_COMPLETE);
6076 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6077 		free(ctsio->kern_data_ptr, M_CTL);
6078 		ctl_set_param_len_error(ctsio);
6079 		ctl_done((union ctl_io *)ctsio);
6080 		return (CTL_RETVAL_COMPLETE);
6081 
6082 	} else if ((page_header->page_code & SMPH_SPF)
6083 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6084 		free(ctsio->kern_data_ptr, M_CTL);
6085 		ctl_set_param_len_error(ctsio);
6086 		ctl_done((union ctl_io *)ctsio);
6087 		return (CTL_RETVAL_COMPLETE);
6088 	}
6089 
6090 	/*
6091 	 * XXX KDM should we do something with the block descriptor?
6092 	 */
6093 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6094 		page_index = &lun->mode_pages.index[i];
6095 		if (lun->be_lun->lun_type == T_DIRECT &&
6096 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6097 			continue;
6098 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6099 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6100 			continue;
6101 		if (lun->be_lun->lun_type == T_CDROM &&
6102 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6103 			continue;
6104 
6105 		if ((page_index->page_code & SMPH_PC_MASK) !=
6106 		    (page_header->page_code & SMPH_PC_MASK))
6107 			continue;
6108 
6109 		/*
6110 		 * If neither page has a subpage code, then we've got a
6111 		 * match.
6112 		 */
6113 		if (((page_index->page_code & SMPH_SPF) == 0)
6114 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6115 			page_len = page_header->page_length;
6116 			break;
6117 		}
6118 
6119 		/*
6120 		 * If both pages have subpages, then the subpage numbers
6121 		 * have to match.
6122 		 */
6123 		if ((page_index->page_code & SMPH_SPF)
6124 		  && (page_header->page_code & SMPH_SPF)) {
6125 			struct scsi_mode_page_header_sp *sph;
6126 
6127 			sph = (struct scsi_mode_page_header_sp *)page_header;
6128 			if (page_index->subpage == sph->subpage) {
6129 				page_len = scsi_2btoul(sph->page_length);
6130 				break;
6131 			}
6132 		}
6133 	}
6134 
6135 	/*
6136 	 * If we couldn't find the page, or if we don't have a mode select
6137 	 * handler for it, send back an error to the user.
6138 	 */
6139 	if ((i >= CTL_NUM_MODE_PAGES)
6140 	 || (page_index->select_handler == NULL)) {
6141 		ctl_set_invalid_field(ctsio,
6142 				      /*sks_valid*/ 1,
6143 				      /*command*/ 0,
6144 				      /*field*/ *len_used,
6145 				      /*bit_valid*/ 0,
6146 				      /*bit*/ 0);
6147 		free(ctsio->kern_data_ptr, M_CTL);
6148 		ctl_done((union ctl_io *)ctsio);
6149 		return (CTL_RETVAL_COMPLETE);
6150 	}
6151 
6152 	if (page_index->page_code & SMPH_SPF) {
6153 		page_len_offset = 2;
6154 		page_len_size = 2;
6155 	} else {
6156 		page_len_size = 1;
6157 		page_len_offset = 1;
6158 	}
6159 
6160 	/*
6161 	 * If the length the initiator gives us isn't the one we specify in
6162 	 * the mode page header, or if they didn't specify enough data in
6163 	 * the CDB to avoid truncating this page, kick out the request.
6164 	 */
6165 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6166 		ctl_set_invalid_field(ctsio,
6167 				      /*sks_valid*/ 1,
6168 				      /*command*/ 0,
6169 				      /*field*/ *len_used + page_len_offset,
6170 				      /*bit_valid*/ 0,
6171 				      /*bit*/ 0);
6172 		free(ctsio->kern_data_ptr, M_CTL);
6173 		ctl_done((union ctl_io *)ctsio);
6174 		return (CTL_RETVAL_COMPLETE);
6175 	}
6176 	if (*len_left < page_index->page_len) {
6177 		free(ctsio->kern_data_ptr, M_CTL);
6178 		ctl_set_param_len_error(ctsio);
6179 		ctl_done((union ctl_io *)ctsio);
6180 		return (CTL_RETVAL_COMPLETE);
6181 	}
6182 
6183 	/*
6184 	 * Run through the mode page, checking to make sure that the bits
6185 	 * the user changed are actually legal for him to change.
6186 	 */
6187 	for (i = 0; i < page_index->page_len; i++) {
6188 		uint8_t *user_byte, *change_mask, *current_byte;
6189 		int bad_bit;
6190 		int j;
6191 
6192 		user_byte = (uint8_t *)page_header + i;
6193 		change_mask = page_index->page_data +
6194 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6195 		current_byte = page_index->page_data +
6196 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6197 
6198 		/*
6199 		 * Check to see whether the user set any bits in this byte
6200 		 * that he is not allowed to set.
6201 		 */
6202 		if ((*user_byte & ~(*change_mask)) ==
6203 		    (*current_byte & ~(*change_mask)))
6204 			continue;
6205 
6206 		/*
6207 		 * Go through bit by bit to determine which one is illegal.
6208 		 */
6209 		bad_bit = 0;
6210 		for (j = 7; j >= 0; j--) {
6211 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6212 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6213 				bad_bit = i;
6214 				break;
6215 			}
6216 		}
6217 		ctl_set_invalid_field(ctsio,
6218 				      /*sks_valid*/ 1,
6219 				      /*command*/ 0,
6220 				      /*field*/ *len_used + i,
6221 				      /*bit_valid*/ 1,
6222 				      /*bit*/ bad_bit);
6223 		free(ctsio->kern_data_ptr, M_CTL);
6224 		ctl_done((union ctl_io *)ctsio);
6225 		return (CTL_RETVAL_COMPLETE);
6226 	}
6227 
6228 	/*
6229 	 * Decrement these before we call the page handler, since we may
6230 	 * end up getting called back one way or another before the handler
6231 	 * returns to this context.
6232 	 */
6233 	*len_left -= page_index->page_len;
6234 	*len_used += page_index->page_len;
6235 
6236 	retval = page_index->select_handler(ctsio, page_index,
6237 					    (uint8_t *)page_header);
6238 
6239 	/*
6240 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6241 	 * wait until this queued command completes to finish processing
6242 	 * the mode page.  If it returns anything other than
6243 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6244 	 * already set the sense information, freed the data pointer, and
6245 	 * completed the io for us.
6246 	 */
6247 	if (retval != CTL_RETVAL_COMPLETE)
6248 		goto bailout_no_done;
6249 
6250 	/*
6251 	 * If the initiator sent us more than one page, parse the next one.
6252 	 */
6253 	if (*len_left > 0)
6254 		goto do_next_page;
6255 
6256 	ctl_set_success(ctsio);
6257 	free(ctsio->kern_data_ptr, M_CTL);
6258 	ctl_done((union ctl_io *)ctsio);
6259 
6260 bailout_no_done:
6261 
6262 	return (CTL_RETVAL_COMPLETE);
6263 
6264 }
6265 
6266 int
6267 ctl_mode_select(struct ctl_scsiio *ctsio)
6268 {
6269 	struct ctl_lun *lun = CTL_LUN(ctsio);
6270 	union ctl_modepage_info *modepage_info;
6271 	int bd_len, i, header_size, param_len, rtd;
6272 	uint32_t initidx;
6273 
6274 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6275 	switch (ctsio->cdb[0]) {
6276 	case MODE_SELECT_6: {
6277 		struct scsi_mode_select_6 *cdb;
6278 
6279 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6280 
6281 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6282 		param_len = cdb->length;
6283 		header_size = sizeof(struct scsi_mode_header_6);
6284 		break;
6285 	}
6286 	case MODE_SELECT_10: {
6287 		struct scsi_mode_select_10 *cdb;
6288 
6289 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6290 
6291 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6292 		param_len = scsi_2btoul(cdb->length);
6293 		header_size = sizeof(struct scsi_mode_header_10);
6294 		break;
6295 	}
6296 	default:
6297 		ctl_set_invalid_opcode(ctsio);
6298 		ctl_done((union ctl_io *)ctsio);
6299 		return (CTL_RETVAL_COMPLETE);
6300 	}
6301 
6302 	if (rtd) {
6303 		if (param_len != 0) {
6304 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6305 			    /*command*/ 1, /*field*/ 0,
6306 			    /*bit_valid*/ 0, /*bit*/ 0);
6307 			ctl_done((union ctl_io *)ctsio);
6308 			return (CTL_RETVAL_COMPLETE);
6309 		}
6310 
6311 		/* Revert to defaults. */
6312 		ctl_init_page_index(lun);
6313 		mtx_lock(&lun->lun_lock);
6314 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6315 		mtx_unlock(&lun->lun_lock);
6316 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6317 			ctl_isc_announce_mode(lun, -1,
6318 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6319 			    lun->mode_pages.index[i].subpage);
6320 		}
6321 		ctl_set_success(ctsio);
6322 		ctl_done((union ctl_io *)ctsio);
6323 		return (CTL_RETVAL_COMPLETE);
6324 	}
6325 
6326 	/*
6327 	 * From SPC-3:
6328 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6329 	 * shall be empty. This condition shall not be considered as an error."
6330 	 */
6331 	if (param_len == 0) {
6332 		ctl_set_success(ctsio);
6333 		ctl_done((union ctl_io *)ctsio);
6334 		return (CTL_RETVAL_COMPLETE);
6335 	}
6336 
6337 	/*
6338 	 * Since we'll hit this the first time through, prior to
6339 	 * allocation, we don't need to free a data buffer here.
6340 	 */
6341 	if (param_len < header_size) {
6342 		ctl_set_param_len_error(ctsio);
6343 		ctl_done((union ctl_io *)ctsio);
6344 		return (CTL_RETVAL_COMPLETE);
6345 	}
6346 
6347 	/*
6348 	 * Allocate the data buffer and grab the user's data.  In theory,
6349 	 * we shouldn't have to sanity check the parameter list length here
6350 	 * because the maximum size is 64K.  We should be able to malloc
6351 	 * that much without too many problems.
6352 	 */
6353 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6354 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6355 		ctsio->kern_data_len = param_len;
6356 		ctsio->kern_total_len = param_len;
6357 		ctsio->kern_rel_offset = 0;
6358 		ctsio->kern_sg_entries = 0;
6359 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6360 		ctsio->be_move_done = ctl_config_move_done;
6361 		ctl_datamove((union ctl_io *)ctsio);
6362 
6363 		return (CTL_RETVAL_COMPLETE);
6364 	}
6365 
6366 	switch (ctsio->cdb[0]) {
6367 	case MODE_SELECT_6: {
6368 		struct scsi_mode_header_6 *mh6;
6369 
6370 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6371 		bd_len = mh6->blk_desc_len;
6372 		break;
6373 	}
6374 	case MODE_SELECT_10: {
6375 		struct scsi_mode_header_10 *mh10;
6376 
6377 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6378 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6379 		break;
6380 	}
6381 	default:
6382 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6383 	}
6384 
6385 	if (param_len < (header_size + bd_len)) {
6386 		free(ctsio->kern_data_ptr, M_CTL);
6387 		ctl_set_param_len_error(ctsio);
6388 		ctl_done((union ctl_io *)ctsio);
6389 		return (CTL_RETVAL_COMPLETE);
6390 	}
6391 
6392 	/*
6393 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6394 	 * ctl_config_write_done(), it'll get passed back to
6395 	 * ctl_do_mode_select() for further processing, or completion if
6396 	 * we're all done.
6397 	 */
6398 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6399 	ctsio->io_cont = ctl_do_mode_select;
6400 
6401 	modepage_info = (union ctl_modepage_info *)
6402 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6403 	memset(modepage_info, 0, sizeof(*modepage_info));
6404 	modepage_info->header.len_left = param_len - header_size - bd_len;
6405 	modepage_info->header.len_used = header_size + bd_len;
6406 
6407 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6408 }
6409 
6410 int
6411 ctl_mode_sense(struct ctl_scsiio *ctsio)
6412 {
6413 	struct ctl_lun *lun = CTL_LUN(ctsio);
6414 	int pc, page_code, llba, subpage;
6415 	int alloc_len, page_len, header_len, bd_len, total_len;
6416 	void *block_desc;
6417 	struct ctl_page_index *page_index;
6418 
6419 	llba = 0;
6420 
6421 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6422 
6423 	switch (ctsio->cdb[0]) {
6424 	case MODE_SENSE_6: {
6425 		struct scsi_mode_sense_6 *cdb;
6426 
6427 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6428 
6429 		header_len = sizeof(struct scsi_mode_hdr_6);
6430 		if (cdb->byte2 & SMS_DBD)
6431 			bd_len = 0;
6432 		else
6433 			bd_len = sizeof(struct scsi_mode_block_descr);
6434 		header_len += bd_len;
6435 
6436 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6437 		page_code = cdb->page & SMS_PAGE_CODE;
6438 		subpage = cdb->subpage;
6439 		alloc_len = cdb->length;
6440 		break;
6441 	}
6442 	case MODE_SENSE_10: {
6443 		struct scsi_mode_sense_10 *cdb;
6444 
6445 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6446 
6447 		header_len = sizeof(struct scsi_mode_hdr_10);
6448 		if (cdb->byte2 & SMS_DBD) {
6449 			bd_len = 0;
6450 		} else if (lun->be_lun->lun_type == T_DIRECT) {
6451 			if (cdb->byte2 & SMS10_LLBAA) {
6452 				llba = 1;
6453 				bd_len = sizeof(struct scsi_mode_block_descr_dlong);
6454 			} else
6455 				bd_len = sizeof(struct scsi_mode_block_descr_dshort);
6456 		} else
6457 			bd_len = sizeof(struct scsi_mode_block_descr);
6458 		header_len += bd_len;
6459 
6460 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6461 		page_code = cdb->page & SMS_PAGE_CODE;
6462 		subpage = cdb->subpage;
6463 		alloc_len = scsi_2btoul(cdb->length);
6464 		break;
6465 	}
6466 	default:
6467 		ctl_set_invalid_opcode(ctsio);
6468 		ctl_done((union ctl_io *)ctsio);
6469 		return (CTL_RETVAL_COMPLETE);
6470 		break; /* NOTREACHED */
6471 	}
6472 
6473 	/*
6474 	 * We have to make a first pass through to calculate the size of
6475 	 * the pages that match the user's query.  Then we allocate enough
6476 	 * memory to hold it, and actually copy the data into the buffer.
6477 	 */
6478 	switch (page_code) {
6479 	case SMS_ALL_PAGES_PAGE: {
6480 		u_int i;
6481 
6482 		page_len = 0;
6483 
6484 		/*
6485 		 * At the moment, values other than 0 and 0xff here are
6486 		 * reserved according to SPC-3.
6487 		 */
6488 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6489 		 && (subpage != SMS_SUBPAGE_ALL)) {
6490 			ctl_set_invalid_field(ctsio,
6491 					      /*sks_valid*/ 1,
6492 					      /*command*/ 1,
6493 					      /*field*/ 3,
6494 					      /*bit_valid*/ 0,
6495 					      /*bit*/ 0);
6496 			ctl_done((union ctl_io *)ctsio);
6497 			return (CTL_RETVAL_COMPLETE);
6498 		}
6499 
6500 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6501 			page_index = &lun->mode_pages.index[i];
6502 
6503 			/* Make sure the page is supported for this dev type */
6504 			if (lun->be_lun->lun_type == T_DIRECT &&
6505 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6506 				continue;
6507 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6508 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6509 				continue;
6510 			if (lun->be_lun->lun_type == T_CDROM &&
6511 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6512 				continue;
6513 
6514 			/*
6515 			 * We don't use this subpage if the user didn't
6516 			 * request all subpages.
6517 			 */
6518 			if ((page_index->subpage != 0)
6519 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6520 				continue;
6521 
6522 			page_len += page_index->page_len;
6523 		}
6524 		break;
6525 	}
6526 	default: {
6527 		u_int i;
6528 
6529 		page_len = 0;
6530 
6531 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6532 			page_index = &lun->mode_pages.index[i];
6533 
6534 			/* Make sure the page is supported for this dev type */
6535 			if (lun->be_lun->lun_type == T_DIRECT &&
6536 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6537 				continue;
6538 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6539 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6540 				continue;
6541 			if (lun->be_lun->lun_type == T_CDROM &&
6542 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6543 				continue;
6544 
6545 			/* Look for the right page code */
6546 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6547 				continue;
6548 
6549 			/* Look for the right subpage or the subpage wildcard*/
6550 			if ((page_index->subpage != subpage)
6551 			 && (subpage != SMS_SUBPAGE_ALL))
6552 				continue;
6553 
6554 			page_len += page_index->page_len;
6555 		}
6556 
6557 		if (page_len == 0) {
6558 			ctl_set_invalid_field(ctsio,
6559 					      /*sks_valid*/ 1,
6560 					      /*command*/ 1,
6561 					      /*field*/ 2,
6562 					      /*bit_valid*/ 1,
6563 					      /*bit*/ 5);
6564 			ctl_done((union ctl_io *)ctsio);
6565 			return (CTL_RETVAL_COMPLETE);
6566 		}
6567 		break;
6568 	}
6569 	}
6570 
6571 	total_len = header_len + page_len;
6572 
6573 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6574 	ctsio->kern_sg_entries = 0;
6575 	ctsio->kern_rel_offset = 0;
6576 	ctsio->kern_data_len = min(total_len, alloc_len);
6577 	ctsio->kern_total_len = ctsio->kern_data_len;
6578 
6579 	switch (ctsio->cdb[0]) {
6580 	case MODE_SENSE_6: {
6581 		struct scsi_mode_hdr_6 *header;
6582 
6583 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6584 
6585 		header->datalen = MIN(total_len - 1, 254);
6586 		if (lun->be_lun->lun_type == T_DIRECT) {
6587 			header->dev_specific = 0x10; /* DPOFUA */
6588 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6589 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6590 				header->dev_specific |= 0x80; /* WP */
6591 		}
6592 		header->block_descr_len = bd_len;
6593 		block_desc = &header[1];
6594 		break;
6595 	}
6596 	case MODE_SENSE_10: {
6597 		struct scsi_mode_hdr_10 *header;
6598 		int datalen;
6599 
6600 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6601 
6602 		datalen = MIN(total_len - 2, 65533);
6603 		scsi_ulto2b(datalen, header->datalen);
6604 		if (lun->be_lun->lun_type == T_DIRECT) {
6605 			header->dev_specific = 0x10; /* DPOFUA */
6606 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6607 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6608 				header->dev_specific |= 0x80; /* WP */
6609 		}
6610 		if (llba)
6611 			header->flags |= SMH_LONGLBA;
6612 		scsi_ulto2b(bd_len, header->block_descr_len);
6613 		block_desc = &header[1];
6614 		break;
6615 	}
6616 	default:
6617 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6618 	}
6619 
6620 	/*
6621 	 * If we've got a disk, use its blocksize in the block
6622 	 * descriptor.  Otherwise, just set it to 0.
6623 	 */
6624 	if (bd_len > 0) {
6625 		if (lun->be_lun->lun_type == T_DIRECT) {
6626 			if (llba) {
6627 				struct scsi_mode_block_descr_dlong *bd = block_desc;
6628 				if (lun->be_lun->maxlba != 0)
6629 					scsi_u64to8b(lun->be_lun->maxlba + 1,
6630 					    bd->num_blocks);
6631 				scsi_ulto4b(lun->be_lun->blocksize,
6632 				    bd->block_len);
6633 			} else {
6634 				struct scsi_mode_block_descr_dshort *bd = block_desc;
6635 				if (lun->be_lun->maxlba != 0)
6636 					scsi_ulto4b(MIN(lun->be_lun->maxlba+1,
6637 					    UINT32_MAX), bd->num_blocks);
6638 				scsi_ulto3b(lun->be_lun->blocksize,
6639 				    bd->block_len);
6640 			}
6641 		} else {
6642 			struct scsi_mode_block_descr *bd = block_desc;
6643 			scsi_ulto3b(0, bd->block_len);
6644 		}
6645 	}
6646 
6647 	switch (page_code) {
6648 	case SMS_ALL_PAGES_PAGE: {
6649 		int i, data_used;
6650 
6651 		data_used = header_len;
6652 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6653 			struct ctl_page_index *page_index;
6654 
6655 			page_index = &lun->mode_pages.index[i];
6656 			if (lun->be_lun->lun_type == T_DIRECT &&
6657 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6658 				continue;
6659 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6660 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6661 				continue;
6662 			if (lun->be_lun->lun_type == T_CDROM &&
6663 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6664 				continue;
6665 
6666 			/*
6667 			 * We don't use this subpage if the user didn't
6668 			 * request all subpages.  We already checked (above)
6669 			 * to make sure the user only specified a subpage
6670 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6671 			 */
6672 			if ((page_index->subpage != 0)
6673 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6674 				continue;
6675 
6676 			/*
6677 			 * Call the handler, if it exists, to update the
6678 			 * page to the latest values.
6679 			 */
6680 			if (page_index->sense_handler != NULL)
6681 				page_index->sense_handler(ctsio, page_index,pc);
6682 
6683 			memcpy(ctsio->kern_data_ptr + data_used,
6684 			       page_index->page_data +
6685 			       (page_index->page_len * pc),
6686 			       page_index->page_len);
6687 			data_used += page_index->page_len;
6688 		}
6689 		break;
6690 	}
6691 	default: {
6692 		int i, data_used;
6693 
6694 		data_used = header_len;
6695 
6696 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6697 			struct ctl_page_index *page_index;
6698 
6699 			page_index = &lun->mode_pages.index[i];
6700 
6701 			/* Look for the right page code */
6702 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6703 				continue;
6704 
6705 			/* Look for the right subpage or the subpage wildcard*/
6706 			if ((page_index->subpage != subpage)
6707 			 && (subpage != SMS_SUBPAGE_ALL))
6708 				continue;
6709 
6710 			/* Make sure the page is supported for this dev type */
6711 			if (lun->be_lun->lun_type == T_DIRECT &&
6712 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6713 				continue;
6714 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6715 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6716 				continue;
6717 			if (lun->be_lun->lun_type == T_CDROM &&
6718 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6719 				continue;
6720 
6721 			/*
6722 			 * Call the handler, if it exists, to update the
6723 			 * page to the latest values.
6724 			 */
6725 			if (page_index->sense_handler != NULL)
6726 				page_index->sense_handler(ctsio, page_index,pc);
6727 
6728 			memcpy(ctsio->kern_data_ptr + data_used,
6729 			       page_index->page_data +
6730 			       (page_index->page_len * pc),
6731 			       page_index->page_len);
6732 			data_used += page_index->page_len;
6733 		}
6734 		break;
6735 	}
6736 	}
6737 
6738 	ctl_set_success(ctsio);
6739 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6740 	ctsio->be_move_done = ctl_config_move_done;
6741 	ctl_datamove((union ctl_io *)ctsio);
6742 	return (CTL_RETVAL_COMPLETE);
6743 }
6744 
6745 int
6746 ctl_temp_log_sense_handler(struct ctl_scsiio *ctsio,
6747 			       struct ctl_page_index *page_index,
6748 			       int pc)
6749 {
6750 	struct ctl_lun *lun = CTL_LUN(ctsio);
6751 	struct scsi_log_temperature *data;
6752 	const char *value;
6753 
6754 	data = (struct scsi_log_temperature *)page_index->page_data;
6755 
6756 	scsi_ulto2b(SLP_TEMPERATURE, data->hdr.param_code);
6757 	data->hdr.param_control = SLP_LBIN;
6758 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6759 	    sizeof(struct scsi_log_param_header);
6760 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6761 	    NULL)) != NULL)
6762 		data->temperature = strtol(value, NULL, 0);
6763 	else
6764 		data->temperature = 0xff;
6765 	data++;
6766 
6767 	scsi_ulto2b(SLP_REFTEMPERATURE, data->hdr.param_code);
6768 	data->hdr.param_control = SLP_LBIN;
6769 	data->hdr.param_len = sizeof(struct scsi_log_temperature) -
6770 	    sizeof(struct scsi_log_param_header);
6771 	if ((value = dnvlist_get_string(lun->be_lun->options, "reftemperature",
6772 	    NULL)) != NULL)
6773 		data->temperature = strtol(value, NULL, 0);
6774 	else
6775 		data->temperature = 0xff;
6776 	return (0);
6777 }
6778 
6779 int
6780 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6781 			       struct ctl_page_index *page_index,
6782 			       int pc)
6783 {
6784 	struct ctl_lun *lun = CTL_LUN(ctsio);
6785 	struct scsi_log_param_header *phdr;
6786 	uint8_t *data;
6787 	uint64_t val;
6788 
6789 	data = page_index->page_data;
6790 
6791 	if (lun->backend->lun_attr != NULL &&
6792 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksavail"))
6793 	     != UINT64_MAX) {
6794 		phdr = (struct scsi_log_param_header *)data;
6795 		scsi_ulto2b(0x0001, phdr->param_code);
6796 		phdr->param_control = SLP_LBIN | SLP_LP;
6797 		phdr->param_len = 8;
6798 		data = (uint8_t *)(phdr + 1);
6799 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6800 		data[4] = 0x02; /* per-pool */
6801 		data += phdr->param_len;
6802 	}
6803 
6804 	if (lun->backend->lun_attr != NULL &&
6805 	    (val = lun->backend->lun_attr(lun->be_lun, "blocksused"))
6806 	     != UINT64_MAX) {
6807 		phdr = (struct scsi_log_param_header *)data;
6808 		scsi_ulto2b(0x0002, phdr->param_code);
6809 		phdr->param_control = SLP_LBIN | SLP_LP;
6810 		phdr->param_len = 8;
6811 		data = (uint8_t *)(phdr + 1);
6812 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6813 		data[4] = 0x01; /* per-LUN */
6814 		data += phdr->param_len;
6815 	}
6816 
6817 	if (lun->backend->lun_attr != NULL &&
6818 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksavail"))
6819 	     != UINT64_MAX) {
6820 		phdr = (struct scsi_log_param_header *)data;
6821 		scsi_ulto2b(0x00f1, phdr->param_code);
6822 		phdr->param_control = SLP_LBIN | SLP_LP;
6823 		phdr->param_len = 8;
6824 		data = (uint8_t *)(phdr + 1);
6825 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6826 		data[4] = 0x02; /* per-pool */
6827 		data += phdr->param_len;
6828 	}
6829 
6830 	if (lun->backend->lun_attr != NULL &&
6831 	    (val = lun->backend->lun_attr(lun->be_lun, "poolblocksused"))
6832 	     != UINT64_MAX) {
6833 		phdr = (struct scsi_log_param_header *)data;
6834 		scsi_ulto2b(0x00f2, phdr->param_code);
6835 		phdr->param_control = SLP_LBIN | SLP_LP;
6836 		phdr->param_len = 8;
6837 		data = (uint8_t *)(phdr + 1);
6838 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6839 		data[4] = 0x02; /* per-pool */
6840 		data += phdr->param_len;
6841 	}
6842 
6843 	page_index->page_len = data - page_index->page_data;
6844 	return (0);
6845 }
6846 
6847 int
6848 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6849 			       struct ctl_page_index *page_index,
6850 			       int pc)
6851 {
6852 	struct ctl_lun *lun = CTL_LUN(ctsio);
6853 	struct stat_page *data;
6854 	struct bintime *t;
6855 
6856 	data = (struct stat_page *)page_index->page_data;
6857 
6858 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6859 	data->sap.hdr.param_control = SLP_LBIN;
6860 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6861 	    sizeof(struct scsi_log_param_header);
6862 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6863 	    data->sap.read_num);
6864 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6865 	    data->sap.write_num);
6866 	if (lun->be_lun->blocksize > 0) {
6867 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6868 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6869 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6870 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6871 	}
6872 	t = &lun->stats.time[CTL_STATS_READ];
6873 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6874 	    data->sap.read_int);
6875 	t = &lun->stats.time[CTL_STATS_WRITE];
6876 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6877 	    data->sap.write_int);
6878 	scsi_u64to8b(0, data->sap.weighted_num);
6879 	scsi_u64to8b(0, data->sap.weighted_int);
6880 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6881 	data->it.hdr.param_control = SLP_LBIN;
6882 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6883 	    sizeof(struct scsi_log_param_header);
6884 #ifdef CTL_TIME_IO
6885 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6886 #endif
6887 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6888 	data->it.hdr.param_control = SLP_LBIN;
6889 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6890 	    sizeof(struct scsi_log_param_header);
6891 	scsi_ulto4b(3, data->ti.exponent);
6892 	scsi_ulto4b(1, data->ti.integer);
6893 	return (0);
6894 }
6895 
6896 int
6897 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6898 			       struct ctl_page_index *page_index,
6899 			       int pc)
6900 {
6901 	struct ctl_lun *lun = CTL_LUN(ctsio);
6902 	struct scsi_log_informational_exceptions *data;
6903 	const char *value;
6904 
6905 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6906 
6907 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6908 	data->hdr.param_control = SLP_LBIN;
6909 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6910 	    sizeof(struct scsi_log_param_header);
6911 	data->ie_asc = lun->ie_asc;
6912 	data->ie_ascq = lun->ie_ascq;
6913 	if ((value = dnvlist_get_string(lun->be_lun->options, "temperature",
6914 	    NULL)) != NULL)
6915 		data->temperature = strtol(value, NULL, 0);
6916 	else
6917 		data->temperature = 0xff;
6918 	return (0);
6919 }
6920 
6921 int
6922 ctl_log_sense(struct ctl_scsiio *ctsio)
6923 {
6924 	struct ctl_lun *lun = CTL_LUN(ctsio);
6925 	int i, pc, page_code, subpage;
6926 	int alloc_len, total_len;
6927 	struct ctl_page_index *page_index;
6928 	struct scsi_log_sense *cdb;
6929 	struct scsi_log_header *header;
6930 
6931 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6932 
6933 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6934 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6935 	page_code = cdb->page & SLS_PAGE_CODE;
6936 	subpage = cdb->subpage;
6937 	alloc_len = scsi_2btoul(cdb->length);
6938 
6939 	page_index = NULL;
6940 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6941 		page_index = &lun->log_pages.index[i];
6942 
6943 		/* Look for the right page code */
6944 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6945 			continue;
6946 
6947 		/* Look for the right subpage or the subpage wildcard*/
6948 		if (page_index->subpage != subpage)
6949 			continue;
6950 
6951 		break;
6952 	}
6953 	if (i >= CTL_NUM_LOG_PAGES) {
6954 		ctl_set_invalid_field(ctsio,
6955 				      /*sks_valid*/ 1,
6956 				      /*command*/ 1,
6957 				      /*field*/ 2,
6958 				      /*bit_valid*/ 0,
6959 				      /*bit*/ 0);
6960 		ctl_done((union ctl_io *)ctsio);
6961 		return (CTL_RETVAL_COMPLETE);
6962 	}
6963 
6964 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6965 
6966 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6967 	ctsio->kern_sg_entries = 0;
6968 	ctsio->kern_rel_offset = 0;
6969 	ctsio->kern_data_len = min(total_len, alloc_len);
6970 	ctsio->kern_total_len = ctsio->kern_data_len;
6971 
6972 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6973 	header->page = page_index->page_code;
6974 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6975 		header->page |= SL_DS;
6976 	if (page_index->subpage) {
6977 		header->page |= SL_SPF;
6978 		header->subpage = page_index->subpage;
6979 	}
6980 	scsi_ulto2b(page_index->page_len, header->datalen);
6981 
6982 	/*
6983 	 * Call the handler, if it exists, to update the
6984 	 * page to the latest values.
6985 	 */
6986 	if (page_index->sense_handler != NULL)
6987 		page_index->sense_handler(ctsio, page_index, pc);
6988 
6989 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6990 
6991 	ctl_set_success(ctsio);
6992 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6993 	ctsio->be_move_done = ctl_config_move_done;
6994 	ctl_datamove((union ctl_io *)ctsio);
6995 	return (CTL_RETVAL_COMPLETE);
6996 }
6997 
6998 int
6999 ctl_read_capacity(struct ctl_scsiio *ctsio)
7000 {
7001 	struct ctl_lun *lun = CTL_LUN(ctsio);
7002 	struct scsi_read_capacity *cdb;
7003 	struct scsi_read_capacity_data *data;
7004 	uint32_t lba;
7005 
7006 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7007 
7008 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7009 
7010 	lba = scsi_4btoul(cdb->addr);
7011 	if (((cdb->pmi & SRC_PMI) == 0)
7012 	 && (lba != 0)) {
7013 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7014 				      /*sks_valid*/ 1,
7015 				      /*command*/ 1,
7016 				      /*field*/ 2,
7017 				      /*bit_valid*/ 0,
7018 				      /*bit*/ 0);
7019 		ctl_done((union ctl_io *)ctsio);
7020 		return (CTL_RETVAL_COMPLETE);
7021 	}
7022 
7023 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7024 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7025 	ctsio->kern_data_len = sizeof(*data);
7026 	ctsio->kern_total_len = sizeof(*data);
7027 	ctsio->kern_rel_offset = 0;
7028 	ctsio->kern_sg_entries = 0;
7029 
7030 	/*
7031 	 * If the maximum LBA is greater than 0xfffffffe, the user must
7032 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7033 	 * serivce action set.
7034 	 */
7035 	if (lun->be_lun->maxlba > 0xfffffffe)
7036 		scsi_ulto4b(0xffffffff, data->addr);
7037 	else
7038 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7039 
7040 	/*
7041 	 * XXX KDM this may not be 512 bytes...
7042 	 */
7043 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7044 
7045 	ctl_set_success(ctsio);
7046 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7047 	ctsio->be_move_done = ctl_config_move_done;
7048 	ctl_datamove((union ctl_io *)ctsio);
7049 	return (CTL_RETVAL_COMPLETE);
7050 }
7051 
7052 int
7053 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7054 {
7055 	struct ctl_lun *lun = CTL_LUN(ctsio);
7056 	struct scsi_read_capacity_16 *cdb;
7057 	struct scsi_read_capacity_data_long *data;
7058 	uint64_t lba;
7059 	uint32_t alloc_len;
7060 
7061 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7062 
7063 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7064 
7065 	alloc_len = scsi_4btoul(cdb->alloc_len);
7066 	lba = scsi_8btou64(cdb->addr);
7067 
7068 	if ((cdb->reladr & SRC16_PMI)
7069 	 && (lba != 0)) {
7070 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7071 				      /*sks_valid*/ 1,
7072 				      /*command*/ 1,
7073 				      /*field*/ 2,
7074 				      /*bit_valid*/ 0,
7075 				      /*bit*/ 0);
7076 		ctl_done((union ctl_io *)ctsio);
7077 		return (CTL_RETVAL_COMPLETE);
7078 	}
7079 
7080 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7081 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7082 	ctsio->kern_rel_offset = 0;
7083 	ctsio->kern_sg_entries = 0;
7084 	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
7085 	ctsio->kern_total_len = ctsio->kern_data_len;
7086 
7087 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7088 	/* XXX KDM this may not be 512 bytes... */
7089 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7090 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7091 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7092 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7093 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7094 
7095 	ctl_set_success(ctsio);
7096 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7097 	ctsio->be_move_done = ctl_config_move_done;
7098 	ctl_datamove((union ctl_io *)ctsio);
7099 	return (CTL_RETVAL_COMPLETE);
7100 }
7101 
7102 int
7103 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7104 {
7105 	struct ctl_lun *lun = CTL_LUN(ctsio);
7106 	struct scsi_get_lba_status *cdb;
7107 	struct scsi_get_lba_status_data *data;
7108 	struct ctl_lba_len_flags *lbalen;
7109 	uint64_t lba;
7110 	uint32_t alloc_len, total_len;
7111 	int retval;
7112 
7113 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7114 
7115 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7116 	lba = scsi_8btou64(cdb->addr);
7117 	alloc_len = scsi_4btoul(cdb->alloc_len);
7118 
7119 	if (lba > lun->be_lun->maxlba) {
7120 		ctl_set_lba_out_of_range(ctsio, lba);
7121 		ctl_done((union ctl_io *)ctsio);
7122 		return (CTL_RETVAL_COMPLETE);
7123 	}
7124 
7125 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7126 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7127 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7128 	ctsio->kern_rel_offset = 0;
7129 	ctsio->kern_sg_entries = 0;
7130 	ctsio->kern_data_len = min(total_len, alloc_len);
7131 	ctsio->kern_total_len = ctsio->kern_data_len;
7132 
7133 	/* Fill dummy data in case backend can't tell anything. */
7134 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7135 	scsi_u64to8b(lba, data->descr[0].addr);
7136 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7137 	    data->descr[0].length);
7138 	data->descr[0].status = 0; /* Mapped or unknown. */
7139 
7140 	ctl_set_success(ctsio);
7141 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7142 	ctsio->be_move_done = ctl_config_move_done;
7143 
7144 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7145 	lbalen->lba = lba;
7146 	lbalen->len = total_len;
7147 	lbalen->flags = 0;
7148 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7149 	return (retval);
7150 }
7151 
7152 int
7153 ctl_read_defect(struct ctl_scsiio *ctsio)
7154 {
7155 	struct scsi_read_defect_data_10 *ccb10;
7156 	struct scsi_read_defect_data_12 *ccb12;
7157 	struct scsi_read_defect_data_hdr_10 *data10;
7158 	struct scsi_read_defect_data_hdr_12 *data12;
7159 	uint32_t alloc_len, data_len;
7160 	uint8_t format;
7161 
7162 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7163 
7164 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7165 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7166 		format = ccb10->format;
7167 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7168 		data_len = sizeof(*data10);
7169 	} else {
7170 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7171 		format = ccb12->format;
7172 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7173 		data_len = sizeof(*data12);
7174 	}
7175 	if (alloc_len == 0) {
7176 		ctl_set_success(ctsio);
7177 		ctl_done((union ctl_io *)ctsio);
7178 		return (CTL_RETVAL_COMPLETE);
7179 	}
7180 
7181 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7182 	ctsio->kern_rel_offset = 0;
7183 	ctsio->kern_sg_entries = 0;
7184 	ctsio->kern_data_len = min(data_len, alloc_len);
7185 	ctsio->kern_total_len = ctsio->kern_data_len;
7186 
7187 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7188 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7189 		    ctsio->kern_data_ptr;
7190 		data10->format = format;
7191 		scsi_ulto2b(0, data10->length);
7192 	} else {
7193 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7194 		    ctsio->kern_data_ptr;
7195 		data12->format = format;
7196 		scsi_ulto2b(0, data12->generation);
7197 		scsi_ulto4b(0, data12->length);
7198 	}
7199 
7200 	ctl_set_success(ctsio);
7201 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7202 	ctsio->be_move_done = ctl_config_move_done;
7203 	ctl_datamove((union ctl_io *)ctsio);
7204 	return (CTL_RETVAL_COMPLETE);
7205 }
7206 
7207 int
7208 ctl_report_ident_info(struct ctl_scsiio *ctsio)
7209 {
7210 	struct ctl_lun *lun = CTL_LUN(ctsio);
7211 	struct scsi_report_ident_info *cdb;
7212 	struct scsi_report_ident_info_data *rii_ptr;
7213 	struct scsi_report_ident_info_descr *riid_ptr;
7214 	const char *oii, *otii;
7215 	int retval, alloc_len, total_len = 0, len = 0;
7216 
7217 	CTL_DEBUG_PRINT(("ctl_report_ident_info\n"));
7218 
7219 	cdb = (struct scsi_report_ident_info *)ctsio->cdb;
7220 	retval = CTL_RETVAL_COMPLETE;
7221 
7222 	total_len = sizeof(struct scsi_report_ident_info_data);
7223 	switch (cdb->type) {
7224 	case RII_LUII:
7225 		oii = dnvlist_get_string(lun->be_lun->options,
7226 		    "ident_info", NULL);
7227 		if (oii)
7228 			len = strlen(oii);	/* Approximately */
7229 		break;
7230 	case RII_LUTII:
7231 		otii = dnvlist_get_string(lun->be_lun->options,
7232 		    "text_ident_info", NULL);
7233 		if (otii)
7234 			len = strlen(otii) + 1;	/* NULL-terminated */
7235 		break;
7236 	case RII_IIS:
7237 		len = 2 * sizeof(struct scsi_report_ident_info_descr);
7238 		break;
7239 	default:
7240 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7241 				      /*sks_valid*/ 1,
7242 				      /*command*/ 1,
7243 				      /*field*/ 11,
7244 				      /*bit_valid*/ 1,
7245 				      /*bit*/ 2);
7246 		ctl_done((union ctl_io *)ctsio);
7247 		return(retval);
7248 	}
7249 	total_len += len;
7250 	alloc_len = scsi_4btoul(cdb->length);
7251 
7252 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7253 	ctsio->kern_sg_entries = 0;
7254 	ctsio->kern_rel_offset = 0;
7255 	ctsio->kern_data_len = min(total_len, alloc_len);
7256 	ctsio->kern_total_len = ctsio->kern_data_len;
7257 
7258 	rii_ptr = (struct scsi_report_ident_info_data *)ctsio->kern_data_ptr;
7259 	switch (cdb->type) {
7260 	case RII_LUII:
7261 		if (oii) {
7262 			if (oii[0] == '0' && oii[1] == 'x')
7263 				len = hex2bin(oii, (uint8_t *)(rii_ptr + 1), len);
7264 			else
7265 				strncpy((uint8_t *)(rii_ptr + 1), oii, len);
7266 		}
7267 		break;
7268 	case RII_LUTII:
7269 		if (otii)
7270 			strlcpy((uint8_t *)(rii_ptr + 1), otii, len);
7271 		break;
7272 	case RII_IIS:
7273 		riid_ptr = (struct scsi_report_ident_info_descr *)(rii_ptr + 1);
7274 		riid_ptr->type = RII_LUII;
7275 		scsi_ulto2b(0xffff, riid_ptr->length);
7276 		riid_ptr++;
7277 		riid_ptr->type = RII_LUTII;
7278 		scsi_ulto2b(0xffff, riid_ptr->length);
7279 	}
7280 	scsi_ulto2b(len, rii_ptr->length);
7281 
7282 	ctl_set_success(ctsio);
7283 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7284 	ctsio->be_move_done = ctl_config_move_done;
7285 	ctl_datamove((union ctl_io *)ctsio);
7286 	return(retval);
7287 }
7288 
7289 int
7290 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7291 {
7292 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7293 	struct ctl_lun *lun = CTL_LUN(ctsio);
7294 	struct scsi_maintenance_in *cdb;
7295 	int retval;
7296 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7297 	int num_ha_groups, num_target_ports, shared_group;
7298 	struct ctl_port *port;
7299 	struct scsi_target_group_data *rtg_ptr;
7300 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7301 	struct scsi_target_port_group_descriptor *tpg_desc;
7302 
7303 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7304 
7305 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7306 	retval = CTL_RETVAL_COMPLETE;
7307 
7308 	switch (cdb->byte2 & STG_PDF_MASK) {
7309 	case STG_PDF_LENGTH:
7310 		ext = 0;
7311 		break;
7312 	case STG_PDF_EXTENDED:
7313 		ext = 1;
7314 		break;
7315 	default:
7316 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7317 				      /*sks_valid*/ 1,
7318 				      /*command*/ 1,
7319 				      /*field*/ 2,
7320 				      /*bit_valid*/ 1,
7321 				      /*bit*/ 5);
7322 		ctl_done((union ctl_io *)ctsio);
7323 		return(retval);
7324 	}
7325 
7326 	num_target_ports = 0;
7327 	shared_group = (softc->is_single != 0);
7328 	mtx_lock(&softc->ctl_lock);
7329 	STAILQ_FOREACH(port, &softc->port_list, links) {
7330 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7331 			continue;
7332 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7333 			continue;
7334 		num_target_ports++;
7335 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7336 			shared_group = 1;
7337 	}
7338 	mtx_unlock(&softc->ctl_lock);
7339 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7340 
7341 	if (ext)
7342 		total_len = sizeof(struct scsi_target_group_data_extended);
7343 	else
7344 		total_len = sizeof(struct scsi_target_group_data);
7345 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7346 		(shared_group + num_ha_groups) +
7347 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7348 
7349 	alloc_len = scsi_4btoul(cdb->length);
7350 
7351 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7352 	ctsio->kern_sg_entries = 0;
7353 	ctsio->kern_rel_offset = 0;
7354 	ctsio->kern_data_len = min(total_len, alloc_len);
7355 	ctsio->kern_total_len = ctsio->kern_data_len;
7356 
7357 	if (ext) {
7358 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7359 		    ctsio->kern_data_ptr;
7360 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7361 		rtg_ext_ptr->format_type = 0x10;
7362 		rtg_ext_ptr->implicit_transition_time = 0;
7363 		tpg_desc = &rtg_ext_ptr->groups[0];
7364 	} else {
7365 		rtg_ptr = (struct scsi_target_group_data *)
7366 		    ctsio->kern_data_ptr;
7367 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7368 		tpg_desc = &rtg_ptr->groups[0];
7369 	}
7370 
7371 	mtx_lock(&softc->ctl_lock);
7372 	pg = softc->port_min / softc->port_cnt;
7373 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7374 		/* Some shelf is known to be primary. */
7375 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7376 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7377 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7378 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7379 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7380 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7381 		else
7382 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7383 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7384 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7385 		} else {
7386 			ts = os;
7387 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7388 		}
7389 	} else {
7390 		/* No known primary shelf. */
7391 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7392 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7393 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7394 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7395 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7396 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7397 		} else {
7398 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7399 		}
7400 	}
7401 	if (shared_group) {
7402 		tpg_desc->pref_state = ts;
7403 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7404 		    TPG_U_SUP | TPG_T_SUP;
7405 		scsi_ulto2b(1, tpg_desc->target_port_group);
7406 		tpg_desc->status = TPG_IMPLICIT;
7407 		pc = 0;
7408 		STAILQ_FOREACH(port, &softc->port_list, links) {
7409 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7410 				continue;
7411 			if (!softc->is_single &&
7412 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7413 				continue;
7414 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7415 				continue;
7416 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7417 			    relative_target_port_identifier);
7418 			pc++;
7419 		}
7420 		tpg_desc->target_port_count = pc;
7421 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7422 		    &tpg_desc->descriptors[pc];
7423 	}
7424 	for (g = 0; g < num_ha_groups; g++) {
7425 		tpg_desc->pref_state = (g == pg) ? ts : os;
7426 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7427 		    TPG_U_SUP | TPG_T_SUP;
7428 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7429 		tpg_desc->status = TPG_IMPLICIT;
7430 		pc = 0;
7431 		STAILQ_FOREACH(port, &softc->port_list, links) {
7432 			if (port->targ_port < g * softc->port_cnt ||
7433 			    port->targ_port >= (g + 1) * softc->port_cnt)
7434 				continue;
7435 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7436 				continue;
7437 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7438 				continue;
7439 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7440 				continue;
7441 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7442 			    relative_target_port_identifier);
7443 			pc++;
7444 		}
7445 		tpg_desc->target_port_count = pc;
7446 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7447 		    &tpg_desc->descriptors[pc];
7448 	}
7449 	mtx_unlock(&softc->ctl_lock);
7450 
7451 	ctl_set_success(ctsio);
7452 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7453 	ctsio->be_move_done = ctl_config_move_done;
7454 	ctl_datamove((union ctl_io *)ctsio);
7455 	return(retval);
7456 }
7457 
7458 int
7459 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7460 {
7461 	struct ctl_lun *lun = CTL_LUN(ctsio);
7462 	struct scsi_report_supported_opcodes *cdb;
7463 	const struct ctl_cmd_entry *entry, *sentry;
7464 	struct scsi_report_supported_opcodes_all *all;
7465 	struct scsi_report_supported_opcodes_descr *descr;
7466 	struct scsi_report_supported_opcodes_one *one;
7467 	int retval;
7468 	int alloc_len, total_len;
7469 	int opcode, service_action, i, j, num;
7470 
7471 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7472 
7473 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7474 	retval = CTL_RETVAL_COMPLETE;
7475 
7476 	opcode = cdb->requested_opcode;
7477 	service_action = scsi_2btoul(cdb->requested_service_action);
7478 	switch (cdb->options & RSO_OPTIONS_MASK) {
7479 	case RSO_OPTIONS_ALL:
7480 		num = 0;
7481 		for (i = 0; i < 256; i++) {
7482 			entry = &ctl_cmd_table[i];
7483 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7484 				for (j = 0; j < 32; j++) {
7485 					sentry = &((const struct ctl_cmd_entry *)
7486 					    entry->execute)[j];
7487 					if (ctl_cmd_applicable(
7488 					    lun->be_lun->lun_type, sentry))
7489 						num++;
7490 				}
7491 			} else {
7492 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7493 				    entry))
7494 					num++;
7495 			}
7496 		}
7497 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7498 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7499 		break;
7500 	case RSO_OPTIONS_OC:
7501 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7502 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7503 					      /*sks_valid*/ 1,
7504 					      /*command*/ 1,
7505 					      /*field*/ 2,
7506 					      /*bit_valid*/ 1,
7507 					      /*bit*/ 2);
7508 			ctl_done((union ctl_io *)ctsio);
7509 			return (CTL_RETVAL_COMPLETE);
7510 		}
7511 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7512 		break;
7513 	case RSO_OPTIONS_OC_SA:
7514 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7515 		    service_action >= 32) {
7516 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7517 					      /*sks_valid*/ 1,
7518 					      /*command*/ 1,
7519 					      /*field*/ 2,
7520 					      /*bit_valid*/ 1,
7521 					      /*bit*/ 2);
7522 			ctl_done((union ctl_io *)ctsio);
7523 			return (CTL_RETVAL_COMPLETE);
7524 		}
7525 		/* FALLTHROUGH */
7526 	case RSO_OPTIONS_OC_ASA:
7527 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7528 		break;
7529 	default:
7530 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7531 				      /*sks_valid*/ 1,
7532 				      /*command*/ 1,
7533 				      /*field*/ 2,
7534 				      /*bit_valid*/ 1,
7535 				      /*bit*/ 2);
7536 		ctl_done((union ctl_io *)ctsio);
7537 		return (CTL_RETVAL_COMPLETE);
7538 	}
7539 
7540 	alloc_len = scsi_4btoul(cdb->length);
7541 
7542 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7543 	ctsio->kern_sg_entries = 0;
7544 	ctsio->kern_rel_offset = 0;
7545 	ctsio->kern_data_len = min(total_len, alloc_len);
7546 	ctsio->kern_total_len = ctsio->kern_data_len;
7547 
7548 	switch (cdb->options & RSO_OPTIONS_MASK) {
7549 	case RSO_OPTIONS_ALL:
7550 		all = (struct scsi_report_supported_opcodes_all *)
7551 		    ctsio->kern_data_ptr;
7552 		num = 0;
7553 		for (i = 0; i < 256; i++) {
7554 			entry = &ctl_cmd_table[i];
7555 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7556 				for (j = 0; j < 32; j++) {
7557 					sentry = &((const struct ctl_cmd_entry *)
7558 					    entry->execute)[j];
7559 					if (!ctl_cmd_applicable(
7560 					    lun->be_lun->lun_type, sentry))
7561 						continue;
7562 					descr = &all->descr[num++];
7563 					descr->opcode = i;
7564 					scsi_ulto2b(j, descr->service_action);
7565 					descr->flags = RSO_SERVACTV;
7566 					scsi_ulto2b(sentry->length,
7567 					    descr->cdb_length);
7568 				}
7569 			} else {
7570 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7571 				    entry))
7572 					continue;
7573 				descr = &all->descr[num++];
7574 				descr->opcode = i;
7575 				scsi_ulto2b(0, descr->service_action);
7576 				descr->flags = 0;
7577 				scsi_ulto2b(entry->length, descr->cdb_length);
7578 			}
7579 		}
7580 		scsi_ulto4b(
7581 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7582 		    all->length);
7583 		break;
7584 	case RSO_OPTIONS_OC:
7585 		one = (struct scsi_report_supported_opcodes_one *)
7586 		    ctsio->kern_data_ptr;
7587 		entry = &ctl_cmd_table[opcode];
7588 		goto fill_one;
7589 	case RSO_OPTIONS_OC_SA:
7590 		one = (struct scsi_report_supported_opcodes_one *)
7591 		    ctsio->kern_data_ptr;
7592 		entry = &ctl_cmd_table[opcode];
7593 		entry = &((const struct ctl_cmd_entry *)
7594 		    entry->execute)[service_action];
7595 fill_one:
7596 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7597 			one->support = 3;
7598 			scsi_ulto2b(entry->length, one->cdb_length);
7599 			one->cdb_usage[0] = opcode;
7600 			memcpy(&one->cdb_usage[1], entry->usage,
7601 			    entry->length - 1);
7602 		} else
7603 			one->support = 1;
7604 		break;
7605 	case RSO_OPTIONS_OC_ASA:
7606 		one = (struct scsi_report_supported_opcodes_one *)
7607 		    ctsio->kern_data_ptr;
7608 		entry = &ctl_cmd_table[opcode];
7609 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7610 			entry = &((const struct ctl_cmd_entry *)
7611 			    entry->execute)[service_action];
7612 		} else if (service_action != 0) {
7613 			one->support = 1;
7614 			break;
7615 		}
7616 		goto fill_one;
7617 	}
7618 
7619 	ctl_set_success(ctsio);
7620 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7621 	ctsio->be_move_done = ctl_config_move_done;
7622 	ctl_datamove((union ctl_io *)ctsio);
7623 	return(retval);
7624 }
7625 
7626 int
7627 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7628 {
7629 	struct scsi_report_supported_tmf *cdb;
7630 	struct scsi_report_supported_tmf_ext_data *data;
7631 	int retval;
7632 	int alloc_len, total_len;
7633 
7634 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7635 
7636 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7637 
7638 	retval = CTL_RETVAL_COMPLETE;
7639 
7640 	if (cdb->options & RST_REPD)
7641 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7642 	else
7643 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7644 	alloc_len = scsi_4btoul(cdb->length);
7645 
7646 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7647 	ctsio->kern_sg_entries = 0;
7648 	ctsio->kern_rel_offset = 0;
7649 	ctsio->kern_data_len = min(total_len, alloc_len);
7650 	ctsio->kern_total_len = ctsio->kern_data_len;
7651 
7652 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7653 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7654 	    RST_TRS;
7655 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7656 	data->length = total_len - 4;
7657 
7658 	ctl_set_success(ctsio);
7659 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7660 	ctsio->be_move_done = ctl_config_move_done;
7661 	ctl_datamove((union ctl_io *)ctsio);
7662 	return (retval);
7663 }
7664 
7665 int
7666 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7667 {
7668 	struct scsi_report_timestamp *cdb;
7669 	struct scsi_report_timestamp_data *data;
7670 	struct timeval tv;
7671 	int64_t timestamp;
7672 	int retval;
7673 	int alloc_len, total_len;
7674 
7675 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7676 
7677 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7678 
7679 	retval = CTL_RETVAL_COMPLETE;
7680 
7681 	total_len = sizeof(struct scsi_report_timestamp_data);
7682 	alloc_len = scsi_4btoul(cdb->length);
7683 
7684 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7685 	ctsio->kern_sg_entries = 0;
7686 	ctsio->kern_rel_offset = 0;
7687 	ctsio->kern_data_len = min(total_len, alloc_len);
7688 	ctsio->kern_total_len = ctsio->kern_data_len;
7689 
7690 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7691 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7692 	data->origin = RTS_ORIG_OUTSIDE;
7693 	getmicrotime(&tv);
7694 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7695 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7696 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7697 
7698 	ctl_set_success(ctsio);
7699 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7700 	ctsio->be_move_done = ctl_config_move_done;
7701 	ctl_datamove((union ctl_io *)ctsio);
7702 	return (retval);
7703 }
7704 
7705 int
7706 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7707 {
7708 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7709 	struct ctl_lun *lun = CTL_LUN(ctsio);
7710 	struct scsi_per_res_in *cdb;
7711 	int alloc_len, total_len = 0;
7712 	/* struct scsi_per_res_in_rsrv in_data; */
7713 	uint64_t key;
7714 
7715 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7716 
7717 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7718 
7719 	alloc_len = scsi_2btoul(cdb->length);
7720 
7721 retry:
7722 	mtx_lock(&lun->lun_lock);
7723 	switch (cdb->action) {
7724 	case SPRI_RK: /* read keys */
7725 		total_len = sizeof(struct scsi_per_res_in_keys) +
7726 			lun->pr_key_count *
7727 			sizeof(struct scsi_per_res_key);
7728 		break;
7729 	case SPRI_RR: /* read reservation */
7730 		if (lun->flags & CTL_LUN_PR_RESERVED)
7731 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7732 		else
7733 			total_len = sizeof(struct scsi_per_res_in_header);
7734 		break;
7735 	case SPRI_RC: /* report capabilities */
7736 		total_len = sizeof(struct scsi_per_res_cap);
7737 		break;
7738 	case SPRI_RS: /* read full status */
7739 		total_len = sizeof(struct scsi_per_res_in_header) +
7740 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7741 		    lun->pr_key_count;
7742 		break;
7743 	default:
7744 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7745 	}
7746 	mtx_unlock(&lun->lun_lock);
7747 
7748 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7749 	ctsio->kern_rel_offset = 0;
7750 	ctsio->kern_sg_entries = 0;
7751 	ctsio->kern_data_len = min(total_len, alloc_len);
7752 	ctsio->kern_total_len = ctsio->kern_data_len;
7753 
7754 	mtx_lock(&lun->lun_lock);
7755 	switch (cdb->action) {
7756 	case SPRI_RK: { // read keys
7757         struct scsi_per_res_in_keys *res_keys;
7758 		int i, key_count;
7759 
7760 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7761 
7762 		/*
7763 		 * We had to drop the lock to allocate our buffer, which
7764 		 * leaves time for someone to come in with another
7765 		 * persistent reservation.  (That is unlikely, though,
7766 		 * since this should be the only persistent reservation
7767 		 * command active right now.)
7768 		 */
7769 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7770 		    (lun->pr_key_count *
7771 		     sizeof(struct scsi_per_res_key)))){
7772 			mtx_unlock(&lun->lun_lock);
7773 			free(ctsio->kern_data_ptr, M_CTL);
7774 			printf("%s: reservation length changed, retrying\n",
7775 			       __func__);
7776 			goto retry;
7777 		}
7778 
7779 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7780 
7781 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7782 			     lun->pr_key_count, res_keys->header.length);
7783 
7784 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7785 			if ((key = ctl_get_prkey(lun, i)) == 0)
7786 				continue;
7787 
7788 			/*
7789 			 * We used lun->pr_key_count to calculate the
7790 			 * size to allocate.  If it turns out the number of
7791 			 * initiators with the registered flag set is
7792 			 * larger than that (i.e. they haven't been kept in
7793 			 * sync), we've got a problem.
7794 			 */
7795 			if (key_count >= lun->pr_key_count) {
7796 				key_count++;
7797 				continue;
7798 			}
7799 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7800 			key_count++;
7801 		}
7802 		break;
7803 	}
7804 	case SPRI_RR: { // read reservation
7805 		struct scsi_per_res_in_rsrv *res;
7806 		int tmp_len, header_only;
7807 
7808 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7809 
7810 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7811 
7812 		if (lun->flags & CTL_LUN_PR_RESERVED)
7813 		{
7814 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7815 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7816 				    res->header.length);
7817 			header_only = 0;
7818 		} else {
7819 			tmp_len = sizeof(struct scsi_per_res_in_header);
7820 			scsi_ulto4b(0, res->header.length);
7821 			header_only = 1;
7822 		}
7823 
7824 		/*
7825 		 * We had to drop the lock to allocate our buffer, which
7826 		 * leaves time for someone to come in with another
7827 		 * persistent reservation.  (That is unlikely, though,
7828 		 * since this should be the only persistent reservation
7829 		 * command active right now.)
7830 		 */
7831 		if (tmp_len != total_len) {
7832 			mtx_unlock(&lun->lun_lock);
7833 			free(ctsio->kern_data_ptr, M_CTL);
7834 			printf("%s: reservation status changed, retrying\n",
7835 			       __func__);
7836 			goto retry;
7837 		}
7838 
7839 		/*
7840 		 * No reservation held, so we're done.
7841 		 */
7842 		if (header_only != 0)
7843 			break;
7844 
7845 		/*
7846 		 * If the registration is an All Registrants type, the key
7847 		 * is 0, since it doesn't really matter.
7848 		 */
7849 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7850 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7851 			    res->data.reservation);
7852 		}
7853 		res->data.scopetype = lun->pr_res_type;
7854 		break;
7855 	}
7856 	case SPRI_RC:     //report capabilities
7857 	{
7858 		struct scsi_per_res_cap *res_cap;
7859 		uint16_t type_mask;
7860 
7861 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7862 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7863 		res_cap->flags1 = SPRI_CRH;
7864 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7865 		type_mask = SPRI_TM_WR_EX_AR |
7866 			    SPRI_TM_EX_AC_RO |
7867 			    SPRI_TM_WR_EX_RO |
7868 			    SPRI_TM_EX_AC |
7869 			    SPRI_TM_WR_EX |
7870 			    SPRI_TM_EX_AC_AR;
7871 		scsi_ulto2b(type_mask, res_cap->type_mask);
7872 		break;
7873 	}
7874 	case SPRI_RS: { // read full status
7875 		struct scsi_per_res_in_full *res_status;
7876 		struct scsi_per_res_in_full_desc *res_desc;
7877 		struct ctl_port *port;
7878 		int i, len;
7879 
7880 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7881 
7882 		/*
7883 		 * We had to drop the lock to allocate our buffer, which
7884 		 * leaves time for someone to come in with another
7885 		 * persistent reservation.  (That is unlikely, though,
7886 		 * since this should be the only persistent reservation
7887 		 * command active right now.)
7888 		 */
7889 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7890 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7891 		     lun->pr_key_count)){
7892 			mtx_unlock(&lun->lun_lock);
7893 			free(ctsio->kern_data_ptr, M_CTL);
7894 			printf("%s: reservation length changed, retrying\n",
7895 			       __func__);
7896 			goto retry;
7897 		}
7898 
7899 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7900 
7901 		res_desc = &res_status->desc[0];
7902 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7903 			if ((key = ctl_get_prkey(lun, i)) == 0)
7904 				continue;
7905 
7906 			scsi_u64to8b(key, res_desc->res_key.key);
7907 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7908 			    (lun->pr_res_idx == i ||
7909 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7910 				res_desc->flags = SPRI_FULL_R_HOLDER;
7911 				res_desc->scopetype = lun->pr_res_type;
7912 			}
7913 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7914 			    res_desc->rel_trgt_port_id);
7915 			len = 0;
7916 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7917 			if (port != NULL)
7918 				len = ctl_create_iid(port,
7919 				    i % CTL_MAX_INIT_PER_PORT,
7920 				    res_desc->transport_id);
7921 			scsi_ulto4b(len, res_desc->additional_length);
7922 			res_desc = (struct scsi_per_res_in_full_desc *)
7923 			    &res_desc->transport_id[len];
7924 		}
7925 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7926 		    res_status->header.length);
7927 		break;
7928 	}
7929 	default:
7930 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7931 	}
7932 	mtx_unlock(&lun->lun_lock);
7933 
7934 	ctl_set_success(ctsio);
7935 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7936 	ctsio->be_move_done = ctl_config_move_done;
7937 	ctl_datamove((union ctl_io *)ctsio);
7938 	return (CTL_RETVAL_COMPLETE);
7939 }
7940 
7941 /*
7942  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7943  * it should return.
7944  */
7945 static int
7946 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7947 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7948 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7949 		struct scsi_per_res_out_parms* param)
7950 {
7951 	union ctl_ha_msg persis_io;
7952 	int i;
7953 
7954 	mtx_lock(&lun->lun_lock);
7955 	if (sa_res_key == 0) {
7956 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7957 			/* validate scope and type */
7958 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7959 			     SPR_LU_SCOPE) {
7960 				mtx_unlock(&lun->lun_lock);
7961 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7962 						      /*sks_valid*/ 1,
7963 						      /*command*/ 1,
7964 						      /*field*/ 2,
7965 						      /*bit_valid*/ 1,
7966 						      /*bit*/ 4);
7967 				ctl_done((union ctl_io *)ctsio);
7968 				return (1);
7969 			}
7970 
7971 		        if (type>8 || type==2 || type==4 || type==0) {
7972 				mtx_unlock(&lun->lun_lock);
7973 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7974        	           				      /*sks_valid*/ 1,
7975 						      /*command*/ 1,
7976 						      /*field*/ 2,
7977 						      /*bit_valid*/ 1,
7978 						      /*bit*/ 0);
7979 				ctl_done((union ctl_io *)ctsio);
7980 				return (1);
7981 		        }
7982 
7983 			/*
7984 			 * Unregister everybody else and build UA for
7985 			 * them
7986 			 */
7987 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7988 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7989 					continue;
7990 
7991 				ctl_clr_prkey(lun, i);
7992 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7993 			}
7994 			lun->pr_key_count = 1;
7995 			lun->pr_res_type = type;
7996 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7997 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7998 				lun->pr_res_idx = residx;
7999 			lun->pr_generation++;
8000 			mtx_unlock(&lun->lun_lock);
8001 
8002 			/* send msg to other side */
8003 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8004 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8005 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8006 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8007 			persis_io.pr.pr_info.res_type = type;
8008 			memcpy(persis_io.pr.pr_info.sa_res_key,
8009 			       param->serv_act_res_key,
8010 			       sizeof(param->serv_act_res_key));
8011 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8012 			    sizeof(persis_io.pr), M_WAITOK);
8013 		} else {
8014 			/* not all registrants */
8015 			mtx_unlock(&lun->lun_lock);
8016 			free(ctsio->kern_data_ptr, M_CTL);
8017 			ctl_set_invalid_field(ctsio,
8018 					      /*sks_valid*/ 1,
8019 					      /*command*/ 0,
8020 					      /*field*/ 8,
8021 					      /*bit_valid*/ 0,
8022 					      /*bit*/ 0);
8023 			ctl_done((union ctl_io *)ctsio);
8024 			return (1);
8025 		}
8026 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8027 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8028 		int found = 0;
8029 
8030 		if (res_key == sa_res_key) {
8031 			/* special case */
8032 			/*
8033 			 * The spec implies this is not good but doesn't
8034 			 * say what to do. There are two choices either
8035 			 * generate a res conflict or check condition
8036 			 * with illegal field in parameter data. Since
8037 			 * that is what is done when the sa_res_key is
8038 			 * zero I'll take that approach since this has
8039 			 * to do with the sa_res_key.
8040 			 */
8041 			mtx_unlock(&lun->lun_lock);
8042 			free(ctsio->kern_data_ptr, M_CTL);
8043 			ctl_set_invalid_field(ctsio,
8044 					      /*sks_valid*/ 1,
8045 					      /*command*/ 0,
8046 					      /*field*/ 8,
8047 					      /*bit_valid*/ 0,
8048 					      /*bit*/ 0);
8049 			ctl_done((union ctl_io *)ctsio);
8050 			return (1);
8051 		}
8052 
8053 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8054 			if (ctl_get_prkey(lun, i) != sa_res_key)
8055 				continue;
8056 
8057 			found = 1;
8058 			ctl_clr_prkey(lun, i);
8059 			lun->pr_key_count--;
8060 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8061 		}
8062 		if (!found) {
8063 			mtx_unlock(&lun->lun_lock);
8064 			free(ctsio->kern_data_ptr, M_CTL);
8065 			ctl_set_reservation_conflict(ctsio);
8066 			ctl_done((union ctl_io *)ctsio);
8067 			return (CTL_RETVAL_COMPLETE);
8068 		}
8069 		lun->pr_generation++;
8070 		mtx_unlock(&lun->lun_lock);
8071 
8072 		/* send msg to other side */
8073 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8074 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8075 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8076 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8077 		persis_io.pr.pr_info.res_type = type;
8078 		memcpy(persis_io.pr.pr_info.sa_res_key,
8079 		       param->serv_act_res_key,
8080 		       sizeof(param->serv_act_res_key));
8081 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8082 		    sizeof(persis_io.pr), M_WAITOK);
8083 	} else {
8084 		/* Reserved but not all registrants */
8085 		/* sa_res_key is res holder */
8086 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
8087 			/* validate scope and type */
8088 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8089 			     SPR_LU_SCOPE) {
8090 				mtx_unlock(&lun->lun_lock);
8091 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8092 						      /*sks_valid*/ 1,
8093 						      /*command*/ 1,
8094 						      /*field*/ 2,
8095 						      /*bit_valid*/ 1,
8096 						      /*bit*/ 4);
8097 				ctl_done((union ctl_io *)ctsio);
8098 				return (1);
8099 			}
8100 
8101 			if (type>8 || type==2 || type==4 || type==0) {
8102 				mtx_unlock(&lun->lun_lock);
8103 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8104 						      /*sks_valid*/ 1,
8105 						      /*command*/ 1,
8106 						      /*field*/ 2,
8107 						      /*bit_valid*/ 1,
8108 						      /*bit*/ 0);
8109 				ctl_done((union ctl_io *)ctsio);
8110 				return (1);
8111 			}
8112 
8113 			/*
8114 			 * Do the following:
8115 			 * if sa_res_key != res_key remove all
8116 			 * registrants w/sa_res_key and generate UA
8117 			 * for these registrants(Registrations
8118 			 * Preempted) if it wasn't an exclusive
8119 			 * reservation generate UA(Reservations
8120 			 * Preempted) for all other registered nexuses
8121 			 * if the type has changed. Establish the new
8122 			 * reservation and holder. If res_key and
8123 			 * sa_res_key are the same do the above
8124 			 * except don't unregister the res holder.
8125 			 */
8126 
8127 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8128 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8129 					continue;
8130 
8131 				if (sa_res_key == ctl_get_prkey(lun, i)) {
8132 					ctl_clr_prkey(lun, i);
8133 					lun->pr_key_count--;
8134 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8135 				} else if (type != lun->pr_res_type &&
8136 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8137 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8138 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8139 				}
8140 			}
8141 			lun->pr_res_type = type;
8142 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8143 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8144 				lun->pr_res_idx = residx;
8145 			else
8146 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8147 			lun->pr_generation++;
8148 			mtx_unlock(&lun->lun_lock);
8149 
8150 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8151 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8152 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8153 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8154 			persis_io.pr.pr_info.res_type = type;
8155 			memcpy(persis_io.pr.pr_info.sa_res_key,
8156 			       param->serv_act_res_key,
8157 			       sizeof(param->serv_act_res_key));
8158 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8159 			    sizeof(persis_io.pr), M_WAITOK);
8160 		} else {
8161 			/*
8162 			 * sa_res_key is not the res holder just
8163 			 * remove registrants
8164 			 */
8165 			int found=0;
8166 
8167 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8168 				if (sa_res_key != ctl_get_prkey(lun, i))
8169 					continue;
8170 
8171 				found = 1;
8172 				ctl_clr_prkey(lun, i);
8173 				lun->pr_key_count--;
8174 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8175 			}
8176 
8177 			if (!found) {
8178 				mtx_unlock(&lun->lun_lock);
8179 				free(ctsio->kern_data_ptr, M_CTL);
8180 				ctl_set_reservation_conflict(ctsio);
8181 				ctl_done((union ctl_io *)ctsio);
8182 		        	return (1);
8183 			}
8184 			lun->pr_generation++;
8185 			mtx_unlock(&lun->lun_lock);
8186 
8187 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8188 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8189 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8190 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8191 			persis_io.pr.pr_info.res_type = type;
8192 			memcpy(persis_io.pr.pr_info.sa_res_key,
8193 			       param->serv_act_res_key,
8194 			       sizeof(param->serv_act_res_key));
8195 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8196 			    sizeof(persis_io.pr), M_WAITOK);
8197 		}
8198 	}
8199 	return (0);
8200 }
8201 
8202 static void
8203 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8204 {
8205 	uint64_t sa_res_key;
8206 	int i;
8207 
8208 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8209 
8210 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8211 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8212 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8213 		if (sa_res_key == 0) {
8214 			/*
8215 			 * Unregister everybody else and build UA for
8216 			 * them
8217 			 */
8218 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8219 				if (i == msg->pr.pr_info.residx ||
8220 				    ctl_get_prkey(lun, i) == 0)
8221 					continue;
8222 
8223 				ctl_clr_prkey(lun, i);
8224 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8225 			}
8226 
8227 			lun->pr_key_count = 1;
8228 			lun->pr_res_type = msg->pr.pr_info.res_type;
8229 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8230 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8231 				lun->pr_res_idx = msg->pr.pr_info.residx;
8232 		} else {
8233 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8234 				if (sa_res_key == ctl_get_prkey(lun, i))
8235 					continue;
8236 
8237 				ctl_clr_prkey(lun, i);
8238 				lun->pr_key_count--;
8239 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8240 			}
8241 		}
8242 	} else {
8243 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8244 			if (i == msg->pr.pr_info.residx ||
8245 			    ctl_get_prkey(lun, i) == 0)
8246 				continue;
8247 
8248 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8249 				ctl_clr_prkey(lun, i);
8250 				lun->pr_key_count--;
8251 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8252 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8253 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8254 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8255 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8256 			}
8257 		}
8258 		lun->pr_res_type = msg->pr.pr_info.res_type;
8259 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8260 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8261 			lun->pr_res_idx = msg->pr.pr_info.residx;
8262 		else
8263 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8264 	}
8265 	lun->pr_generation++;
8266 
8267 }
8268 
8269 int
8270 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8271 {
8272 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8273 	struct ctl_lun *lun = CTL_LUN(ctsio);
8274 	int retval;
8275 	u_int32_t param_len;
8276 	struct scsi_per_res_out *cdb;
8277 	struct scsi_per_res_out_parms* param;
8278 	uint32_t residx;
8279 	uint64_t res_key, sa_res_key, key;
8280 	uint8_t type;
8281 	union ctl_ha_msg persis_io;
8282 	int    i;
8283 
8284 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8285 
8286 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8287 	retval = CTL_RETVAL_COMPLETE;
8288 
8289 	/*
8290 	 * We only support whole-LUN scope.  The scope & type are ignored for
8291 	 * register, register and ignore existing key and clear.
8292 	 * We sometimes ignore scope and type on preempts too!!
8293 	 * Verify reservation type here as well.
8294 	 */
8295 	type = cdb->scope_type & SPR_TYPE_MASK;
8296 	if ((cdb->action == SPRO_RESERVE)
8297 	 || (cdb->action == SPRO_RELEASE)) {
8298 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8299 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8300 					      /*sks_valid*/ 1,
8301 					      /*command*/ 1,
8302 					      /*field*/ 2,
8303 					      /*bit_valid*/ 1,
8304 					      /*bit*/ 4);
8305 			ctl_done((union ctl_io *)ctsio);
8306 			return (CTL_RETVAL_COMPLETE);
8307 		}
8308 
8309 		if (type>8 || type==2 || type==4 || type==0) {
8310 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8311 					      /*sks_valid*/ 1,
8312 					      /*command*/ 1,
8313 					      /*field*/ 2,
8314 					      /*bit_valid*/ 1,
8315 					      /*bit*/ 0);
8316 			ctl_done((union ctl_io *)ctsio);
8317 			return (CTL_RETVAL_COMPLETE);
8318 		}
8319 	}
8320 
8321 	param_len = scsi_4btoul(cdb->length);
8322 
8323 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8324 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8325 		ctsio->kern_data_len = param_len;
8326 		ctsio->kern_total_len = param_len;
8327 		ctsio->kern_rel_offset = 0;
8328 		ctsio->kern_sg_entries = 0;
8329 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8330 		ctsio->be_move_done = ctl_config_move_done;
8331 		ctl_datamove((union ctl_io *)ctsio);
8332 
8333 		return (CTL_RETVAL_COMPLETE);
8334 	}
8335 
8336 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8337 
8338 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8339 	res_key = scsi_8btou64(param->res_key.key);
8340 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8341 
8342 	/*
8343 	 * Validate the reservation key here except for SPRO_REG_IGNO
8344 	 * This must be done for all other service actions
8345 	 */
8346 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8347 		mtx_lock(&lun->lun_lock);
8348 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8349 			if (res_key != key) {
8350 				/*
8351 				 * The current key passed in doesn't match
8352 				 * the one the initiator previously
8353 				 * registered.
8354 				 */
8355 				mtx_unlock(&lun->lun_lock);
8356 				free(ctsio->kern_data_ptr, M_CTL);
8357 				ctl_set_reservation_conflict(ctsio);
8358 				ctl_done((union ctl_io *)ctsio);
8359 				return (CTL_RETVAL_COMPLETE);
8360 			}
8361 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8362 			/*
8363 			 * We are not registered
8364 			 */
8365 			mtx_unlock(&lun->lun_lock);
8366 			free(ctsio->kern_data_ptr, M_CTL);
8367 			ctl_set_reservation_conflict(ctsio);
8368 			ctl_done((union ctl_io *)ctsio);
8369 			return (CTL_RETVAL_COMPLETE);
8370 		} else if (res_key != 0) {
8371 			/*
8372 			 * We are not registered and trying to register but
8373 			 * the register key isn't zero.
8374 			 */
8375 			mtx_unlock(&lun->lun_lock);
8376 			free(ctsio->kern_data_ptr, M_CTL);
8377 			ctl_set_reservation_conflict(ctsio);
8378 			ctl_done((union ctl_io *)ctsio);
8379 			return (CTL_RETVAL_COMPLETE);
8380 		}
8381 		mtx_unlock(&lun->lun_lock);
8382 	}
8383 
8384 	switch (cdb->action & SPRO_ACTION_MASK) {
8385 	case SPRO_REGISTER:
8386 	case SPRO_REG_IGNO: {
8387 		/*
8388 		 * We don't support any of these options, as we report in
8389 		 * the read capabilities request (see
8390 		 * ctl_persistent_reserve_in(), above).
8391 		 */
8392 		if ((param->flags & SPR_SPEC_I_PT)
8393 		 || (param->flags & SPR_ALL_TG_PT)
8394 		 || (param->flags & SPR_APTPL)) {
8395 			int bit_ptr;
8396 
8397 			if (param->flags & SPR_APTPL)
8398 				bit_ptr = 0;
8399 			else if (param->flags & SPR_ALL_TG_PT)
8400 				bit_ptr = 2;
8401 			else /* SPR_SPEC_I_PT */
8402 				bit_ptr = 3;
8403 
8404 			free(ctsio->kern_data_ptr, M_CTL);
8405 			ctl_set_invalid_field(ctsio,
8406 					      /*sks_valid*/ 1,
8407 					      /*command*/ 0,
8408 					      /*field*/ 20,
8409 					      /*bit_valid*/ 1,
8410 					      /*bit*/ bit_ptr);
8411 			ctl_done((union ctl_io *)ctsio);
8412 			return (CTL_RETVAL_COMPLETE);
8413 		}
8414 
8415 		mtx_lock(&lun->lun_lock);
8416 
8417 		/*
8418 		 * The initiator wants to clear the
8419 		 * key/unregister.
8420 		 */
8421 		if (sa_res_key == 0) {
8422 			if ((res_key == 0
8423 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8424 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8425 			  && ctl_get_prkey(lun, residx) == 0)) {
8426 				mtx_unlock(&lun->lun_lock);
8427 				goto done;
8428 			}
8429 
8430 			ctl_clr_prkey(lun, residx);
8431 			lun->pr_key_count--;
8432 
8433 			if (residx == lun->pr_res_idx) {
8434 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8435 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8436 
8437 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8438 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8439 				    lun->pr_key_count) {
8440 					/*
8441 					 * If the reservation is a registrants
8442 					 * only type we need to generate a UA
8443 					 * for other registered inits.  The
8444 					 * sense code should be RESERVATIONS
8445 					 * RELEASED
8446 					 */
8447 
8448 					for (i = softc->init_min; i < softc->init_max; i++){
8449 						if (ctl_get_prkey(lun, i) == 0)
8450 							continue;
8451 						ctl_est_ua(lun, i,
8452 						    CTL_UA_RES_RELEASE);
8453 					}
8454 				}
8455 				lun->pr_res_type = 0;
8456 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8457 				if (lun->pr_key_count==0) {
8458 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8459 					lun->pr_res_type = 0;
8460 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8461 				}
8462 			}
8463 			lun->pr_generation++;
8464 			mtx_unlock(&lun->lun_lock);
8465 
8466 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8467 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8468 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8469 			persis_io.pr.pr_info.residx = residx;
8470 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8471 			    sizeof(persis_io.pr), M_WAITOK);
8472 		} else /* sa_res_key != 0 */ {
8473 			/*
8474 			 * If we aren't registered currently then increment
8475 			 * the key count and set the registered flag.
8476 			 */
8477 			ctl_alloc_prkey(lun, residx);
8478 			if (ctl_get_prkey(lun, residx) == 0)
8479 				lun->pr_key_count++;
8480 			ctl_set_prkey(lun, residx, sa_res_key);
8481 			lun->pr_generation++;
8482 			mtx_unlock(&lun->lun_lock);
8483 
8484 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8485 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8486 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8487 			persis_io.pr.pr_info.residx = residx;
8488 			memcpy(persis_io.pr.pr_info.sa_res_key,
8489 			       param->serv_act_res_key,
8490 			       sizeof(param->serv_act_res_key));
8491 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8492 			    sizeof(persis_io.pr), M_WAITOK);
8493 		}
8494 
8495 		break;
8496 	}
8497 	case SPRO_RESERVE:
8498 		mtx_lock(&lun->lun_lock);
8499 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8500 			/*
8501 			 * if this isn't the reservation holder and it's
8502 			 * not a "all registrants" type or if the type is
8503 			 * different then we have a conflict
8504 			 */
8505 			if ((lun->pr_res_idx != residx
8506 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8507 			 || lun->pr_res_type != type) {
8508 				mtx_unlock(&lun->lun_lock);
8509 				free(ctsio->kern_data_ptr, M_CTL);
8510 				ctl_set_reservation_conflict(ctsio);
8511 				ctl_done((union ctl_io *)ctsio);
8512 				return (CTL_RETVAL_COMPLETE);
8513 			}
8514 			mtx_unlock(&lun->lun_lock);
8515 		} else /* create a reservation */ {
8516 			/*
8517 			 * If it's not an "all registrants" type record
8518 			 * reservation holder
8519 			 */
8520 			if (type != SPR_TYPE_WR_EX_AR
8521 			 && type != SPR_TYPE_EX_AC_AR)
8522 				lun->pr_res_idx = residx; /* Res holder */
8523 			else
8524 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8525 
8526 			lun->flags |= CTL_LUN_PR_RESERVED;
8527 			lun->pr_res_type = type;
8528 
8529 			mtx_unlock(&lun->lun_lock);
8530 
8531 			/* send msg to other side */
8532 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8533 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8534 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8535 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8536 			persis_io.pr.pr_info.res_type = type;
8537 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8538 			    sizeof(persis_io.pr), M_WAITOK);
8539 		}
8540 		break;
8541 
8542 	case SPRO_RELEASE:
8543 		mtx_lock(&lun->lun_lock);
8544 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8545 			/* No reservation exists return good status */
8546 			mtx_unlock(&lun->lun_lock);
8547 			goto done;
8548 		}
8549 		/*
8550 		 * Is this nexus a reservation holder?
8551 		 */
8552 		if (lun->pr_res_idx != residx
8553 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8554 			/*
8555 			 * not a res holder return good status but
8556 			 * do nothing
8557 			 */
8558 			mtx_unlock(&lun->lun_lock);
8559 			goto done;
8560 		}
8561 
8562 		if (lun->pr_res_type != type) {
8563 			mtx_unlock(&lun->lun_lock);
8564 			free(ctsio->kern_data_ptr, M_CTL);
8565 			ctl_set_illegal_pr_release(ctsio);
8566 			ctl_done((union ctl_io *)ctsio);
8567 			return (CTL_RETVAL_COMPLETE);
8568 		}
8569 
8570 		/* okay to release */
8571 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8572 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8573 		lun->pr_res_type = 0;
8574 
8575 		/*
8576 		 * If this isn't an exclusive access reservation and NUAR
8577 		 * is not set, generate UA for all other registrants.
8578 		 */
8579 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8580 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8581 			for (i = softc->init_min; i < softc->init_max; i++) {
8582 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8583 					continue;
8584 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8585 			}
8586 		}
8587 		mtx_unlock(&lun->lun_lock);
8588 
8589 		/* Send msg to other side */
8590 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8591 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8592 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8593 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8594 		     sizeof(persis_io.pr), M_WAITOK);
8595 		break;
8596 
8597 	case SPRO_CLEAR:
8598 		/* send msg to other side */
8599 
8600 		mtx_lock(&lun->lun_lock);
8601 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8602 		lun->pr_res_type = 0;
8603 		lun->pr_key_count = 0;
8604 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8605 
8606 		ctl_clr_prkey(lun, residx);
8607 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8608 			if (ctl_get_prkey(lun, i) != 0) {
8609 				ctl_clr_prkey(lun, i);
8610 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8611 			}
8612 		lun->pr_generation++;
8613 		mtx_unlock(&lun->lun_lock);
8614 
8615 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8616 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8617 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8618 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8619 		     sizeof(persis_io.pr), M_WAITOK);
8620 		break;
8621 
8622 	case SPRO_PREEMPT:
8623 	case SPRO_PRE_ABO: {
8624 		int nretval;
8625 
8626 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8627 					  residx, ctsio, cdb, param);
8628 		if (nretval != 0)
8629 			return (CTL_RETVAL_COMPLETE);
8630 		break;
8631 	}
8632 	default:
8633 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8634 	}
8635 
8636 done:
8637 	free(ctsio->kern_data_ptr, M_CTL);
8638 	ctl_set_success(ctsio);
8639 	ctl_done((union ctl_io *)ctsio);
8640 
8641 	return (retval);
8642 }
8643 
8644 /*
8645  * This routine is for handling a message from the other SC pertaining to
8646  * persistent reserve out. All the error checking will have been done
8647  * so only performing the action need be done here to keep the two
8648  * in sync.
8649  */
8650 static void
8651 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8652 {
8653 	struct ctl_softc *softc = CTL_SOFTC(io);
8654 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8655 	struct ctl_lun *lun;
8656 	int i;
8657 	uint32_t residx, targ_lun;
8658 
8659 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8660 	mtx_lock(&softc->ctl_lock);
8661 	if (targ_lun >= ctl_max_luns ||
8662 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8663 		mtx_unlock(&softc->ctl_lock);
8664 		return;
8665 	}
8666 	mtx_lock(&lun->lun_lock);
8667 	mtx_unlock(&softc->ctl_lock);
8668 	if (lun->flags & CTL_LUN_DISABLED) {
8669 		mtx_unlock(&lun->lun_lock);
8670 		return;
8671 	}
8672 	residx = ctl_get_initindex(&msg->hdr.nexus);
8673 	switch(msg->pr.pr_info.action) {
8674 	case CTL_PR_REG_KEY:
8675 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8676 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8677 			lun->pr_key_count++;
8678 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8679 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8680 		lun->pr_generation++;
8681 		break;
8682 
8683 	case CTL_PR_UNREG_KEY:
8684 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8685 		lun->pr_key_count--;
8686 
8687 		/* XXX Need to see if the reservation has been released */
8688 		/* if so do we need to generate UA? */
8689 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8690 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8691 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8692 
8693 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8694 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8695 			    lun->pr_key_count) {
8696 				/*
8697 				 * If the reservation is a registrants
8698 				 * only type we need to generate a UA
8699 				 * for other registered inits.  The
8700 				 * sense code should be RESERVATIONS
8701 				 * RELEASED
8702 				 */
8703 
8704 				for (i = softc->init_min; i < softc->init_max; i++) {
8705 					if (ctl_get_prkey(lun, i) == 0)
8706 						continue;
8707 
8708 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8709 				}
8710 			}
8711 			lun->pr_res_type = 0;
8712 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8713 			if (lun->pr_key_count==0) {
8714 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8715 				lun->pr_res_type = 0;
8716 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8717 			}
8718 		}
8719 		lun->pr_generation++;
8720 		break;
8721 
8722 	case CTL_PR_RESERVE:
8723 		lun->flags |= CTL_LUN_PR_RESERVED;
8724 		lun->pr_res_type = msg->pr.pr_info.res_type;
8725 		lun->pr_res_idx = msg->pr.pr_info.residx;
8726 
8727 		break;
8728 
8729 	case CTL_PR_RELEASE:
8730 		/*
8731 		 * If this isn't an exclusive access reservation and NUAR
8732 		 * is not set, generate UA for all other registrants.
8733 		 */
8734 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8735 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8736 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8737 			for (i = softc->init_min; i < softc->init_max; i++) {
8738 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8739 					continue;
8740 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8741 			}
8742 		}
8743 
8744 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8745 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8746 		lun->pr_res_type = 0;
8747 		break;
8748 
8749 	case CTL_PR_PREEMPT:
8750 		ctl_pro_preempt_other(lun, msg);
8751 		break;
8752 	case CTL_PR_CLEAR:
8753 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8754 		lun->pr_res_type = 0;
8755 		lun->pr_key_count = 0;
8756 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8757 
8758 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8759 			if (ctl_get_prkey(lun, i) == 0)
8760 				continue;
8761 			ctl_clr_prkey(lun, i);
8762 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8763 		}
8764 		lun->pr_generation++;
8765 		break;
8766 	}
8767 
8768 	mtx_unlock(&lun->lun_lock);
8769 }
8770 
8771 int
8772 ctl_read_write(struct ctl_scsiio *ctsio)
8773 {
8774 	struct ctl_lun *lun = CTL_LUN(ctsio);
8775 	struct ctl_lba_len_flags *lbalen;
8776 	uint64_t lba;
8777 	uint32_t num_blocks;
8778 	int flags, retval;
8779 	int isread;
8780 
8781 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8782 
8783 	flags = 0;
8784 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8785 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8786 	switch (ctsio->cdb[0]) {
8787 	case READ_6:
8788 	case WRITE_6: {
8789 		struct scsi_rw_6 *cdb;
8790 
8791 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8792 
8793 		lba = scsi_3btoul(cdb->addr);
8794 		/* only 5 bits are valid in the most significant address byte */
8795 		lba &= 0x1fffff;
8796 		num_blocks = cdb->length;
8797 		/*
8798 		 * This is correct according to SBC-2.
8799 		 */
8800 		if (num_blocks == 0)
8801 			num_blocks = 256;
8802 		break;
8803 	}
8804 	case READ_10:
8805 	case WRITE_10: {
8806 		struct scsi_rw_10 *cdb;
8807 
8808 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8809 		if (cdb->byte2 & SRW10_FUA)
8810 			flags |= CTL_LLF_FUA;
8811 		if (cdb->byte2 & SRW10_DPO)
8812 			flags |= CTL_LLF_DPO;
8813 		lba = scsi_4btoul(cdb->addr);
8814 		num_blocks = scsi_2btoul(cdb->length);
8815 		break;
8816 	}
8817 	case WRITE_VERIFY_10: {
8818 		struct scsi_write_verify_10 *cdb;
8819 
8820 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8821 		flags |= CTL_LLF_FUA;
8822 		if (cdb->byte2 & SWV_DPO)
8823 			flags |= CTL_LLF_DPO;
8824 		lba = scsi_4btoul(cdb->addr);
8825 		num_blocks = scsi_2btoul(cdb->length);
8826 		break;
8827 	}
8828 	case READ_12:
8829 	case WRITE_12: {
8830 		struct scsi_rw_12 *cdb;
8831 
8832 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8833 		if (cdb->byte2 & SRW12_FUA)
8834 			flags |= CTL_LLF_FUA;
8835 		if (cdb->byte2 & SRW12_DPO)
8836 			flags |= CTL_LLF_DPO;
8837 		lba = scsi_4btoul(cdb->addr);
8838 		num_blocks = scsi_4btoul(cdb->length);
8839 		break;
8840 	}
8841 	case WRITE_VERIFY_12: {
8842 		struct scsi_write_verify_12 *cdb;
8843 
8844 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8845 		flags |= CTL_LLF_FUA;
8846 		if (cdb->byte2 & SWV_DPO)
8847 			flags |= CTL_LLF_DPO;
8848 		lba = scsi_4btoul(cdb->addr);
8849 		num_blocks = scsi_4btoul(cdb->length);
8850 		break;
8851 	}
8852 	case READ_16:
8853 	case WRITE_16: {
8854 		struct scsi_rw_16 *cdb;
8855 
8856 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8857 		if (cdb->byte2 & SRW12_FUA)
8858 			flags |= CTL_LLF_FUA;
8859 		if (cdb->byte2 & SRW12_DPO)
8860 			flags |= CTL_LLF_DPO;
8861 		lba = scsi_8btou64(cdb->addr);
8862 		num_blocks = scsi_4btoul(cdb->length);
8863 		break;
8864 	}
8865 	case WRITE_ATOMIC_16: {
8866 		struct scsi_write_atomic_16 *cdb;
8867 
8868 		if (lun->be_lun->atomicblock == 0) {
8869 			ctl_set_invalid_opcode(ctsio);
8870 			ctl_done((union ctl_io *)ctsio);
8871 			return (CTL_RETVAL_COMPLETE);
8872 		}
8873 
8874 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8875 		if (cdb->byte2 & SRW12_FUA)
8876 			flags |= CTL_LLF_FUA;
8877 		if (cdb->byte2 & SRW12_DPO)
8878 			flags |= CTL_LLF_DPO;
8879 		lba = scsi_8btou64(cdb->addr);
8880 		num_blocks = scsi_2btoul(cdb->length);
8881 		if (num_blocks > lun->be_lun->atomicblock) {
8882 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8883 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8884 			    /*bit*/ 0);
8885 			ctl_done((union ctl_io *)ctsio);
8886 			return (CTL_RETVAL_COMPLETE);
8887 		}
8888 		break;
8889 	}
8890 	case WRITE_VERIFY_16: {
8891 		struct scsi_write_verify_16 *cdb;
8892 
8893 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8894 		flags |= CTL_LLF_FUA;
8895 		if (cdb->byte2 & SWV_DPO)
8896 			flags |= CTL_LLF_DPO;
8897 		lba = scsi_8btou64(cdb->addr);
8898 		num_blocks = scsi_4btoul(cdb->length);
8899 		break;
8900 	}
8901 	default:
8902 		/*
8903 		 * We got a command we don't support.  This shouldn't
8904 		 * happen, commands should be filtered out above us.
8905 		 */
8906 		ctl_set_invalid_opcode(ctsio);
8907 		ctl_done((union ctl_io *)ctsio);
8908 
8909 		return (CTL_RETVAL_COMPLETE);
8910 		break; /* NOTREACHED */
8911 	}
8912 
8913 	/*
8914 	 * The first check is to make sure we're in bounds, the second
8915 	 * check is to catch wrap-around problems.  If the lba + num blocks
8916 	 * is less than the lba, then we've wrapped around and the block
8917 	 * range is invalid anyway.
8918 	 */
8919 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8920 	 || ((lba + num_blocks) < lba)) {
8921 		ctl_set_lba_out_of_range(ctsio,
8922 		    MAX(lba, lun->be_lun->maxlba + 1));
8923 		ctl_done((union ctl_io *)ctsio);
8924 		return (CTL_RETVAL_COMPLETE);
8925 	}
8926 
8927 	/*
8928 	 * According to SBC-3, a transfer length of 0 is not an error.
8929 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8930 	 * translates to 256 blocks for those commands.
8931 	 */
8932 	if (num_blocks == 0) {
8933 		ctl_set_success(ctsio);
8934 		ctl_done((union ctl_io *)ctsio);
8935 		return (CTL_RETVAL_COMPLETE);
8936 	}
8937 
8938 	/* Set FUA and/or DPO if caches are disabled. */
8939 	if (isread) {
8940 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8941 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8942 	} else {
8943 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8944 			flags |= CTL_LLF_FUA;
8945 	}
8946 
8947 	lbalen = (struct ctl_lba_len_flags *)
8948 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8949 	lbalen->lba = lba;
8950 	lbalen->len = num_blocks;
8951 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8952 
8953 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8954 	ctsio->kern_rel_offset = 0;
8955 
8956 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8957 
8958 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8959 	return (retval);
8960 }
8961 
8962 static int
8963 ctl_cnw_cont(union ctl_io *io)
8964 {
8965 	struct ctl_lun *lun = CTL_LUN(io);
8966 	struct ctl_scsiio *ctsio;
8967 	struct ctl_lba_len_flags *lbalen;
8968 	int retval;
8969 
8970 	ctsio = &io->scsiio;
8971 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8972 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8973 	lbalen = (struct ctl_lba_len_flags *)
8974 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8975 	lbalen->flags &= ~CTL_LLF_COMPARE;
8976 	lbalen->flags |= CTL_LLF_WRITE;
8977 
8978 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8979 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8980 	return (retval);
8981 }
8982 
8983 int
8984 ctl_cnw(struct ctl_scsiio *ctsio)
8985 {
8986 	struct ctl_lun *lun = CTL_LUN(ctsio);
8987 	struct ctl_lba_len_flags *lbalen;
8988 	uint64_t lba;
8989 	uint32_t num_blocks;
8990 	int flags, retval;
8991 
8992 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8993 
8994 	flags = 0;
8995 	switch (ctsio->cdb[0]) {
8996 	case COMPARE_AND_WRITE: {
8997 		struct scsi_compare_and_write *cdb;
8998 
8999 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9000 		if (cdb->byte2 & SRW10_FUA)
9001 			flags |= CTL_LLF_FUA;
9002 		if (cdb->byte2 & SRW10_DPO)
9003 			flags |= CTL_LLF_DPO;
9004 		lba = scsi_8btou64(cdb->addr);
9005 		num_blocks = cdb->length;
9006 		break;
9007 	}
9008 	default:
9009 		/*
9010 		 * We got a command we don't support.  This shouldn't
9011 		 * happen, commands should be filtered out above us.
9012 		 */
9013 		ctl_set_invalid_opcode(ctsio);
9014 		ctl_done((union ctl_io *)ctsio);
9015 
9016 		return (CTL_RETVAL_COMPLETE);
9017 		break; /* NOTREACHED */
9018 	}
9019 
9020 	/*
9021 	 * The first check is to make sure we're in bounds, the second
9022 	 * check is to catch wrap-around problems.  If the lba + num blocks
9023 	 * is less than the lba, then we've wrapped around and the block
9024 	 * range is invalid anyway.
9025 	 */
9026 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9027 	 || ((lba + num_blocks) < lba)) {
9028 		ctl_set_lba_out_of_range(ctsio,
9029 		    MAX(lba, lun->be_lun->maxlba + 1));
9030 		ctl_done((union ctl_io *)ctsio);
9031 		return (CTL_RETVAL_COMPLETE);
9032 	}
9033 
9034 	/*
9035 	 * According to SBC-3, a transfer length of 0 is not an error.
9036 	 */
9037 	if (num_blocks == 0) {
9038 		ctl_set_success(ctsio);
9039 		ctl_done((union ctl_io *)ctsio);
9040 		return (CTL_RETVAL_COMPLETE);
9041 	}
9042 
9043 	/* Set FUA if write cache is disabled. */
9044 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
9045 		flags |= CTL_LLF_FUA;
9046 
9047 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9048 	ctsio->kern_rel_offset = 0;
9049 
9050 	/*
9051 	 * Set the IO_CONT flag, so that if this I/O gets passed to
9052 	 * ctl_data_submit_done(), it'll get passed back to
9053 	 * ctl_ctl_cnw_cont() for further processing.
9054 	 */
9055 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9056 	ctsio->io_cont = ctl_cnw_cont;
9057 
9058 	lbalen = (struct ctl_lba_len_flags *)
9059 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9060 	lbalen->lba = lba;
9061 	lbalen->len = num_blocks;
9062 	lbalen->flags = CTL_LLF_COMPARE | flags;
9063 
9064 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9065 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9066 	return (retval);
9067 }
9068 
9069 int
9070 ctl_verify(struct ctl_scsiio *ctsio)
9071 {
9072 	struct ctl_lun *lun = CTL_LUN(ctsio);
9073 	struct ctl_lba_len_flags *lbalen;
9074 	uint64_t lba;
9075 	uint32_t num_blocks;
9076 	int bytchk, flags;
9077 	int retval;
9078 
9079 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9080 
9081 	bytchk = 0;
9082 	flags = CTL_LLF_FUA;
9083 	switch (ctsio->cdb[0]) {
9084 	case VERIFY_10: {
9085 		struct scsi_verify_10 *cdb;
9086 
9087 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9088 		if (cdb->byte2 & SVFY_BYTCHK)
9089 			bytchk = 1;
9090 		if (cdb->byte2 & SVFY_DPO)
9091 			flags |= CTL_LLF_DPO;
9092 		lba = scsi_4btoul(cdb->addr);
9093 		num_blocks = scsi_2btoul(cdb->length);
9094 		break;
9095 	}
9096 	case VERIFY_12: {
9097 		struct scsi_verify_12 *cdb;
9098 
9099 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9100 		if (cdb->byte2 & SVFY_BYTCHK)
9101 			bytchk = 1;
9102 		if (cdb->byte2 & SVFY_DPO)
9103 			flags |= CTL_LLF_DPO;
9104 		lba = scsi_4btoul(cdb->addr);
9105 		num_blocks = scsi_4btoul(cdb->length);
9106 		break;
9107 	}
9108 	case VERIFY_16: {
9109 		struct scsi_rw_16 *cdb;
9110 
9111 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9112 		if (cdb->byte2 & SVFY_BYTCHK)
9113 			bytchk = 1;
9114 		if (cdb->byte2 & SVFY_DPO)
9115 			flags |= CTL_LLF_DPO;
9116 		lba = scsi_8btou64(cdb->addr);
9117 		num_blocks = scsi_4btoul(cdb->length);
9118 		break;
9119 	}
9120 	default:
9121 		/*
9122 		 * We got a command we don't support.  This shouldn't
9123 		 * happen, commands should be filtered out above us.
9124 		 */
9125 		ctl_set_invalid_opcode(ctsio);
9126 		ctl_done((union ctl_io *)ctsio);
9127 		return (CTL_RETVAL_COMPLETE);
9128 	}
9129 
9130 	/*
9131 	 * The first check is to make sure we're in bounds, the second
9132 	 * check is to catch wrap-around problems.  If the lba + num blocks
9133 	 * is less than the lba, then we've wrapped around and the block
9134 	 * range is invalid anyway.
9135 	 */
9136 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9137 	 || ((lba + num_blocks) < lba)) {
9138 		ctl_set_lba_out_of_range(ctsio,
9139 		    MAX(lba, lun->be_lun->maxlba + 1));
9140 		ctl_done((union ctl_io *)ctsio);
9141 		return (CTL_RETVAL_COMPLETE);
9142 	}
9143 
9144 	/*
9145 	 * According to SBC-3, a transfer length of 0 is not an error.
9146 	 */
9147 	if (num_blocks == 0) {
9148 		ctl_set_success(ctsio);
9149 		ctl_done((union ctl_io *)ctsio);
9150 		return (CTL_RETVAL_COMPLETE);
9151 	}
9152 
9153 	lbalen = (struct ctl_lba_len_flags *)
9154 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9155 	lbalen->lba = lba;
9156 	lbalen->len = num_blocks;
9157 	if (bytchk) {
9158 		lbalen->flags = CTL_LLF_COMPARE | flags;
9159 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9160 	} else {
9161 		lbalen->flags = CTL_LLF_VERIFY | flags;
9162 		ctsio->kern_total_len = 0;
9163 	}
9164 	ctsio->kern_rel_offset = 0;
9165 
9166 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9167 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9168 	return (retval);
9169 }
9170 
9171 int
9172 ctl_report_luns(struct ctl_scsiio *ctsio)
9173 {
9174 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9175 	struct ctl_port *port = CTL_PORT(ctsio);
9176 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9177 	struct scsi_report_luns *cdb;
9178 	struct scsi_report_luns_data *lun_data;
9179 	int num_filled, num_luns, num_port_luns, retval;
9180 	uint32_t alloc_len, lun_datalen;
9181 	uint32_t initidx, targ_lun_id, lun_id;
9182 
9183 	retval = CTL_RETVAL_COMPLETE;
9184 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9185 
9186 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9187 
9188 	num_luns = 0;
9189 	num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
9190 	mtx_lock(&softc->ctl_lock);
9191 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9192 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9193 			num_luns++;
9194 	}
9195 	mtx_unlock(&softc->ctl_lock);
9196 
9197 	switch (cdb->select_report) {
9198 	case RPL_REPORT_DEFAULT:
9199 	case RPL_REPORT_ALL:
9200 	case RPL_REPORT_NONSUBSID:
9201 		break;
9202 	case RPL_REPORT_WELLKNOWN:
9203 	case RPL_REPORT_ADMIN:
9204 	case RPL_REPORT_CONGLOM:
9205 		num_luns = 0;
9206 		break;
9207 	default:
9208 		ctl_set_invalid_field(ctsio,
9209 				      /*sks_valid*/ 1,
9210 				      /*command*/ 1,
9211 				      /*field*/ 2,
9212 				      /*bit_valid*/ 0,
9213 				      /*bit*/ 0);
9214 		ctl_done((union ctl_io *)ctsio);
9215 		return (retval);
9216 		break; /* NOTREACHED */
9217 	}
9218 
9219 	alloc_len = scsi_4btoul(cdb->length);
9220 	/*
9221 	 * The initiator has to allocate at least 16 bytes for this request,
9222 	 * so he can at least get the header and the first LUN.  Otherwise
9223 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9224 	 */
9225 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9226 	    sizeof(struct scsi_report_luns_lundata))) {
9227 		ctl_set_invalid_field(ctsio,
9228 				      /*sks_valid*/ 1,
9229 				      /*command*/ 1,
9230 				      /*field*/ 6,
9231 				      /*bit_valid*/ 0,
9232 				      /*bit*/ 0);
9233 		ctl_done((union ctl_io *)ctsio);
9234 		return (retval);
9235 	}
9236 
9237 	lun_datalen = sizeof(*lun_data) +
9238 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9239 
9240 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9241 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9242 	ctsio->kern_sg_entries = 0;
9243 
9244 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9245 
9246 	mtx_lock(&softc->ctl_lock);
9247 	for (targ_lun_id = 0, num_filled = 0;
9248 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9249 	    targ_lun_id++) {
9250 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9251 		if (lun_id == UINT32_MAX)
9252 			continue;
9253 		lun = softc->ctl_luns[lun_id];
9254 		if (lun == NULL)
9255 			continue;
9256 
9257 		be64enc(lun_data->luns[num_filled++].lundata,
9258 		    ctl_encode_lun(targ_lun_id));
9259 
9260 		/*
9261 		 * According to SPC-3, rev 14 section 6.21:
9262 		 *
9263 		 * "The execution of a REPORT LUNS command to any valid and
9264 		 * installed logical unit shall clear the REPORTED LUNS DATA
9265 		 * HAS CHANGED unit attention condition for all logical
9266 		 * units of that target with respect to the requesting
9267 		 * initiator. A valid and installed logical unit is one
9268 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9269 		 * INQUIRY data (see 6.4.2)."
9270 		 *
9271 		 * If request_lun is NULL, the LUN this report luns command
9272 		 * was issued to is either disabled or doesn't exist. In that
9273 		 * case, we shouldn't clear any pending lun change unit
9274 		 * attention.
9275 		 */
9276 		if (request_lun != NULL) {
9277 			mtx_lock(&lun->lun_lock);
9278 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9279 			mtx_unlock(&lun->lun_lock);
9280 		}
9281 	}
9282 	mtx_unlock(&softc->ctl_lock);
9283 
9284 	/*
9285 	 * It's quite possible that we've returned fewer LUNs than we allocated
9286 	 * space for.  Trim it.
9287 	 */
9288 	lun_datalen = sizeof(*lun_data) +
9289 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9290 	ctsio->kern_rel_offset = 0;
9291 	ctsio->kern_sg_entries = 0;
9292 	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9293 	ctsio->kern_total_len = ctsio->kern_data_len;
9294 
9295 	/*
9296 	 * We set this to the actual data length, regardless of how much
9297 	 * space we actually have to return results.  If the user looks at
9298 	 * this value, he'll know whether or not he allocated enough space
9299 	 * and reissue the command if necessary.  We don't support well
9300 	 * known logical units, so if the user asks for that, return none.
9301 	 */
9302 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9303 
9304 	/*
9305 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9306 	 * this request.
9307 	 */
9308 	ctl_set_success(ctsio);
9309 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9310 	ctsio->be_move_done = ctl_config_move_done;
9311 	ctl_datamove((union ctl_io *)ctsio);
9312 	return (retval);
9313 }
9314 
9315 int
9316 ctl_request_sense(struct ctl_scsiio *ctsio)
9317 {
9318 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9319 	struct ctl_lun *lun = CTL_LUN(ctsio);
9320 	struct scsi_request_sense *cdb;
9321 	struct scsi_sense_data *sense_ptr, *ps;
9322 	uint32_t initidx;
9323 	int have_error;
9324 	u_int sense_len = SSD_FULL_SIZE;
9325 	scsi_sense_data_type sense_format;
9326 	ctl_ua_type ua_type;
9327 	uint8_t asc = 0, ascq = 0;
9328 
9329 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9330 
9331 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9332 
9333 	/*
9334 	 * Determine which sense format the user wants.
9335 	 */
9336 	if (cdb->byte2 & SRS_DESC)
9337 		sense_format = SSD_TYPE_DESC;
9338 	else
9339 		sense_format = SSD_TYPE_FIXED;
9340 
9341 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9342 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9343 	ctsio->kern_sg_entries = 0;
9344 	ctsio->kern_rel_offset = 0;
9345 
9346 	/*
9347 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9348 	 * larger than the largest allowed value for the length field in the
9349 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9350 	 */
9351 	ctsio->kern_data_len = cdb->length;
9352 	ctsio->kern_total_len = cdb->length;
9353 
9354 	/*
9355 	 * If we don't have a LUN, we don't have any pending sense.
9356 	 */
9357 	if (lun == NULL ||
9358 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9359 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9360 		/* "Logical unit not supported" */
9361 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9362 		    /*current_error*/ 1,
9363 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9364 		    /*asc*/ 0x25,
9365 		    /*ascq*/ 0x00,
9366 		    SSD_ELEM_NONE);
9367 		goto send;
9368 	}
9369 
9370 	have_error = 0;
9371 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9372 	/*
9373 	 * Check for pending sense, and then for pending unit attentions.
9374 	 * Pending sense gets returned first, then pending unit attentions.
9375 	 */
9376 	mtx_lock(&lun->lun_lock);
9377 	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9378 	if (ps != NULL)
9379 		ps += initidx % CTL_MAX_INIT_PER_PORT;
9380 	if (ps != NULL && ps->error_code != 0) {
9381 		scsi_sense_data_type stored_format;
9382 
9383 		/*
9384 		 * Check to see which sense format was used for the stored
9385 		 * sense data.
9386 		 */
9387 		stored_format = scsi_sense_type(ps);
9388 
9389 		/*
9390 		 * If the user requested a different sense format than the
9391 		 * one we stored, then we need to convert it to the other
9392 		 * format.  If we're going from descriptor to fixed format
9393 		 * sense data, we may lose things in translation, depending
9394 		 * on what options were used.
9395 		 *
9396 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9397 		 * for some reason we'll just copy it out as-is.
9398 		 */
9399 		if ((stored_format == SSD_TYPE_FIXED)
9400 		 && (sense_format == SSD_TYPE_DESC))
9401 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9402 			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9403 		else if ((stored_format == SSD_TYPE_DESC)
9404 		      && (sense_format == SSD_TYPE_FIXED))
9405 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9406 			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9407 		else
9408 			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9409 
9410 		ps->error_code = 0;
9411 		have_error = 1;
9412 	} else {
9413 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9414 		    sense_format);
9415 		if (ua_type != CTL_UA_NONE)
9416 			have_error = 1;
9417 	}
9418 	if (have_error == 0) {
9419 		/*
9420 		 * Report informational exception if have one and allowed.
9421 		 */
9422 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9423 			asc = lun->ie_asc;
9424 			ascq = lun->ie_ascq;
9425 		}
9426 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9427 		    /*current_error*/ 1,
9428 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9429 		    /*asc*/ asc,
9430 		    /*ascq*/ ascq,
9431 		    SSD_ELEM_NONE);
9432 	}
9433 	mtx_unlock(&lun->lun_lock);
9434 
9435 send:
9436 	/*
9437 	 * We report the SCSI status as OK, since the status of the command
9438 	 * itself is OK.  We're reporting sense as parameter data.
9439 	 */
9440 	ctl_set_success(ctsio);
9441 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9442 	ctsio->be_move_done = ctl_config_move_done;
9443 	ctl_datamove((union ctl_io *)ctsio);
9444 	return (CTL_RETVAL_COMPLETE);
9445 }
9446 
9447 int
9448 ctl_tur(struct ctl_scsiio *ctsio)
9449 {
9450 
9451 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9452 
9453 	ctl_set_success(ctsio);
9454 	ctl_done((union ctl_io *)ctsio);
9455 
9456 	return (CTL_RETVAL_COMPLETE);
9457 }
9458 
9459 /*
9460  * SCSI VPD page 0x00, the Supported VPD Pages page.
9461  */
9462 static int
9463 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9464 {
9465 	struct ctl_lun *lun = CTL_LUN(ctsio);
9466 	struct scsi_vpd_supported_pages *pages;
9467 	int sup_page_size;
9468 	int p;
9469 
9470 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9471 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9472 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9473 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9474 	ctsio->kern_rel_offset = 0;
9475 	ctsio->kern_sg_entries = 0;
9476 	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9477 	ctsio->kern_total_len = ctsio->kern_data_len;
9478 
9479 	/*
9480 	 * The control device is always connected.  The disk device, on the
9481 	 * other hand, may not be online all the time.  Need to change this
9482 	 * to figure out whether the disk device is actually online or not.
9483 	 */
9484 	if (lun != NULL)
9485 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9486 				lun->be_lun->lun_type;
9487 	else
9488 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9489 
9490 	p = 0;
9491 	/* Supported VPD pages */
9492 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9493 	/* Serial Number */
9494 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9495 	/* Device Identification */
9496 	pages->page_list[p++] = SVPD_DEVICE_ID;
9497 	/* Extended INQUIRY Data */
9498 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9499 	/* Mode Page Policy */
9500 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9501 	/* SCSI Ports */
9502 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9503 	/* Third-party Copy */
9504 	pages->page_list[p++] = SVPD_SCSI_TPC;
9505 	/* SCSI Feature Sets */
9506 	pages->page_list[p++] = SVPD_SCSI_SFS;
9507 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9508 		/* Block limits */
9509 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9510 		/* Block Device Characteristics */
9511 		pages->page_list[p++] = SVPD_BDC;
9512 		/* Logical Block Provisioning */
9513 		pages->page_list[p++] = SVPD_LBP;
9514 	}
9515 	pages->length = p;
9516 
9517 	ctl_set_success(ctsio);
9518 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9519 	ctsio->be_move_done = ctl_config_move_done;
9520 	ctl_datamove((union ctl_io *)ctsio);
9521 	return (CTL_RETVAL_COMPLETE);
9522 }
9523 
9524 /*
9525  * SCSI VPD page 0x80, the Unit Serial Number page.
9526  */
9527 static int
9528 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9529 {
9530 	struct ctl_lun *lun = CTL_LUN(ctsio);
9531 	struct scsi_vpd_unit_serial_number *sn_ptr;
9532 	int data_len;
9533 
9534 	data_len = 4 + CTL_SN_LEN;
9535 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9536 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9537 	ctsio->kern_rel_offset = 0;
9538 	ctsio->kern_sg_entries = 0;
9539 	ctsio->kern_data_len = min(data_len, alloc_len);
9540 	ctsio->kern_total_len = ctsio->kern_data_len;
9541 
9542 	/*
9543 	 * The control device is always connected.  The disk device, on the
9544 	 * other hand, may not be online all the time.  Need to change this
9545 	 * to figure out whether the disk device is actually online or not.
9546 	 */
9547 	if (lun != NULL)
9548 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9549 				  lun->be_lun->lun_type;
9550 	else
9551 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9552 
9553 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9554 	sn_ptr->length = CTL_SN_LEN;
9555 	/*
9556 	 * If we don't have a LUN, we just leave the serial number as
9557 	 * all spaces.
9558 	 */
9559 	if (lun != NULL) {
9560 		strncpy((char *)sn_ptr->serial_num,
9561 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9562 	} else
9563 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9564 
9565 	ctl_set_success(ctsio);
9566 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9567 	ctsio->be_move_done = ctl_config_move_done;
9568 	ctl_datamove((union ctl_io *)ctsio);
9569 	return (CTL_RETVAL_COMPLETE);
9570 }
9571 
9572 /*
9573  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9574  */
9575 static int
9576 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9577 {
9578 	struct ctl_lun *lun = CTL_LUN(ctsio);
9579 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9580 	int data_len;
9581 
9582 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9583 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9584 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9585 	ctsio->kern_sg_entries = 0;
9586 	ctsio->kern_rel_offset = 0;
9587 	ctsio->kern_data_len = min(data_len, alloc_len);
9588 	ctsio->kern_total_len = ctsio->kern_data_len;
9589 
9590 	/*
9591 	 * The control device is always connected.  The disk device, on the
9592 	 * other hand, may not be online all the time.
9593 	 */
9594 	if (lun != NULL)
9595 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9596 				     lun->be_lun->lun_type;
9597 	else
9598 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9599 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9600 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9601 	/*
9602 	 * We support head of queue, ordered and simple tags.
9603 	 */
9604 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9605 	/*
9606 	 * Volatile cache supported.
9607 	 */
9608 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9609 
9610 	/*
9611 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9612 	 * attention for a particular IT nexus on all LUNs once we report
9613 	 * it to that nexus once.  This bit is required as of SPC-4.
9614 	 */
9615 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9616 
9617 	/*
9618 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9619 	 */
9620 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9621 
9622 	/*
9623 	 * XXX KDM in order to correctly answer this, we would need
9624 	 * information from the SIM to determine how much sense data it
9625 	 * can send.  So this would really be a path inquiry field, most
9626 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9627 	 * but the hardware may or may not be able to support that much.
9628 	 * 0 just means that the maximum sense data length is not reported.
9629 	 */
9630 	eid_ptr->max_sense_length = 0;
9631 
9632 	ctl_set_success(ctsio);
9633 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9634 	ctsio->be_move_done = ctl_config_move_done;
9635 	ctl_datamove((union ctl_io *)ctsio);
9636 	return (CTL_RETVAL_COMPLETE);
9637 }
9638 
9639 static int
9640 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9641 {
9642 	struct ctl_lun *lun = CTL_LUN(ctsio);
9643 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9644 	int data_len;
9645 
9646 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9647 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9648 
9649 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9650 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9651 	ctsio->kern_rel_offset = 0;
9652 	ctsio->kern_sg_entries = 0;
9653 	ctsio->kern_data_len = min(data_len, alloc_len);
9654 	ctsio->kern_total_len = ctsio->kern_data_len;
9655 
9656 	/*
9657 	 * The control device is always connected.  The disk device, on the
9658 	 * other hand, may not be online all the time.
9659 	 */
9660 	if (lun != NULL)
9661 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9662 				     lun->be_lun->lun_type;
9663 	else
9664 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9665 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9666 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9667 	mpp_ptr->descr[0].page_code = 0x3f;
9668 	mpp_ptr->descr[0].subpage_code = 0xff;
9669 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9670 
9671 	ctl_set_success(ctsio);
9672 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9673 	ctsio->be_move_done = ctl_config_move_done;
9674 	ctl_datamove((union ctl_io *)ctsio);
9675 	return (CTL_RETVAL_COMPLETE);
9676 }
9677 
9678 /*
9679  * SCSI VPD page 0x83, the Device Identification page.
9680  */
9681 static int
9682 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9683 {
9684 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9685 	struct ctl_port *port = CTL_PORT(ctsio);
9686 	struct ctl_lun *lun = CTL_LUN(ctsio);
9687 	struct scsi_vpd_device_id *devid_ptr;
9688 	struct scsi_vpd_id_descriptor *desc;
9689 	int data_len, g;
9690 	uint8_t proto;
9691 
9692 	data_len = sizeof(struct scsi_vpd_device_id) +
9693 	    sizeof(struct scsi_vpd_id_descriptor) +
9694 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9695 	    sizeof(struct scsi_vpd_id_descriptor) +
9696 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9697 	if (lun && lun->lun_devid)
9698 		data_len += lun->lun_devid->len;
9699 	if (port && port->port_devid)
9700 		data_len += port->port_devid->len;
9701 	if (port && port->target_devid)
9702 		data_len += port->target_devid->len;
9703 
9704 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9705 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9706 	ctsio->kern_sg_entries = 0;
9707 	ctsio->kern_rel_offset = 0;
9708 	ctsio->kern_sg_entries = 0;
9709 	ctsio->kern_data_len = min(data_len, alloc_len);
9710 	ctsio->kern_total_len = ctsio->kern_data_len;
9711 
9712 	/*
9713 	 * The control device is always connected.  The disk device, on the
9714 	 * other hand, may not be online all the time.
9715 	 */
9716 	if (lun != NULL)
9717 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9718 				     lun->be_lun->lun_type;
9719 	else
9720 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9721 	devid_ptr->page_code = SVPD_DEVICE_ID;
9722 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9723 
9724 	if (port && port->port_type == CTL_PORT_FC)
9725 		proto = SCSI_PROTO_FC << 4;
9726 	else if (port && port->port_type == CTL_PORT_SAS)
9727 		proto = SCSI_PROTO_SAS << 4;
9728 	else if (port && port->port_type == CTL_PORT_ISCSI)
9729 		proto = SCSI_PROTO_ISCSI << 4;
9730 	else
9731 		proto = SCSI_PROTO_SPI << 4;
9732 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9733 
9734 	/*
9735 	 * We're using a LUN association here.  i.e., this device ID is a
9736 	 * per-LUN identifier.
9737 	 */
9738 	if (lun && lun->lun_devid) {
9739 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9740 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9741 		    lun->lun_devid->len);
9742 	}
9743 
9744 	/*
9745 	 * This is for the WWPN which is a port association.
9746 	 */
9747 	if (port && port->port_devid) {
9748 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9749 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9750 		    port->port_devid->len);
9751 	}
9752 
9753 	/*
9754 	 * This is for the Relative Target Port(type 4h) identifier
9755 	 */
9756 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9757 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9758 	    SVPD_ID_TYPE_RELTARG;
9759 	desc->length = 4;
9760 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9761 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9762 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9763 
9764 	/*
9765 	 * This is for the Target Port Group(type 5h) identifier
9766 	 */
9767 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9768 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9769 	    SVPD_ID_TYPE_TPORTGRP;
9770 	desc->length = 4;
9771 	if (softc->is_single ||
9772 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9773 		g = 1;
9774 	else
9775 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9776 	scsi_ulto2b(g, &desc->identifier[2]);
9777 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9778 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9779 
9780 	/*
9781 	 * This is for the Target identifier
9782 	 */
9783 	if (port && port->target_devid) {
9784 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9785 	}
9786 
9787 	ctl_set_success(ctsio);
9788 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9789 	ctsio->be_move_done = ctl_config_move_done;
9790 	ctl_datamove((union ctl_io *)ctsio);
9791 	return (CTL_RETVAL_COMPLETE);
9792 }
9793 
9794 static int
9795 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9796 {
9797 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9798 	struct ctl_lun *lun = CTL_LUN(ctsio);
9799 	struct scsi_vpd_scsi_ports *sp;
9800 	struct scsi_vpd_port_designation *pd;
9801 	struct scsi_vpd_port_designation_cont *pdc;
9802 	struct ctl_port *port;
9803 	int data_len, num_target_ports, iid_len, id_len;
9804 
9805 	num_target_ports = 0;
9806 	iid_len = 0;
9807 	id_len = 0;
9808 	mtx_lock(&softc->ctl_lock);
9809 	STAILQ_FOREACH(port, &softc->port_list, links) {
9810 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9811 			continue;
9812 		if (lun != NULL &&
9813 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9814 			continue;
9815 		num_target_ports++;
9816 		if (port->init_devid)
9817 			iid_len += port->init_devid->len;
9818 		if (port->port_devid)
9819 			id_len += port->port_devid->len;
9820 	}
9821 	mtx_unlock(&softc->ctl_lock);
9822 
9823 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9824 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9825 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9826 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9827 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9828 	ctsio->kern_sg_entries = 0;
9829 	ctsio->kern_rel_offset = 0;
9830 	ctsio->kern_sg_entries = 0;
9831 	ctsio->kern_data_len = min(data_len, alloc_len);
9832 	ctsio->kern_total_len = ctsio->kern_data_len;
9833 
9834 	/*
9835 	 * The control device is always connected.  The disk device, on the
9836 	 * other hand, may not be online all the time.  Need to change this
9837 	 * to figure out whether the disk device is actually online or not.
9838 	 */
9839 	if (lun != NULL)
9840 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9841 				  lun->be_lun->lun_type;
9842 	else
9843 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9844 
9845 	sp->page_code = SVPD_SCSI_PORTS;
9846 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9847 	    sp->page_length);
9848 	pd = &sp->design[0];
9849 
9850 	mtx_lock(&softc->ctl_lock);
9851 	STAILQ_FOREACH(port, &softc->port_list, links) {
9852 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9853 			continue;
9854 		if (lun != NULL &&
9855 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9856 			continue;
9857 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9858 		if (port->init_devid) {
9859 			iid_len = port->init_devid->len;
9860 			memcpy(pd->initiator_transportid,
9861 			    port->init_devid->data, port->init_devid->len);
9862 		} else
9863 			iid_len = 0;
9864 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9865 		pdc = (struct scsi_vpd_port_designation_cont *)
9866 		    (&pd->initiator_transportid[iid_len]);
9867 		if (port->port_devid) {
9868 			id_len = port->port_devid->len;
9869 			memcpy(pdc->target_port_descriptors,
9870 			    port->port_devid->data, port->port_devid->len);
9871 		} else
9872 			id_len = 0;
9873 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9874 		pd = (struct scsi_vpd_port_designation *)
9875 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9876 	}
9877 	mtx_unlock(&softc->ctl_lock);
9878 
9879 	ctl_set_success(ctsio);
9880 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9881 	ctsio->be_move_done = ctl_config_move_done;
9882 	ctl_datamove((union ctl_io *)ctsio);
9883 	return (CTL_RETVAL_COMPLETE);
9884 }
9885 
9886 static int
9887 ctl_inquiry_evpd_sfs(struct ctl_scsiio *ctsio, int alloc_len)
9888 {
9889 	struct ctl_lun *lun = CTL_LUN(ctsio);
9890 	struct scsi_vpd_sfs *sfs_ptr;
9891 	int sfs_page_size, n;
9892 
9893 	sfs_page_size = sizeof(*sfs_ptr) + 5 * 2;
9894 	ctsio->kern_data_ptr = malloc(sfs_page_size, M_CTL, M_WAITOK | M_ZERO);
9895 	sfs_ptr = (struct scsi_vpd_sfs *)ctsio->kern_data_ptr;
9896 	ctsio->kern_sg_entries = 0;
9897 	ctsio->kern_rel_offset = 0;
9898 	ctsio->kern_sg_entries = 0;
9899 	ctsio->kern_data_len = min(sfs_page_size, alloc_len);
9900 	ctsio->kern_total_len = ctsio->kern_data_len;
9901 
9902 	/*
9903 	 * The control device is always connected.  The disk device, on the
9904 	 * other hand, may not be online all the time.  Need to change this
9905 	 * to figure out whether the disk device is actually online or not.
9906 	 */
9907 	if (lun != NULL)
9908 		sfs_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9909 				  lun->be_lun->lun_type;
9910 	else
9911 		sfs_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9912 
9913 	sfs_ptr->page_code = SVPD_SCSI_SFS;
9914 	n = 0;
9915 	/* Discovery 2016 */
9916 	scsi_ulto2b(0x0001, &sfs_ptr->codes[2 * n++]);
9917 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9918 		 /* SBC Base 2016 */
9919 		scsi_ulto2b(0x0101, &sfs_ptr->codes[2 * n++]);
9920 		 /* SBC Base 2010 */
9921 		scsi_ulto2b(0x0102, &sfs_ptr->codes[2 * n++]);
9922 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9923 			/* Basic Provisioning 2016 */
9924 			scsi_ulto2b(0x0103, &sfs_ptr->codes[2 * n++]);
9925 		}
9926 		/* Drive Maintenance 2016 */
9927 		//scsi_ulto2b(0x0104, &sfs_ptr->codes[2 * n++]);
9928 	}
9929 	scsi_ulto2b(4 + 2 * n, sfs_ptr->page_length);
9930 
9931 	ctl_set_success(ctsio);
9932 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9933 	ctsio->be_move_done = ctl_config_move_done;
9934 	ctl_datamove((union ctl_io *)ctsio);
9935 	return (CTL_RETVAL_COMPLETE);
9936 }
9937 
9938 static int
9939 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9940 {
9941 	struct ctl_lun *lun = CTL_LUN(ctsio);
9942 	struct scsi_vpd_block_limits *bl_ptr;
9943 	const char *val;
9944 	uint64_t ival;
9945 
9946 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9947 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9948 	ctsio->kern_sg_entries = 0;
9949 	ctsio->kern_rel_offset = 0;
9950 	ctsio->kern_sg_entries = 0;
9951 	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9952 	ctsio->kern_total_len = ctsio->kern_data_len;
9953 
9954 	/*
9955 	 * The control device is always connected.  The disk device, on the
9956 	 * other hand, may not be online all the time.  Need to change this
9957 	 * to figure out whether the disk device is actually online or not.
9958 	 */
9959 	if (lun != NULL)
9960 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9961 				  lun->be_lun->lun_type;
9962 	else
9963 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9964 
9965 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9966 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9967 	bl_ptr->max_cmp_write_len = 0xff;
9968 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9969 	if (lun != NULL) {
9970 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9971 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9972 			ival = 0xffffffff;
9973 			val = dnvlist_get_string(lun->be_lun->options,
9974 			    "unmap_max_lba", NULL);
9975 			if (val != NULL)
9976 				ctl_expand_number(val, &ival);
9977 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9978 			ival = 0xffffffff;
9979 			val = dnvlist_get_string(lun->be_lun->options,
9980 			    "unmap_max_descr", NULL);
9981 			if (val != NULL)
9982 				ctl_expand_number(val, &ival);
9983 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9984 			if (lun->be_lun->ublockexp != 0) {
9985 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9986 				    bl_ptr->opt_unmap_grain);
9987 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9988 				    bl_ptr->unmap_grain_align);
9989 			}
9990 		}
9991 		scsi_ulto4b(lun->be_lun->atomicblock,
9992 		    bl_ptr->max_atomic_transfer_length);
9993 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9994 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9995 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9996 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9997 		ival = UINT64_MAX;
9998 		val = dnvlist_get_string(lun->be_lun->options,
9999 		    "write_same_max_lba", NULL);
10000 		if (val != NULL)
10001 			ctl_expand_number(val, &ival);
10002 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
10003 		if (lun->be_lun->maxlba + 1 > ival)
10004 			bl_ptr->flags |= SVPD_BL_WSNZ;
10005 	}
10006 
10007 	ctl_set_success(ctsio);
10008 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10009 	ctsio->be_move_done = ctl_config_move_done;
10010 	ctl_datamove((union ctl_io *)ctsio);
10011 	return (CTL_RETVAL_COMPLETE);
10012 }
10013 
10014 static int
10015 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10016 {
10017 	struct ctl_lun *lun = CTL_LUN(ctsio);
10018 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10019 	const char *value;
10020 	u_int i;
10021 
10022 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10023 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10024 	ctsio->kern_sg_entries = 0;
10025 	ctsio->kern_rel_offset = 0;
10026 	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
10027 	ctsio->kern_total_len = ctsio->kern_data_len;
10028 
10029 	/*
10030 	 * The control device is always connected.  The disk device, on the
10031 	 * other hand, may not be online all the time.  Need to change this
10032 	 * to figure out whether the disk device is actually online or not.
10033 	 */
10034 	if (lun != NULL)
10035 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10036 				  lun->be_lun->lun_type;
10037 	else
10038 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10039 	bdc_ptr->page_code = SVPD_BDC;
10040 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10041 	if (lun != NULL &&
10042 	    (value = dnvlist_get_string(lun->be_lun->options, "rpm", NULL)) != NULL)
10043 		i = strtol(value, NULL, 0);
10044 	else
10045 		i = CTL_DEFAULT_ROTATION_RATE;
10046 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
10047 	if (lun != NULL &&
10048 	    (value = dnvlist_get_string(lun->be_lun->options, "formfactor", NULL)) != NULL)
10049 		i = strtol(value, NULL, 0);
10050 	else
10051 		i = 0;
10052 	bdc_ptr->wab_wac_ff = (i & 0x0f);
10053 	bdc_ptr->flags = SVPD_RBWZ | SVPD_FUAB | SVPD_VBULS;
10054 
10055 	ctl_set_success(ctsio);
10056 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10057 	ctsio->be_move_done = ctl_config_move_done;
10058 	ctl_datamove((union ctl_io *)ctsio);
10059 	return (CTL_RETVAL_COMPLETE);
10060 }
10061 
10062 static int
10063 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10064 {
10065 	struct ctl_lun *lun = CTL_LUN(ctsio);
10066 	struct scsi_vpd_logical_block_prov *lbp_ptr;
10067 	const char *value;
10068 
10069 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10070 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10071 	ctsio->kern_sg_entries = 0;
10072 	ctsio->kern_rel_offset = 0;
10073 	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
10074 	ctsio->kern_total_len = ctsio->kern_data_len;
10075 
10076 	/*
10077 	 * The control device is always connected.  The disk device, on the
10078 	 * other hand, may not be online all the time.  Need to change this
10079 	 * to figure out whether the disk device is actually online or not.
10080 	 */
10081 	if (lun != NULL)
10082 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10083 				  lun->be_lun->lun_type;
10084 	else
10085 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10086 
10087 	lbp_ptr->page_code = SVPD_LBP;
10088 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10089 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10090 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10091 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10092 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10093 		value = dnvlist_get_string(lun->be_lun->options,
10094 		    "provisioning_type", NULL);
10095 		if (value != NULL) {
10096 			if (strcmp(value, "resource") == 0)
10097 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10098 			else if (strcmp(value, "thin") == 0)
10099 				lbp_ptr->prov_type = SVPD_LBP_THIN;
10100 		} else
10101 			lbp_ptr->prov_type = SVPD_LBP_THIN;
10102 	}
10103 
10104 	ctl_set_success(ctsio);
10105 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10106 	ctsio->be_move_done = ctl_config_move_done;
10107 	ctl_datamove((union ctl_io *)ctsio);
10108 	return (CTL_RETVAL_COMPLETE);
10109 }
10110 
10111 /*
10112  * INQUIRY with the EVPD bit set.
10113  */
10114 static int
10115 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10116 {
10117 	struct ctl_lun *lun = CTL_LUN(ctsio);
10118 	struct scsi_inquiry *cdb;
10119 	int alloc_len, retval;
10120 
10121 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10122 	alloc_len = scsi_2btoul(cdb->length);
10123 
10124 	switch (cdb->page_code) {
10125 	case SVPD_SUPPORTED_PAGES:
10126 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10127 		break;
10128 	case SVPD_UNIT_SERIAL_NUMBER:
10129 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10130 		break;
10131 	case SVPD_DEVICE_ID:
10132 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10133 		break;
10134 	case SVPD_EXTENDED_INQUIRY_DATA:
10135 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10136 		break;
10137 	case SVPD_MODE_PAGE_POLICY:
10138 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10139 		break;
10140 	case SVPD_SCSI_PORTS:
10141 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10142 		break;
10143 	case SVPD_SCSI_TPC:
10144 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10145 		break;
10146 	case SVPD_SCSI_SFS:
10147 		retval = ctl_inquiry_evpd_sfs(ctsio, alloc_len);
10148 		break;
10149 	case SVPD_BLOCK_LIMITS:
10150 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10151 			goto err;
10152 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10153 		break;
10154 	case SVPD_BDC:
10155 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10156 			goto err;
10157 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10158 		break;
10159 	case SVPD_LBP:
10160 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10161 			goto err;
10162 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10163 		break;
10164 	default:
10165 err:
10166 		ctl_set_invalid_field(ctsio,
10167 				      /*sks_valid*/ 1,
10168 				      /*command*/ 1,
10169 				      /*field*/ 2,
10170 				      /*bit_valid*/ 0,
10171 				      /*bit*/ 0);
10172 		ctl_done((union ctl_io *)ctsio);
10173 		retval = CTL_RETVAL_COMPLETE;
10174 		break;
10175 	}
10176 
10177 	return (retval);
10178 }
10179 
10180 /*
10181  * Standard INQUIRY data.
10182  */
10183 static int
10184 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10185 {
10186 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
10187 	struct ctl_port *port = CTL_PORT(ctsio);
10188 	struct ctl_lun *lun = CTL_LUN(ctsio);
10189 	struct scsi_inquiry_data *inq_ptr;
10190 	struct scsi_inquiry *cdb;
10191 	const char *val;
10192 	uint32_t alloc_len, data_len;
10193 	ctl_port_type port_type;
10194 
10195 	port_type = port->port_type;
10196 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10197 		port_type = CTL_PORT_SCSI;
10198 
10199 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10200 	alloc_len = scsi_2btoul(cdb->length);
10201 
10202 	/*
10203 	 * We malloc the full inquiry data size here and fill it
10204 	 * in.  If the user only asks for less, we'll give him
10205 	 * that much.
10206 	 */
10207 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10208 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10209 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10210 	ctsio->kern_sg_entries = 0;
10211 	ctsio->kern_rel_offset = 0;
10212 	ctsio->kern_data_len = min(data_len, alloc_len);
10213 	ctsio->kern_total_len = ctsio->kern_data_len;
10214 
10215 	if (lun != NULL) {
10216 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10217 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10218 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10219 			    lun->be_lun->lun_type;
10220 		} else {
10221 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10222 			    lun->be_lun->lun_type;
10223 		}
10224 		if (lun->flags & CTL_LUN_REMOVABLE)
10225 			inq_ptr->dev_qual2 |= SID_RMB;
10226 	} else
10227 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10228 
10229 	/* RMB in byte 2 is 0 */
10230 	inq_ptr->version = SCSI_REV_SPC5;
10231 
10232 	/*
10233 	 * According to SAM-3, even if a device only supports a single
10234 	 * level of LUN addressing, it should still set the HISUP bit:
10235 	 *
10236 	 * 4.9.1 Logical unit numbers overview
10237 	 *
10238 	 * All logical unit number formats described in this standard are
10239 	 * hierarchical in structure even when only a single level in that
10240 	 * hierarchy is used. The HISUP bit shall be set to one in the
10241 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10242 	 * format described in this standard is used.  Non-hierarchical
10243 	 * formats are outside the scope of this standard.
10244 	 *
10245 	 * Therefore we set the HiSup bit here.
10246 	 *
10247 	 * The response format is 2, per SPC-3.
10248 	 */
10249 	inq_ptr->response_format = SID_HiSup | 2;
10250 
10251 	inq_ptr->additional_length = data_len -
10252 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10253 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10254 			 inq_ptr->additional_length));
10255 
10256 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10257 	if (port_type == CTL_PORT_SCSI)
10258 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10259 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10260 	inq_ptr->flags = SID_CmdQue;
10261 	if (port_type == CTL_PORT_SCSI)
10262 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10263 
10264 	/*
10265 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10266 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10267 	 * name and 4 bytes for the revision.
10268 	 */
10269 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10270 	    "vendor", NULL)) == NULL) {
10271 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10272 	} else {
10273 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10274 		strncpy(inq_ptr->vendor, val,
10275 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10276 	}
10277 	if (lun == NULL) {
10278 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10279 		    sizeof(inq_ptr->product));
10280 	} else if ((val = dnvlist_get_string(lun->be_lun->options, "product",
10281 	    NULL)) == NULL) {
10282 		switch (lun->be_lun->lun_type) {
10283 		case T_DIRECT:
10284 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10285 			    sizeof(inq_ptr->product));
10286 			break;
10287 		case T_PROCESSOR:
10288 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10289 			    sizeof(inq_ptr->product));
10290 			break;
10291 		case T_CDROM:
10292 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10293 			    sizeof(inq_ptr->product));
10294 			break;
10295 		default:
10296 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10297 			    sizeof(inq_ptr->product));
10298 			break;
10299 		}
10300 	} else {
10301 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10302 		strncpy(inq_ptr->product, val,
10303 		    min(sizeof(inq_ptr->product), strlen(val)));
10304 	}
10305 
10306 	/*
10307 	 * XXX make this a macro somewhere so it automatically gets
10308 	 * incremented when we make changes.
10309 	 */
10310 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10311 	    "revision", NULL)) == NULL) {
10312 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10313 	} else {
10314 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10315 		strncpy(inq_ptr->revision, val,
10316 		    min(sizeof(inq_ptr->revision), strlen(val)));
10317 	}
10318 
10319 	/*
10320 	 * For parallel SCSI, we support double transition and single
10321 	 * transition clocking.  We also support QAS (Quick Arbitration
10322 	 * and Selection) and Information Unit transfers on both the
10323 	 * control and array devices.
10324 	 */
10325 	if (port_type == CTL_PORT_SCSI)
10326 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10327 				    SID_SPI_IUS;
10328 
10329 	/* SAM-6 (no version claimed) */
10330 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10331 	/* SPC-5 (no version claimed) */
10332 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10333 	if (port_type == CTL_PORT_FC) {
10334 		/* FCP-2 ANSI INCITS.350:2003 */
10335 		scsi_ulto2b(0x0917, inq_ptr->version3);
10336 	} else if (port_type == CTL_PORT_SCSI) {
10337 		/* SPI-4 ANSI INCITS.362:200x */
10338 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10339 	} else if (port_type == CTL_PORT_ISCSI) {
10340 		/* iSCSI (no version claimed) */
10341 		scsi_ulto2b(0x0960, inq_ptr->version3);
10342 	} else if (port_type == CTL_PORT_SAS) {
10343 		/* SAS (no version claimed) */
10344 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10345 	} else if (port_type == CTL_PORT_UMASS) {
10346 		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10347 		scsi_ulto2b(0x1730, inq_ptr->version3);
10348 	}
10349 
10350 	if (lun == NULL) {
10351 		/* SBC-4 (no version claimed) */
10352 		scsi_ulto2b(0x0600, inq_ptr->version4);
10353 	} else {
10354 		switch (lun->be_lun->lun_type) {
10355 		case T_DIRECT:
10356 			/* SBC-4 (no version claimed) */
10357 			scsi_ulto2b(0x0600, inq_ptr->version4);
10358 			break;
10359 		case T_PROCESSOR:
10360 			break;
10361 		case T_CDROM:
10362 			/* MMC-6 (no version claimed) */
10363 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10364 			break;
10365 		default:
10366 			break;
10367 		}
10368 	}
10369 
10370 	ctl_set_success(ctsio);
10371 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10372 	ctsio->be_move_done = ctl_config_move_done;
10373 	ctl_datamove((union ctl_io *)ctsio);
10374 	return (CTL_RETVAL_COMPLETE);
10375 }
10376 
10377 int
10378 ctl_inquiry(struct ctl_scsiio *ctsio)
10379 {
10380 	struct scsi_inquiry *cdb;
10381 	int retval;
10382 
10383 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10384 
10385 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10386 	if (cdb->byte2 & SI_EVPD)
10387 		retval = ctl_inquiry_evpd(ctsio);
10388 	else if (cdb->page_code == 0)
10389 		retval = ctl_inquiry_std(ctsio);
10390 	else {
10391 		ctl_set_invalid_field(ctsio,
10392 				      /*sks_valid*/ 1,
10393 				      /*command*/ 1,
10394 				      /*field*/ 2,
10395 				      /*bit_valid*/ 0,
10396 				      /*bit*/ 0);
10397 		ctl_done((union ctl_io *)ctsio);
10398 		return (CTL_RETVAL_COMPLETE);
10399 	}
10400 
10401 	return (retval);
10402 }
10403 
10404 int
10405 ctl_get_config(struct ctl_scsiio *ctsio)
10406 {
10407 	struct ctl_lun *lun = CTL_LUN(ctsio);
10408 	struct scsi_get_config_header *hdr;
10409 	struct scsi_get_config_feature *feature;
10410 	struct scsi_get_config *cdb;
10411 	uint32_t alloc_len, data_len;
10412 	int rt, starting;
10413 
10414 	cdb = (struct scsi_get_config *)ctsio->cdb;
10415 	rt = (cdb->rt & SGC_RT_MASK);
10416 	starting = scsi_2btoul(cdb->starting_feature);
10417 	alloc_len = scsi_2btoul(cdb->length);
10418 
10419 	data_len = sizeof(struct scsi_get_config_header) +
10420 	    sizeof(struct scsi_get_config_feature) + 8 +
10421 	    sizeof(struct scsi_get_config_feature) + 8 +
10422 	    sizeof(struct scsi_get_config_feature) + 4 +
10423 	    sizeof(struct scsi_get_config_feature) + 4 +
10424 	    sizeof(struct scsi_get_config_feature) + 8 +
10425 	    sizeof(struct scsi_get_config_feature) +
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 	    sizeof(struct scsi_get_config_feature) + 4;
10432 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10433 	ctsio->kern_sg_entries = 0;
10434 	ctsio->kern_rel_offset = 0;
10435 
10436 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10437 	if (lun->flags & CTL_LUN_NO_MEDIA)
10438 		scsi_ulto2b(0x0000, hdr->current_profile);
10439 	else
10440 		scsi_ulto2b(0x0010, hdr->current_profile);
10441 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10442 
10443 	if (starting > 0x003b)
10444 		goto done;
10445 	if (starting > 0x003a)
10446 		goto f3b;
10447 	if (starting > 0x002b)
10448 		goto f3a;
10449 	if (starting > 0x002a)
10450 		goto f2b;
10451 	if (starting > 0x001f)
10452 		goto f2a;
10453 	if (starting > 0x001e)
10454 		goto f1f;
10455 	if (starting > 0x001d)
10456 		goto f1e;
10457 	if (starting > 0x0010)
10458 		goto f1d;
10459 	if (starting > 0x0003)
10460 		goto f10;
10461 	if (starting > 0x0002)
10462 		goto f3;
10463 	if (starting > 0x0001)
10464 		goto f2;
10465 	if (starting > 0x0000)
10466 		goto f1;
10467 
10468 	/* Profile List */
10469 	scsi_ulto2b(0x0000, feature->feature_code);
10470 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10471 	feature->add_length = 8;
10472 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10473 	feature->feature_data[2] = 0x00;
10474 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10475 	feature->feature_data[6] = 0x01;
10476 	feature = (struct scsi_get_config_feature *)
10477 	    &feature->feature_data[feature->add_length];
10478 
10479 f1:	/* Core */
10480 	scsi_ulto2b(0x0001, feature->feature_code);
10481 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10482 	feature->add_length = 8;
10483 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10484 	feature->feature_data[4] = 0x03;
10485 	feature = (struct scsi_get_config_feature *)
10486 	    &feature->feature_data[feature->add_length];
10487 
10488 f2:	/* Morphing */
10489 	scsi_ulto2b(0x0002, feature->feature_code);
10490 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10491 	feature->add_length = 4;
10492 	feature->feature_data[0] = 0x02;
10493 	feature = (struct scsi_get_config_feature *)
10494 	    &feature->feature_data[feature->add_length];
10495 
10496 f3:	/* Removable Medium */
10497 	scsi_ulto2b(0x0003, feature->feature_code);
10498 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10499 	feature->add_length = 4;
10500 	feature->feature_data[0] = 0x39;
10501 	feature = (struct scsi_get_config_feature *)
10502 	    &feature->feature_data[feature->add_length];
10503 
10504 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10505 		goto done;
10506 
10507 f10:	/* Random Read */
10508 	scsi_ulto2b(0x0010, feature->feature_code);
10509 	feature->flags = 0x00;
10510 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10511 		feature->flags |= SGC_F_CURRENT;
10512 	feature->add_length = 8;
10513 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10514 	scsi_ulto2b(1, &feature->feature_data[4]);
10515 	feature->feature_data[6] = 0x00;
10516 	feature = (struct scsi_get_config_feature *)
10517 	    &feature->feature_data[feature->add_length];
10518 
10519 f1d:	/* Multi-Read */
10520 	scsi_ulto2b(0x001D, feature->feature_code);
10521 	feature->flags = 0x00;
10522 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10523 		feature->flags |= SGC_F_CURRENT;
10524 	feature->add_length = 0;
10525 	feature = (struct scsi_get_config_feature *)
10526 	    &feature->feature_data[feature->add_length];
10527 
10528 f1e:	/* CD Read */
10529 	scsi_ulto2b(0x001E, feature->feature_code);
10530 	feature->flags = 0x00;
10531 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10532 		feature->flags |= SGC_F_CURRENT;
10533 	feature->add_length = 4;
10534 	feature->feature_data[0] = 0x00;
10535 	feature = (struct scsi_get_config_feature *)
10536 	    &feature->feature_data[feature->add_length];
10537 
10538 f1f:	/* DVD Read */
10539 	scsi_ulto2b(0x001F, feature->feature_code);
10540 	feature->flags = 0x08;
10541 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10542 		feature->flags |= SGC_F_CURRENT;
10543 	feature->add_length = 4;
10544 	feature->feature_data[0] = 0x01;
10545 	feature->feature_data[2] = 0x03;
10546 	feature = (struct scsi_get_config_feature *)
10547 	    &feature->feature_data[feature->add_length];
10548 
10549 f2a:	/* DVD+RW */
10550 	scsi_ulto2b(0x002A, feature->feature_code);
10551 	feature->flags = 0x04;
10552 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10553 		feature->flags |= SGC_F_CURRENT;
10554 	feature->add_length = 4;
10555 	feature->feature_data[0] = 0x00;
10556 	feature->feature_data[1] = 0x00;
10557 	feature = (struct scsi_get_config_feature *)
10558 	    &feature->feature_data[feature->add_length];
10559 
10560 f2b:	/* DVD+R */
10561 	scsi_ulto2b(0x002B, feature->feature_code);
10562 	feature->flags = 0x00;
10563 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10564 		feature->flags |= SGC_F_CURRENT;
10565 	feature->add_length = 4;
10566 	feature->feature_data[0] = 0x00;
10567 	feature = (struct scsi_get_config_feature *)
10568 	    &feature->feature_data[feature->add_length];
10569 
10570 f3a:	/* DVD+RW Dual Layer */
10571 	scsi_ulto2b(0x003A, feature->feature_code);
10572 	feature->flags = 0x00;
10573 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10574 		feature->flags |= SGC_F_CURRENT;
10575 	feature->add_length = 4;
10576 	feature->feature_data[0] = 0x00;
10577 	feature->feature_data[1] = 0x00;
10578 	feature = (struct scsi_get_config_feature *)
10579 	    &feature->feature_data[feature->add_length];
10580 
10581 f3b:	/* DVD+R Dual Layer */
10582 	scsi_ulto2b(0x003B, feature->feature_code);
10583 	feature->flags = 0x00;
10584 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10585 		feature->flags |= SGC_F_CURRENT;
10586 	feature->add_length = 4;
10587 	feature->feature_data[0] = 0x00;
10588 	feature = (struct scsi_get_config_feature *)
10589 	    &feature->feature_data[feature->add_length];
10590 
10591 done:
10592 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10593 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10594 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10595 		if (scsi_2btoul(feature->feature_code) == starting)
10596 			feature = (struct scsi_get_config_feature *)
10597 			    &feature->feature_data[feature->add_length];
10598 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10599 	}
10600 	scsi_ulto4b(data_len - 4, hdr->data_length);
10601 	ctsio->kern_data_len = min(data_len, alloc_len);
10602 	ctsio->kern_total_len = ctsio->kern_data_len;
10603 
10604 	ctl_set_success(ctsio);
10605 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10606 	ctsio->be_move_done = ctl_config_move_done;
10607 	ctl_datamove((union ctl_io *)ctsio);
10608 	return (CTL_RETVAL_COMPLETE);
10609 }
10610 
10611 int
10612 ctl_get_event_status(struct ctl_scsiio *ctsio)
10613 {
10614 	struct scsi_get_event_status_header *hdr;
10615 	struct scsi_get_event_status *cdb;
10616 	uint32_t alloc_len, data_len;
10617 
10618 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10619 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10620 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10621 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10622 		ctl_done((union ctl_io *)ctsio);
10623 		return (CTL_RETVAL_COMPLETE);
10624 	}
10625 	alloc_len = scsi_2btoul(cdb->length);
10626 
10627 	data_len = sizeof(struct scsi_get_event_status_header);
10628 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10629 	ctsio->kern_sg_entries = 0;
10630 	ctsio->kern_rel_offset = 0;
10631 	ctsio->kern_data_len = min(data_len, alloc_len);
10632 	ctsio->kern_total_len = ctsio->kern_data_len;
10633 
10634 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10635 	scsi_ulto2b(0, hdr->descr_length);
10636 	hdr->nea_class = SGESN_NEA;
10637 	hdr->supported_class = 0;
10638 
10639 	ctl_set_success(ctsio);
10640 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10641 	ctsio->be_move_done = ctl_config_move_done;
10642 	ctl_datamove((union ctl_io *)ctsio);
10643 	return (CTL_RETVAL_COMPLETE);
10644 }
10645 
10646 int
10647 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10648 {
10649 	struct scsi_mechanism_status_header *hdr;
10650 	struct scsi_mechanism_status *cdb;
10651 	uint32_t alloc_len, data_len;
10652 
10653 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10654 	alloc_len = scsi_2btoul(cdb->length);
10655 
10656 	data_len = sizeof(struct scsi_mechanism_status_header);
10657 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10658 	ctsio->kern_sg_entries = 0;
10659 	ctsio->kern_rel_offset = 0;
10660 	ctsio->kern_data_len = min(data_len, alloc_len);
10661 	ctsio->kern_total_len = ctsio->kern_data_len;
10662 
10663 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10664 	hdr->state1 = 0x00;
10665 	hdr->state2 = 0xe0;
10666 	scsi_ulto3b(0, hdr->lba);
10667 	hdr->slots_num = 0;
10668 	scsi_ulto2b(0, hdr->slots_length);
10669 
10670 	ctl_set_success(ctsio);
10671 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10672 	ctsio->be_move_done = ctl_config_move_done;
10673 	ctl_datamove((union ctl_io *)ctsio);
10674 	return (CTL_RETVAL_COMPLETE);
10675 }
10676 
10677 static void
10678 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10679 {
10680 
10681 	lba += 150;
10682 	buf[0] = 0;
10683 	buf[1] = bin2bcd((lba / 75) / 60);
10684 	buf[2] = bin2bcd((lba / 75) % 60);
10685 	buf[3] = bin2bcd(lba % 75);
10686 }
10687 
10688 int
10689 ctl_read_toc(struct ctl_scsiio *ctsio)
10690 {
10691 	struct ctl_lun *lun = CTL_LUN(ctsio);
10692 	struct scsi_read_toc_hdr *hdr;
10693 	struct scsi_read_toc_type01_descr *descr;
10694 	struct scsi_read_toc *cdb;
10695 	uint32_t alloc_len, data_len;
10696 	int format, msf;
10697 
10698 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10699 	msf = (cdb->byte2 & CD_MSF) != 0;
10700 	format = cdb->format;
10701 	alloc_len = scsi_2btoul(cdb->data_len);
10702 
10703 	data_len = sizeof(struct scsi_read_toc_hdr);
10704 	if (format == 0)
10705 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10706 	else
10707 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10708 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10709 	ctsio->kern_sg_entries = 0;
10710 	ctsio->kern_rel_offset = 0;
10711 	ctsio->kern_data_len = min(data_len, alloc_len);
10712 	ctsio->kern_total_len = ctsio->kern_data_len;
10713 
10714 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10715 	if (format == 0) {
10716 		scsi_ulto2b(0x12, hdr->data_length);
10717 		hdr->first = 1;
10718 		hdr->last = 1;
10719 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10720 		descr->addr_ctl = 0x14;
10721 		descr->track_number = 1;
10722 		if (msf)
10723 			ctl_ultomsf(0, descr->track_start);
10724 		else
10725 			scsi_ulto4b(0, descr->track_start);
10726 		descr++;
10727 		descr->addr_ctl = 0x14;
10728 		descr->track_number = 0xaa;
10729 		if (msf)
10730 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10731 		else
10732 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10733 	} else {
10734 		scsi_ulto2b(0x0a, hdr->data_length);
10735 		hdr->first = 1;
10736 		hdr->last = 1;
10737 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10738 		descr->addr_ctl = 0x14;
10739 		descr->track_number = 1;
10740 		if (msf)
10741 			ctl_ultomsf(0, descr->track_start);
10742 		else
10743 			scsi_ulto4b(0, descr->track_start);
10744 	}
10745 
10746 	ctl_set_success(ctsio);
10747 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10748 	ctsio->be_move_done = ctl_config_move_done;
10749 	ctl_datamove((union ctl_io *)ctsio);
10750 	return (CTL_RETVAL_COMPLETE);
10751 }
10752 
10753 /*
10754  * For known CDB types, parse the LBA and length.
10755  */
10756 static int
10757 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10758 {
10759 
10760 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10761 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10762 
10763 	switch (io->scsiio.cdb[0]) {
10764 	case COMPARE_AND_WRITE: {
10765 		struct scsi_compare_and_write *cdb;
10766 
10767 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10768 
10769 		*lba = scsi_8btou64(cdb->addr);
10770 		*len = cdb->length;
10771 		break;
10772 	}
10773 	case READ_6:
10774 	case WRITE_6: {
10775 		struct scsi_rw_6 *cdb;
10776 
10777 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10778 
10779 		*lba = scsi_3btoul(cdb->addr);
10780 		/* only 5 bits are valid in the most significant address byte */
10781 		*lba &= 0x1fffff;
10782 		*len = cdb->length;
10783 		break;
10784 	}
10785 	case READ_10:
10786 	case WRITE_10: {
10787 		struct scsi_rw_10 *cdb;
10788 
10789 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10790 
10791 		*lba = scsi_4btoul(cdb->addr);
10792 		*len = scsi_2btoul(cdb->length);
10793 		break;
10794 	}
10795 	case WRITE_VERIFY_10: {
10796 		struct scsi_write_verify_10 *cdb;
10797 
10798 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10799 
10800 		*lba = scsi_4btoul(cdb->addr);
10801 		*len = scsi_2btoul(cdb->length);
10802 		break;
10803 	}
10804 	case READ_12:
10805 	case WRITE_12: {
10806 		struct scsi_rw_12 *cdb;
10807 
10808 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10809 
10810 		*lba = scsi_4btoul(cdb->addr);
10811 		*len = scsi_4btoul(cdb->length);
10812 		break;
10813 	}
10814 	case WRITE_VERIFY_12: {
10815 		struct scsi_write_verify_12 *cdb;
10816 
10817 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10818 
10819 		*lba = scsi_4btoul(cdb->addr);
10820 		*len = scsi_4btoul(cdb->length);
10821 		break;
10822 	}
10823 	case READ_16:
10824 	case WRITE_16: {
10825 		struct scsi_rw_16 *cdb;
10826 
10827 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10828 
10829 		*lba = scsi_8btou64(cdb->addr);
10830 		*len = scsi_4btoul(cdb->length);
10831 		break;
10832 	}
10833 	case WRITE_ATOMIC_16: {
10834 		struct scsi_write_atomic_16 *cdb;
10835 
10836 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10837 
10838 		*lba = scsi_8btou64(cdb->addr);
10839 		*len = scsi_2btoul(cdb->length);
10840 		break;
10841 	}
10842 	case WRITE_VERIFY_16: {
10843 		struct scsi_write_verify_16 *cdb;
10844 
10845 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10846 
10847 		*lba = scsi_8btou64(cdb->addr);
10848 		*len = scsi_4btoul(cdb->length);
10849 		break;
10850 	}
10851 	case WRITE_SAME_10: {
10852 		struct scsi_write_same_10 *cdb;
10853 
10854 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10855 
10856 		*lba = scsi_4btoul(cdb->addr);
10857 		*len = scsi_2btoul(cdb->length);
10858 		break;
10859 	}
10860 	case WRITE_SAME_16: {
10861 		struct scsi_write_same_16 *cdb;
10862 
10863 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10864 
10865 		*lba = scsi_8btou64(cdb->addr);
10866 		*len = scsi_4btoul(cdb->length);
10867 		break;
10868 	}
10869 	case VERIFY_10: {
10870 		struct scsi_verify_10 *cdb;
10871 
10872 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10873 
10874 		*lba = scsi_4btoul(cdb->addr);
10875 		*len = scsi_2btoul(cdb->length);
10876 		break;
10877 	}
10878 	case VERIFY_12: {
10879 		struct scsi_verify_12 *cdb;
10880 
10881 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10882 
10883 		*lba = scsi_4btoul(cdb->addr);
10884 		*len = scsi_4btoul(cdb->length);
10885 		break;
10886 	}
10887 	case VERIFY_16: {
10888 		struct scsi_verify_16 *cdb;
10889 
10890 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10891 
10892 		*lba = scsi_8btou64(cdb->addr);
10893 		*len = scsi_4btoul(cdb->length);
10894 		break;
10895 	}
10896 	case UNMAP: {
10897 		*lba = 0;
10898 		*len = UINT64_MAX;
10899 		break;
10900 	}
10901 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10902 		struct scsi_get_lba_status *cdb;
10903 
10904 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10905 		*lba = scsi_8btou64(cdb->addr);
10906 		*len = UINT32_MAX;
10907 		break;
10908 	}
10909 	default:
10910 		*lba = 0;
10911 		*len = UINT64_MAX;
10912 		return (1);
10913 	}
10914 
10915 	return (0);
10916 }
10917 
10918 static ctl_action
10919 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10920     bool seq)
10921 {
10922 	uint64_t endlba1, endlba2;
10923 
10924 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10925 	endlba2 = lba2 + len2 - 1;
10926 
10927 	if ((endlba1 < lba2) || (endlba2 < lba1))
10928 		return (CTL_ACTION_PASS);
10929 	else
10930 		return (CTL_ACTION_BLOCK);
10931 }
10932 
10933 static int
10934 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10935 {
10936 	struct ctl_ptr_len_flags *ptrlen;
10937 	struct scsi_unmap_desc *buf, *end, *range;
10938 	uint64_t lba;
10939 	uint32_t len;
10940 
10941 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
10942 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
10943 
10944 	/* If not UNMAP -- go other way. */
10945 	if (io->scsiio.cdb[0] != UNMAP)
10946 		return (CTL_ACTION_SKIP);
10947 
10948 	/* If UNMAP without data -- block and wait for data. */
10949 	ptrlen = (struct ctl_ptr_len_flags *)
10950 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10951 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10952 	    ptrlen->ptr == NULL)
10953 		return (CTL_ACTION_BLOCK);
10954 
10955 	/* UNMAP with data -- check for collision. */
10956 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10957 	end = buf + ptrlen->len / sizeof(*buf);
10958 	for (range = buf; range < end; range++) {
10959 		lba = scsi_8btou64(range->lba);
10960 		len = scsi_4btoul(range->length);
10961 		if ((lba < lba2 + len2) && (lba + len > lba2))
10962 			return (CTL_ACTION_BLOCK);
10963 	}
10964 	return (CTL_ACTION_PASS);
10965 }
10966 
10967 static ctl_action
10968 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10969 {
10970 	uint64_t lba1, lba2;
10971 	uint64_t len1, len2;
10972 	int retval;
10973 
10974 	retval = ctl_get_lba_len(io2, &lba2, &len2);
10975 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10976 
10977 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10978 	if (retval != CTL_ACTION_SKIP)
10979 		return (retval);
10980 
10981 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10982 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
10983 
10984 	if (seq && (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE))
10985 		seq = FALSE;
10986 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10987 }
10988 
10989 static ctl_action
10990 ctl_seq_check(union ctl_io *io1, union ctl_io *io2)
10991 {
10992 	uint64_t lba1, lba2;
10993 	uint64_t len1, len2;
10994 	int retval __diagused;
10995 
10996 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10997 		return (CTL_ACTION_PASS);
10998 	retval = ctl_get_lba_len(io1, &lba1, &len1);
10999 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
11000 	retval = ctl_get_lba_len(io2, &lba2, &len2);
11001 	KASSERT(retval == 0, ("ctl_get_lba_len() error"));
11002 
11003 	if (lba1 + len1 == lba2)
11004 		return (CTL_ACTION_BLOCK);
11005 	return (CTL_ACTION_PASS);
11006 }
11007 
11008 static ctl_action
11009 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11010     const uint8_t *serialize_row, union ctl_io *ooa_io)
11011 {
11012 
11013 	/*
11014 	 * The initiator attempted multiple untagged commands at the same
11015 	 * time.  Can't do that.
11016 	 */
11017 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11018 	 && __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11019 	 && ((pending_io->io_hdr.nexus.targ_port ==
11020 	      ooa_io->io_hdr.nexus.targ_port)
11021 	  && (pending_io->io_hdr.nexus.initid ==
11022 	      ooa_io->io_hdr.nexus.initid))
11023 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11024 	      CTL_FLAG_STATUS_SENT)) == 0))
11025 		return (CTL_ACTION_OVERLAP);
11026 
11027 	/*
11028 	 * The initiator attempted to send multiple tagged commands with
11029 	 * the same ID.  (It's fine if different initiators have the same
11030 	 * tag ID.)
11031 	 *
11032 	 * Even if all of those conditions are true, we don't kill the I/O
11033 	 * if the command ahead of us has been aborted.  We won't end up
11034 	 * sending it to the FETD, and it's perfectly legal to resend a
11035 	 * command with the same tag number as long as the previous
11036 	 * instance of this tag number has been aborted somehow.
11037 	 */
11038 	if (__predict_true(pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11039 	 && __predict_true(ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11040 	 && __predict_false(pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11041 	 && ((pending_io->io_hdr.nexus.targ_port ==
11042 	      ooa_io->io_hdr.nexus.targ_port)
11043 	  && (pending_io->io_hdr.nexus.initid ==
11044 	      ooa_io->io_hdr.nexus.initid))
11045 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11046 	      CTL_FLAG_STATUS_SENT)) == 0))
11047 		return (CTL_ACTION_OVERLAP_TAG);
11048 
11049 	/*
11050 	 * If we get a head of queue tag, SAM-3 says that we should
11051 	 * immediately execute it.
11052 	 *
11053 	 * What happens if this command would normally block for some other
11054 	 * reason?  e.g. a request sense with a head of queue tag
11055 	 * immediately after a write.  Normally that would block, but this
11056 	 * will result in its getting executed immediately...
11057 	 *
11058 	 * We currently return "pass" instead of "skip", so we'll end up
11059 	 * going through the rest of the queue to check for overlapped tags.
11060 	 *
11061 	 * XXX KDM check for other types of blockage first??
11062 	 */
11063 	if (__predict_false(pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
11064 		return (CTL_ACTION_PASS);
11065 
11066 	/*
11067 	 * Simple tags get blocked until all head of queue and ordered tags
11068 	 * ahead of them have completed.  I'm lumping untagged commands in
11069 	 * with simple tags here.  XXX KDM is that the right thing to do?
11070 	 */
11071 	if (__predict_false(ooa_io->scsiio.tag_type == CTL_TAG_ORDERED) ||
11072 	    __predict_false(ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE))
11073 		return (CTL_ACTION_BLOCK);
11074 
11075 	/* Unsupported command in OOA queue. */
11076 	if (__predict_false(ooa_io->scsiio.seridx == CTL_SERIDX_INVLD))
11077 		return (CTL_ACTION_PASS);
11078 
11079 	switch (serialize_row[ooa_io->scsiio.seridx]) {
11080 	case CTL_SER_SEQ:
11081 		if (lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11082 			return (ctl_seq_check(ooa_io, pending_io));
11083 		/* FALLTHROUGH */
11084 	case CTL_SER_PASS:
11085 		return (CTL_ACTION_PASS);
11086 	case CTL_SER_EXTENTOPT:
11087 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
11088 		    SCP_QUEUE_ALG_UNRESTRICTED)
11089 			return (CTL_ACTION_PASS);
11090 		/* FALLTHROUGH */
11091 	case CTL_SER_EXTENT:
11092 		return (ctl_extent_check(ooa_io, pending_io,
11093 		    (lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11094 	case CTL_SER_BLOCKOPT:
11095 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) ==
11096 		    SCP_QUEUE_ALG_UNRESTRICTED)
11097 			return (CTL_ACTION_PASS);
11098 		/* FALLTHROUGH */
11099 	case CTL_SER_BLOCK:
11100 		return (CTL_ACTION_BLOCK);
11101 	default:
11102 		__assert_unreachable();
11103 	}
11104 }
11105 
11106 /*
11107  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11108  * Assumptions:
11109  * - pending_io is generally either incoming, or on the blocked queue
11110  * - starting I/O is the I/O we want to start the check with.
11111  */
11112 static ctl_action
11113 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11114 	      union ctl_io **starting_io)
11115 {
11116 	union ctl_io *ooa_io = *starting_io;
11117 	const uint8_t *serialize_row;
11118 	ctl_action action;
11119 
11120 	mtx_assert(&lun->lun_lock, MA_OWNED);
11121 
11122 	/*
11123 	 * Aborted commands are not going to be executed and may even
11124 	 * not report completion, so we don't care about their order.
11125 	 * Let them complete ASAP to clean the OOA queue.
11126 	 */
11127 	if (__predict_false(pending_io->io_hdr.flags & CTL_FLAG_ABORT))
11128 		return (CTL_ACTION_SKIP);
11129 
11130 	/*
11131 	 * Ordered tags have to block until all items ahead of them have
11132 	 * completed.  If we get called with an ordered tag, we always
11133 	 * block, if something else is ahead of us in the queue.
11134 	 */
11135 	if ((pending_io->scsiio.tag_type == CTL_TAG_ORDERED) &&
11136 	    (ooa_io != NULL))
11137 		return (CTL_ACTION_BLOCK);
11138 
11139 	serialize_row = ctl_serialize_table[pending_io->scsiio.seridx];
11140 
11141 	/*
11142 	 * Run back along the OOA queue, starting with the current
11143 	 * blocked I/O and going through every I/O before it on the
11144 	 * queue.  If starting_io is NULL, we'll just end up returning
11145 	 * CTL_ACTION_PASS.
11146 	 */
11147 	for (; ooa_io != NULL;
11148 	     ooa_io = (union ctl_io *)LIST_NEXT(&ooa_io->io_hdr, ooa_links)) {
11149 		action = ctl_check_for_blockage(lun, pending_io, serialize_row,
11150 		    ooa_io);
11151 		if (action != CTL_ACTION_PASS) {
11152 			*starting_io = ooa_io;
11153 			return (action);
11154 		}
11155 	}
11156 
11157 	*starting_io = NULL;
11158 	return (CTL_ACTION_PASS);
11159 }
11160 
11161 /*
11162  * Try to unblock the specified I/O.
11163  *
11164  * skip parameter allows explicitly skip present blocker of the I/O,
11165  * starting from the previous one on OOA queue.  It can be used when
11166  * we know for sure that the blocker I/O does no longer count.
11167  */
11168 static void
11169 ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io, bool skip)
11170 {
11171 	struct ctl_softc *softc = lun->ctl_softc;
11172 	union ctl_io *bio, *obio;
11173 	const struct ctl_cmd_entry *entry;
11174 	union ctl_ha_msg msg_info;
11175 	ctl_action action;
11176 
11177 	mtx_assert(&lun->lun_lock, MA_OWNED);
11178 
11179 	if (io->io_hdr.blocker == NULL)
11180 		return;
11181 
11182 	obio = bio = io->io_hdr.blocker;
11183 	if (skip)
11184 		bio = (union ctl_io *)LIST_NEXT(&bio->io_hdr, ooa_links);
11185 	action = ctl_check_ooa(lun, io, &bio);
11186 	if (action == CTL_ACTION_BLOCK) {
11187 		/* Still blocked, but may be by different I/O now. */
11188 		if (bio != obio) {
11189 			TAILQ_REMOVE(&obio->io_hdr.blocked_queue,
11190 			    &io->io_hdr, blocked_links);
11191 			TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue,
11192 			    &io->io_hdr, blocked_links);
11193 			io->io_hdr.blocker = bio;
11194 		}
11195 		return;
11196 	}
11197 
11198 	/* No longer blocked, one way or another. */
11199 	TAILQ_REMOVE(&obio->io_hdr.blocked_queue, &io->io_hdr, blocked_links);
11200 	io->io_hdr.blocker = NULL;
11201 
11202 	switch (action) {
11203 	case CTL_ACTION_PASS:
11204 	case CTL_ACTION_SKIP:
11205 
11206 		/* Serializing commands from the other SC retire there. */
11207 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11208 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11209 			io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11210 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11211 			msg_info.hdr.serializing_sc = io;
11212 			msg_info.hdr.msg_type = CTL_MSG_R2R;
11213 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11214 			    sizeof(msg_info.hdr), M_NOWAIT);
11215 			break;
11216 		}
11217 
11218 		/*
11219 		 * Check this I/O for LUN state changes that may have happened
11220 		 * while this command was blocked. The LUN state may have been
11221 		 * changed by a command ahead of us in the queue.
11222 		 */
11223 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11224 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
11225 			ctl_done(io);
11226 			break;
11227 		}
11228 
11229 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11230 		ctl_enqueue_rtr(io);
11231 		break;
11232 	default:
11233 		__assert_unreachable();
11234 	case CTL_ACTION_OVERLAP:
11235 		ctl_set_overlapped_cmd(&io->scsiio);
11236 		goto error;
11237 	case CTL_ACTION_OVERLAP_TAG:
11238 		ctl_set_overlapped_tag(&io->scsiio,
11239 		    io->scsiio.tag_num & 0xff);
11240 error:
11241 		/* Serializing commands from the other SC are done here. */
11242 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11243 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11244 			ctl_try_unblock_others(lun, io, TRUE);
11245 			LIST_REMOVE(&io->io_hdr, ooa_links);
11246 
11247 			ctl_copy_sense_data_back(io, &msg_info);
11248 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11249 			msg_info.hdr.serializing_sc = NULL;
11250 			msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
11251 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11252 			    sizeof(msg_info.scsi), M_WAITOK);
11253 			ctl_free_io(io);
11254 			break;
11255 		}
11256 
11257 		ctl_done(io);
11258 		break;
11259 	}
11260 }
11261 
11262 /*
11263  * Try to unblock I/Os blocked by the specified I/O.
11264  *
11265  * skip parameter allows explicitly skip the specified I/O as blocker,
11266  * starting from the previous one on the OOA queue.  It can be used when
11267  * we know for sure that the specified I/O does no longer count (done).
11268  * It has to be still on OOA queue though so that we know where to start.
11269  */
11270 static void
11271 ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *bio, bool skip)
11272 {
11273 	union ctl_io *io, *next_io;
11274 
11275 	mtx_assert(&lun->lun_lock, MA_OWNED);
11276 
11277 	for (io = (union ctl_io *)TAILQ_FIRST(&bio->io_hdr.blocked_queue);
11278 	     io != NULL; io = next_io) {
11279 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, blocked_links);
11280 
11281 		KASSERT(io->io_hdr.blocker != NULL,
11282 		    ("I/O %p on blocked list without blocker", io));
11283 		ctl_try_unblock_io(lun, io, skip);
11284 	}
11285 	KASSERT(!skip || TAILQ_EMPTY(&bio->io_hdr.blocked_queue),
11286 	    ("blocked_queue is not empty after skipping %p", bio));
11287 }
11288 
11289 /*
11290  * This routine (with one exception) checks LUN flags that can be set by
11291  * commands ahead of us in the OOA queue.  These flags have to be checked
11292  * when a command initially comes in, and when we pull a command off the
11293  * blocked queue and are preparing to execute it.  The reason we have to
11294  * check these flags for commands on the blocked queue is that the LUN
11295  * state may have been changed by a command ahead of us while we're on the
11296  * blocked queue.
11297  *
11298  * Ordering is somewhat important with these checks, so please pay
11299  * careful attention to the placement of any new checks.
11300  */
11301 static int
11302 ctl_scsiio_lun_check(struct ctl_lun *lun,
11303     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11304 {
11305 	struct ctl_softc *softc = lun->ctl_softc;
11306 	int retval;
11307 	uint32_t residx;
11308 
11309 	retval = 0;
11310 
11311 	mtx_assert(&lun->lun_lock, MA_OWNED);
11312 
11313 	/*
11314 	 * If this shelf is a secondary shelf controller, we may have to
11315 	 * reject some commands disallowed by HA mode and link state.
11316 	 */
11317 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11318 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11319 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11320 			ctl_set_lun_unavail(ctsio);
11321 			retval = 1;
11322 			goto bailout;
11323 		}
11324 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11325 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11326 			ctl_set_lun_transit(ctsio);
11327 			retval = 1;
11328 			goto bailout;
11329 		}
11330 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11331 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11332 			ctl_set_lun_standby(ctsio);
11333 			retval = 1;
11334 			goto bailout;
11335 		}
11336 
11337 		/* The rest of checks are only done on executing side */
11338 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11339 			goto bailout;
11340 	}
11341 
11342 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11343 		if (lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11344 			ctl_set_hw_write_protected(ctsio);
11345 			retval = 1;
11346 			goto bailout;
11347 		}
11348 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11349 			ctl_set_sense(ctsio, /*current_error*/ 1,
11350 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11351 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11352 			retval = 1;
11353 			goto bailout;
11354 		}
11355 	}
11356 
11357 	/*
11358 	 * Check for a reservation conflict.  If this command isn't allowed
11359 	 * even on reserved LUNs, and if this initiator isn't the one who
11360 	 * reserved us, reject the command with a reservation conflict.
11361 	 */
11362 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11363 	if ((lun->flags & CTL_LUN_RESERVED)
11364 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11365 		if (lun->res_idx != residx) {
11366 			ctl_set_reservation_conflict(ctsio);
11367 			retval = 1;
11368 			goto bailout;
11369 		}
11370 	}
11371 
11372 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11373 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11374 		/* No reservation or command is allowed. */;
11375 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11376 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11377 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11378 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11379 		/* The command is allowed for Write Exclusive resv. */;
11380 	} else {
11381 		/*
11382 		 * if we aren't registered or it's a res holder type
11383 		 * reservation and this isn't the res holder then set a
11384 		 * conflict.
11385 		 */
11386 		if (ctl_get_prkey(lun, residx) == 0 ||
11387 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11388 			ctl_set_reservation_conflict(ctsio);
11389 			retval = 1;
11390 			goto bailout;
11391 		}
11392 	}
11393 
11394 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11395 		if (lun->flags & CTL_LUN_EJECTED)
11396 			ctl_set_lun_ejected(ctsio);
11397 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11398 			if (lun->flags & CTL_LUN_REMOVABLE)
11399 				ctl_set_lun_no_media(ctsio);
11400 			else
11401 				ctl_set_lun_int_reqd(ctsio);
11402 		} else if (lun->flags & CTL_LUN_STOPPED)
11403 			ctl_set_lun_stopped(ctsio);
11404 		else
11405 			goto bailout;
11406 		retval = 1;
11407 		goto bailout;
11408 	}
11409 
11410 bailout:
11411 	return (retval);
11412 }
11413 
11414 static void
11415 ctl_failover_io(union ctl_io *io, int have_lock)
11416 {
11417 	ctl_set_busy(&io->scsiio);
11418 	ctl_done(io);
11419 }
11420 
11421 static void
11422 ctl_failover_lun(union ctl_io *rio)
11423 {
11424 	struct ctl_softc *softc = CTL_SOFTC(rio);
11425 	struct ctl_lun *lun;
11426 	struct ctl_io_hdr *io, *next_io;
11427 	uint32_t targ_lun;
11428 
11429 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11430 	CTL_DEBUG_PRINT(("FAILOVER for lun %u\n", targ_lun));
11431 
11432 	/* Find and lock the LUN. */
11433 	mtx_lock(&softc->ctl_lock);
11434 	if (targ_lun > ctl_max_luns ||
11435 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11436 		mtx_unlock(&softc->ctl_lock);
11437 		return;
11438 	}
11439 	mtx_lock(&lun->lun_lock);
11440 	mtx_unlock(&softc->ctl_lock);
11441 	if (lun->flags & CTL_LUN_DISABLED) {
11442 		mtx_unlock(&lun->lun_lock);
11443 		return;
11444 	}
11445 
11446 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11447 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11448 			/* We are master */
11449 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11450 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11451 					io->flags |= CTL_FLAG_ABORT |
11452 					    CTL_FLAG_FAILOVER;
11453 					ctl_try_unblock_io(lun,
11454 					    (union ctl_io *)io, FALSE);
11455 				} else { /* This can be only due to DATAMOVE */
11456 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11457 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11458 					io->flags |= CTL_FLAG_IO_ACTIVE;
11459 					io->port_status = 31340;
11460 					ctl_enqueue_isc((union ctl_io *)io);
11461 				}
11462 			} else
11463 			/* We are slave */
11464 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11465 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11466 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11467 					io->flags |= CTL_FLAG_FAILOVER;
11468 				} else {
11469 					ctl_set_busy(&((union ctl_io *)io)->
11470 					    scsiio);
11471 					ctl_done((union ctl_io *)io);
11472 				}
11473 			}
11474 		}
11475 	} else { /* SERIALIZE modes */
11476 		LIST_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11477 			/* We are master */
11478 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11479 				if (io->blocker != NULL) {
11480 					TAILQ_REMOVE(&io->blocker->io_hdr.blocked_queue,
11481 					    io, blocked_links);
11482 					io->blocker = NULL;
11483 				}
11484 				ctl_try_unblock_others(lun, (union ctl_io *)io,
11485 				    TRUE);
11486 				LIST_REMOVE(io, ooa_links);
11487 				ctl_free_io((union ctl_io *)io);
11488 			} else
11489 			/* We are slave */
11490 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11491 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11492 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11493 					ctl_set_busy(&((union ctl_io *)io)->
11494 					    scsiio);
11495 					ctl_done((union ctl_io *)io);
11496 				}
11497 			}
11498 		}
11499 	}
11500 	mtx_unlock(&lun->lun_lock);
11501 }
11502 
11503 static void
11504 ctl_scsiio_precheck(struct ctl_scsiio *ctsio)
11505 {
11506 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
11507 	struct ctl_lun *lun;
11508 	const struct ctl_cmd_entry *entry;
11509 	union ctl_io *bio;
11510 	uint32_t initidx, targ_lun;
11511 
11512 	lun = NULL;
11513 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11514 	if (targ_lun < ctl_max_luns)
11515 		lun = softc->ctl_luns[targ_lun];
11516 	if (lun) {
11517 		/*
11518 		 * If the LUN is invalid, pretend that it doesn't exist.
11519 		 * It will go away as soon as all pending I/O has been
11520 		 * completed.
11521 		 */
11522 		mtx_lock(&lun->lun_lock);
11523 		if (lun->flags & CTL_LUN_DISABLED) {
11524 			mtx_unlock(&lun->lun_lock);
11525 			lun = NULL;
11526 		}
11527 	}
11528 	CTL_LUN(ctsio) = lun;
11529 	if (lun) {
11530 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11531 
11532 		/*
11533 		 * Every I/O goes into the OOA queue for a particular LUN,
11534 		 * and stays there until completion.
11535 		 */
11536 #ifdef CTL_TIME_IO
11537 		if (LIST_EMPTY(&lun->ooa_queue))
11538 			lun->idle_time += getsbinuptime() - lun->last_busy;
11539 #endif
11540 		LIST_INSERT_HEAD(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11541 	}
11542 
11543 	/* Get command entry and return error if it is unsuppotyed. */
11544 	entry = ctl_validate_command(ctsio);
11545 	if (entry == NULL) {
11546 		if (lun)
11547 			mtx_unlock(&lun->lun_lock);
11548 		return;
11549 	}
11550 
11551 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11552 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11553 
11554 	/*
11555 	 * Check to see whether we can send this command to LUNs that don't
11556 	 * exist.  This should pretty much only be the case for inquiry
11557 	 * and request sense.  Further checks, below, really require having
11558 	 * a LUN, so we can't really check the command anymore.  Just put
11559 	 * it on the rtr queue.
11560 	 */
11561 	if (lun == NULL) {
11562 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11563 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11564 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11565 			return;
11566 		}
11567 
11568 		ctl_set_unsupported_lun(ctsio);
11569 		ctl_done((union ctl_io *)ctsio);
11570 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11571 		return;
11572 	} else {
11573 		/*
11574 		 * Make sure we support this particular command on this LUN.
11575 		 * e.g., we don't support writes to the control LUN.
11576 		 */
11577 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11578 			mtx_unlock(&lun->lun_lock);
11579 			ctl_set_invalid_opcode(ctsio);
11580 			ctl_done((union ctl_io *)ctsio);
11581 			return;
11582 		}
11583 	}
11584 
11585 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11586 
11587 	/*
11588 	 * If we've got a request sense, it'll clear the contingent
11589 	 * allegiance condition.  Otherwise, if we have a CA condition for
11590 	 * this initiator, clear it, because it sent down a command other
11591 	 * than request sense.
11592 	 */
11593 	if (ctsio->cdb[0] != REQUEST_SENSE) {
11594 		struct scsi_sense_data *ps;
11595 
11596 		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11597 		if (ps != NULL)
11598 			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11599 	}
11600 
11601 	/*
11602 	 * If the command has this flag set, it handles its own unit
11603 	 * attention reporting, we shouldn't do anything.  Otherwise we
11604 	 * check for any pending unit attentions, and send them back to the
11605 	 * initiator.  We only do this when a command initially comes in,
11606 	 * not when we pull it off the blocked queue.
11607 	 *
11608 	 * According to SAM-3, section 5.3.2, the order that things get
11609 	 * presented back to the host is basically unit attentions caused
11610 	 * by some sort of reset event, busy status, reservation conflicts
11611 	 * or task set full, and finally any other status.
11612 	 *
11613 	 * One issue here is that some of the unit attentions we report
11614 	 * don't fall into the "reset" category (e.g. "reported luns data
11615 	 * has changed").  So reporting it here, before the reservation
11616 	 * check, may be technically wrong.  I guess the only thing to do
11617 	 * would be to check for and report the reset events here, and then
11618 	 * check for the other unit attention types after we check for a
11619 	 * reservation conflict.
11620 	 *
11621 	 * XXX KDM need to fix this
11622 	 */
11623 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11624 		ctl_ua_type ua_type;
11625 		u_int sense_len = 0;
11626 
11627 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11628 		    &sense_len, SSD_TYPE_NONE);
11629 		if (ua_type != CTL_UA_NONE) {
11630 			mtx_unlock(&lun->lun_lock);
11631 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11632 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11633 			ctsio->sense_len = sense_len;
11634 			ctl_done((union ctl_io *)ctsio);
11635 			return;
11636 		}
11637 	}
11638 
11639 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11640 		mtx_unlock(&lun->lun_lock);
11641 		ctl_done((union ctl_io *)ctsio);
11642 		return;
11643 	}
11644 
11645 	/*
11646 	 * XXX CHD this is where we want to send IO to other side if
11647 	 * this LUN is secondary on this SC. We will need to make a copy
11648 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11649 	 * the copy we send as FROM_OTHER.
11650 	 * We also need to stuff the address of the original IO so we can
11651 	 * find it easily. Something similar will need be done on the other
11652 	 * side so when we are done we can find the copy.
11653 	 */
11654 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11655 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11656 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11657 		union ctl_ha_msg msg_info;
11658 		int isc_retval;
11659 
11660 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11661 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11662 		mtx_unlock(&lun->lun_lock);
11663 
11664 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11665 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11666 		msg_info.hdr.serializing_sc = NULL;
11667 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11668 		msg_info.scsi.tag_num = ctsio->tag_num;
11669 		msg_info.scsi.tag_type = ctsio->tag_type;
11670 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11671 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11672 		msg_info.scsi.priority = ctsio->priority;
11673 
11674 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11675 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11676 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11677 			ctsio->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11678 			ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
11679 			ctl_set_busy(ctsio);
11680 			ctl_done((union ctl_io *)ctsio);
11681 			return;
11682 		}
11683 		return;
11684 	}
11685 
11686 	bio = (union ctl_io *)LIST_NEXT(&ctsio->io_hdr, ooa_links);
11687 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
11688 	case CTL_ACTION_PASS:
11689 	case CTL_ACTION_SKIP:
11690 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11691 		mtx_unlock(&lun->lun_lock);
11692 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11693 		break;
11694 	case CTL_ACTION_BLOCK:
11695 		ctsio->io_hdr.blocker = bio;
11696 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
11697 				  blocked_links);
11698 		mtx_unlock(&lun->lun_lock);
11699 		break;
11700 	case CTL_ACTION_OVERLAP:
11701 		mtx_unlock(&lun->lun_lock);
11702 		ctl_set_overlapped_cmd(ctsio);
11703 		ctl_done((union ctl_io *)ctsio);
11704 		break;
11705 	case CTL_ACTION_OVERLAP_TAG:
11706 		mtx_unlock(&lun->lun_lock);
11707 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11708 		ctl_done((union ctl_io *)ctsio);
11709 		break;
11710 	default:
11711 		__assert_unreachable();
11712 	}
11713 }
11714 
11715 const struct ctl_cmd_entry *
11716 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11717 {
11718 	const struct ctl_cmd_entry *entry;
11719 	int service_action;
11720 
11721 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11722 	if (sa)
11723 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11724 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11725 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11726 		entry = &((const struct ctl_cmd_entry *)
11727 		    entry->execute)[service_action];
11728 	}
11729 	return (entry);
11730 }
11731 
11732 const struct ctl_cmd_entry *
11733 ctl_validate_command(struct ctl_scsiio *ctsio)
11734 {
11735 	const struct ctl_cmd_entry *entry;
11736 	int i, sa;
11737 	uint8_t diff;
11738 
11739 	entry = ctl_get_cmd_entry(ctsio, &sa);
11740 	ctsio->seridx = entry->seridx;
11741 	if (entry->execute == NULL) {
11742 		if (sa)
11743 			ctl_set_invalid_field(ctsio,
11744 					      /*sks_valid*/ 1,
11745 					      /*command*/ 1,
11746 					      /*field*/ 1,
11747 					      /*bit_valid*/ 1,
11748 					      /*bit*/ 4);
11749 		else
11750 			ctl_set_invalid_opcode(ctsio);
11751 		ctl_done((union ctl_io *)ctsio);
11752 		return (NULL);
11753 	}
11754 	KASSERT(entry->length > 0,
11755 	    ("Not defined length for command 0x%02x/0x%02x",
11756 	     ctsio->cdb[0], ctsio->cdb[1]));
11757 	for (i = 1; i < entry->length; i++) {
11758 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11759 		if (diff == 0)
11760 			continue;
11761 		ctl_set_invalid_field(ctsio,
11762 				      /*sks_valid*/ 1,
11763 				      /*command*/ 1,
11764 				      /*field*/ i,
11765 				      /*bit_valid*/ 1,
11766 				      /*bit*/ fls(diff) - 1);
11767 		ctl_done((union ctl_io *)ctsio);
11768 		return (NULL);
11769 	}
11770 	return (entry);
11771 }
11772 
11773 static int
11774 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11775 {
11776 
11777 	switch (lun_type) {
11778 	case T_DIRECT:
11779 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11780 			return (0);
11781 		break;
11782 	case T_PROCESSOR:
11783 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11784 			return (0);
11785 		break;
11786 	case T_CDROM:
11787 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11788 			return (0);
11789 		break;
11790 	default:
11791 		return (0);
11792 	}
11793 	return (1);
11794 }
11795 
11796 static int
11797 ctl_scsiio(struct ctl_scsiio *ctsio)
11798 {
11799 	int retval;
11800 	const struct ctl_cmd_entry *entry;
11801 
11802 	retval = CTL_RETVAL_COMPLETE;
11803 
11804 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11805 
11806 	entry = ctl_get_cmd_entry(ctsio, NULL);
11807 
11808 	/*
11809 	 * If this I/O has been aborted, just send it straight to
11810 	 * ctl_done() without executing it.
11811 	 */
11812 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11813 		ctl_done((union ctl_io *)ctsio);
11814 		goto bailout;
11815 	}
11816 
11817 	/*
11818 	 * All the checks should have been handled by ctl_scsiio_precheck().
11819 	 * We should be clear now to just execute the I/O.
11820 	 */
11821 	retval = entry->execute(ctsio);
11822 
11823 bailout:
11824 	return (retval);
11825 }
11826 
11827 static int
11828 ctl_target_reset(union ctl_io *io)
11829 {
11830 	struct ctl_softc *softc = CTL_SOFTC(io);
11831 	struct ctl_port *port = CTL_PORT(io);
11832 	struct ctl_lun *lun;
11833 	uint32_t initidx;
11834 	ctl_ua_type ua_type;
11835 
11836 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11837 		union ctl_ha_msg msg_info;
11838 
11839 		msg_info.hdr.nexus = io->io_hdr.nexus;
11840 		msg_info.task.task_action = io->taskio.task_action;
11841 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11842 		msg_info.hdr.original_sc = NULL;
11843 		msg_info.hdr.serializing_sc = NULL;
11844 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11845 		    sizeof(msg_info.task), M_WAITOK);
11846 	}
11847 
11848 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11849 	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11850 		ua_type = CTL_UA_TARG_RESET;
11851 	else
11852 		ua_type = CTL_UA_BUS_RESET;
11853 	mtx_lock(&softc->ctl_lock);
11854 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11855 		if (port != NULL &&
11856 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11857 			continue;
11858 		ctl_do_lun_reset(lun, initidx, ua_type);
11859 	}
11860 	mtx_unlock(&softc->ctl_lock);
11861 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11862 	return (0);
11863 }
11864 
11865 /*
11866  * The LUN should always be set.  The I/O is optional, and is used to
11867  * distinguish between I/Os sent by this initiator, and by other
11868  * initiators.  We set unit attention for initiators other than this one.
11869  * SAM-3 is vague on this point.  It does say that a unit attention should
11870  * be established for other initiators when a LUN is reset (see section
11871  * 5.7.3), but it doesn't specifically say that the unit attention should
11872  * be established for this particular initiator when a LUN is reset.  Here
11873  * is the relevant text, from SAM-3 rev 8:
11874  *
11875  * 5.7.2 When a SCSI initiator port aborts its own tasks
11876  *
11877  * When a SCSI initiator port causes its own task(s) to be aborted, no
11878  * notification that the task(s) have been aborted shall be returned to
11879  * the SCSI initiator port other than the completion response for the
11880  * command or task management function action that caused the task(s) to
11881  * be aborted and notification(s) associated with related effects of the
11882  * action (e.g., a reset unit attention condition).
11883  *
11884  * XXX KDM for now, we're setting unit attention for all initiators.
11885  */
11886 static void
11887 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11888 {
11889 	struct ctl_io_hdr *xioh;
11890 	int i;
11891 
11892 	mtx_lock(&lun->lun_lock);
11893 	/* Abort tasks. */
11894 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11895 		xioh->flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11896 		ctl_try_unblock_io(lun, (union ctl_io *)xioh, FALSE);
11897 	}
11898 	/* Clear CA. */
11899 	for (i = 0; i < ctl_max_ports; i++) {
11900 		free(lun->pending_sense[i], M_CTL);
11901 		lun->pending_sense[i] = NULL;
11902 	}
11903 	/* Clear reservation. */
11904 	lun->flags &= ~CTL_LUN_RESERVED;
11905 	/* Clear prevent media removal. */
11906 	if (lun->prevent) {
11907 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11908 			ctl_clear_mask(lun->prevent, i);
11909 		lun->prevent_count = 0;
11910 	}
11911 	/* Clear TPC status */
11912 	ctl_tpc_lun_clear(lun, -1);
11913 	/* Establish UA. */
11914 #if 0
11915 	ctl_est_ua_all(lun, initidx, ua_type);
11916 #else
11917 	ctl_est_ua_all(lun, -1, ua_type);
11918 #endif
11919 	mtx_unlock(&lun->lun_lock);
11920 }
11921 
11922 static int
11923 ctl_lun_reset(union ctl_io *io)
11924 {
11925 	struct ctl_softc *softc = CTL_SOFTC(io);
11926 	struct ctl_lun *lun;
11927 	uint32_t targ_lun, initidx;
11928 
11929 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11930 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11931 	mtx_lock(&softc->ctl_lock);
11932 	if (targ_lun >= ctl_max_luns ||
11933 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11934 		mtx_unlock(&softc->ctl_lock);
11935 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11936 		return (1);
11937 	}
11938 	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11939 	mtx_unlock(&softc->ctl_lock);
11940 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11941 
11942 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11943 		union ctl_ha_msg msg_info;
11944 
11945 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11946 		msg_info.hdr.nexus = io->io_hdr.nexus;
11947 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11948 		msg_info.hdr.original_sc = NULL;
11949 		msg_info.hdr.serializing_sc = NULL;
11950 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11951 		    sizeof(msg_info.task), M_WAITOK);
11952 	}
11953 	return (0);
11954 }
11955 
11956 static void
11957 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11958     int other_sc)
11959 {
11960 	struct ctl_io_hdr *xioh;
11961 
11962 	mtx_assert(&lun->lun_lock, MA_OWNED);
11963 
11964 	/*
11965 	 * Run through the OOA queue and attempt to find the given I/O.
11966 	 * The target port, initiator ID, tag type and tag number have to
11967 	 * match the values that we got from the initiator.  If we have an
11968 	 * untagged command to abort, simply abort the first untagged command
11969 	 * we come to.  We only allow one untagged command at a time of course.
11970 	 */
11971 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
11972 		union ctl_io *xio = (union ctl_io *)xioh;
11973 		if ((targ_port == UINT32_MAX ||
11974 		     targ_port == xioh->nexus.targ_port) &&
11975 		    (init_id == UINT32_MAX ||
11976 		     init_id == xioh->nexus.initid)) {
11977 			if (targ_port != xioh->nexus.targ_port ||
11978 			    init_id != xioh->nexus.initid)
11979 				xioh->flags |= CTL_FLAG_ABORT_STATUS;
11980 			xioh->flags |= CTL_FLAG_ABORT;
11981 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11982 				union ctl_ha_msg msg_info;
11983 
11984 				msg_info.hdr.nexus = xioh->nexus;
11985 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11986 				msg_info.task.tag_num = xio->scsiio.tag_num;
11987 				msg_info.task.tag_type = xio->scsiio.tag_type;
11988 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11989 				msg_info.hdr.original_sc = NULL;
11990 				msg_info.hdr.serializing_sc = NULL;
11991 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11992 				    sizeof(msg_info.task), M_NOWAIT);
11993 			}
11994 			ctl_try_unblock_io(lun, xio, FALSE);
11995 		}
11996 	}
11997 }
11998 
11999 static int
12000 ctl_abort_task_set(union ctl_io *io)
12001 {
12002 	struct ctl_softc *softc = CTL_SOFTC(io);
12003 	struct ctl_lun *lun;
12004 	uint32_t targ_lun;
12005 
12006 	/*
12007 	 * Look up the LUN.
12008 	 */
12009 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12010 	mtx_lock(&softc->ctl_lock);
12011 	if (targ_lun >= ctl_max_luns ||
12012 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12013 		mtx_unlock(&softc->ctl_lock);
12014 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12015 		return (1);
12016 	}
12017 
12018 	mtx_lock(&lun->lun_lock);
12019 	mtx_unlock(&softc->ctl_lock);
12020 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12021 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12022 		    io->io_hdr.nexus.initid,
12023 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12024 	} else { /* CTL_TASK_CLEAR_TASK_SET */
12025 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12026 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12027 	}
12028 	mtx_unlock(&lun->lun_lock);
12029 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12030 	return (0);
12031 }
12032 
12033 static void
12034 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
12035     ctl_ua_type ua_type)
12036 {
12037 	struct ctl_lun *lun;
12038 	struct scsi_sense_data *ps;
12039 	uint32_t p, i;
12040 
12041 	p = initidx / CTL_MAX_INIT_PER_PORT;
12042 	i = initidx % CTL_MAX_INIT_PER_PORT;
12043 	mtx_lock(&softc->ctl_lock);
12044 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12045 		mtx_lock(&lun->lun_lock);
12046 		/* Abort tasks. */
12047 		ctl_abort_tasks_lun(lun, p, i, 1);
12048 		/* Clear CA. */
12049 		ps = lun->pending_sense[p];
12050 		if (ps != NULL)
12051 			ps[i].error_code = 0;
12052 		/* Clear reservation. */
12053 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12054 			lun->flags &= ~CTL_LUN_RESERVED;
12055 		/* Clear prevent media removal. */
12056 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
12057 			ctl_clear_mask(lun->prevent, initidx);
12058 			lun->prevent_count--;
12059 		}
12060 		/* Clear TPC status */
12061 		ctl_tpc_lun_clear(lun, initidx);
12062 		/* Establish UA. */
12063 		ctl_est_ua(lun, initidx, ua_type);
12064 		mtx_unlock(&lun->lun_lock);
12065 	}
12066 	mtx_unlock(&softc->ctl_lock);
12067 }
12068 
12069 static int
12070 ctl_i_t_nexus_reset(union ctl_io *io)
12071 {
12072 	struct ctl_softc *softc = CTL_SOFTC(io);
12073 	uint32_t initidx;
12074 
12075 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12076 		union ctl_ha_msg msg_info;
12077 
12078 		msg_info.hdr.nexus = io->io_hdr.nexus;
12079 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12080 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12081 		msg_info.hdr.original_sc = NULL;
12082 		msg_info.hdr.serializing_sc = NULL;
12083 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12084 		    sizeof(msg_info.task), M_WAITOK);
12085 	}
12086 
12087 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12088 	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
12089 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12090 	return (0);
12091 }
12092 
12093 static int
12094 ctl_abort_task(union ctl_io *io)
12095 {
12096 	struct ctl_softc *softc = CTL_SOFTC(io);
12097 	struct ctl_io_hdr *xioh;
12098 	struct ctl_lun *lun;
12099 	uint32_t targ_lun;
12100 
12101 	/*
12102 	 * Look up the LUN.
12103 	 */
12104 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12105 	mtx_lock(&softc->ctl_lock);
12106 	if (targ_lun >= ctl_max_luns ||
12107 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12108 		mtx_unlock(&softc->ctl_lock);
12109 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12110 		return (1);
12111 	}
12112 
12113 	mtx_lock(&lun->lun_lock);
12114 	mtx_unlock(&softc->ctl_lock);
12115 	/*
12116 	 * Run through the OOA queue and attempt to find the given I/O.
12117 	 * The target port, initiator ID, tag type and tag number have to
12118 	 * match the values that we got from the initiator.  If we have an
12119 	 * untagged command to abort, simply abort the first untagged command
12120 	 * we come to.  We only allow one untagged command at a time of course.
12121 	 */
12122 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12123 		union ctl_io *xio = (union ctl_io *)xioh;
12124 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12125 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12126 		 || (xioh->flags & CTL_FLAG_ABORT))
12127 			continue;
12128 
12129 		/*
12130 		 * If the abort says that the task is untagged, the
12131 		 * task in the queue must be untagged.  Otherwise,
12132 		 * we just check to see whether the tag numbers
12133 		 * match.  This is because the QLogic firmware
12134 		 * doesn't pass back the tag type in an abort
12135 		 * request.
12136 		 */
12137 #if 0
12138 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12139 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12140 		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12141 #else
12142 		/*
12143 		 * XXX KDM we've got problems with FC, because it
12144 		 * doesn't send down a tag type with aborts.  So we
12145 		 * can only really go by the tag number...
12146 		 * This may cause problems with parallel SCSI.
12147 		 * Need to figure that out!!
12148 		 */
12149 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12150 #endif
12151 			xioh->flags |= CTL_FLAG_ABORT;
12152 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12153 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12154 				union ctl_ha_msg msg_info;
12155 
12156 				msg_info.hdr.nexus = io->io_hdr.nexus;
12157 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12158 				msg_info.task.tag_num = io->taskio.tag_num;
12159 				msg_info.task.tag_type = io->taskio.tag_type;
12160 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12161 				msg_info.hdr.original_sc = NULL;
12162 				msg_info.hdr.serializing_sc = NULL;
12163 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12164 				    sizeof(msg_info.task), M_NOWAIT);
12165 			}
12166 			ctl_try_unblock_io(lun, xio, FALSE);
12167 		}
12168 	}
12169 	mtx_unlock(&lun->lun_lock);
12170 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12171 	return (0);
12172 }
12173 
12174 static int
12175 ctl_query_task(union ctl_io *io, int task_set)
12176 {
12177 	struct ctl_softc *softc = CTL_SOFTC(io);
12178 	struct ctl_io_hdr *xioh;
12179 	struct ctl_lun *lun;
12180 	int found = 0;
12181 	uint32_t targ_lun;
12182 
12183 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12184 	mtx_lock(&softc->ctl_lock);
12185 	if (targ_lun >= ctl_max_luns ||
12186 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12187 		mtx_unlock(&softc->ctl_lock);
12188 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12189 		return (1);
12190 	}
12191 	mtx_lock(&lun->lun_lock);
12192 	mtx_unlock(&softc->ctl_lock);
12193 	LIST_FOREACH(xioh, &lun->ooa_queue, ooa_links) {
12194 		union ctl_io *xio = (union ctl_io *)xioh;
12195 		if ((xioh->nexus.targ_port != io->io_hdr.nexus.targ_port)
12196 		 || (xioh->nexus.initid != io->io_hdr.nexus.initid)
12197 		 || (xioh->flags & CTL_FLAG_ABORT))
12198 			continue;
12199 
12200 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12201 			found = 1;
12202 			break;
12203 		}
12204 	}
12205 	mtx_unlock(&lun->lun_lock);
12206 	if (found)
12207 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12208 	else
12209 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12210 	return (0);
12211 }
12212 
12213 static int
12214 ctl_query_async_event(union ctl_io *io)
12215 {
12216 	struct ctl_softc *softc = CTL_SOFTC(io);
12217 	struct ctl_lun *lun;
12218 	ctl_ua_type ua;
12219 	uint32_t targ_lun, initidx;
12220 
12221 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12222 	mtx_lock(&softc->ctl_lock);
12223 	if (targ_lun >= ctl_max_luns ||
12224 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12225 		mtx_unlock(&softc->ctl_lock);
12226 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12227 		return (1);
12228 	}
12229 	mtx_lock(&lun->lun_lock);
12230 	mtx_unlock(&softc->ctl_lock);
12231 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12232 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12233 	mtx_unlock(&lun->lun_lock);
12234 	if (ua != CTL_UA_NONE)
12235 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12236 	else
12237 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12238 	return (0);
12239 }
12240 
12241 static void
12242 ctl_run_task(union ctl_io *io)
12243 {
12244 	int retval = 1;
12245 
12246 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12247 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12248 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12249 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12250 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12251 	switch (io->taskio.task_action) {
12252 	case CTL_TASK_ABORT_TASK:
12253 		retval = ctl_abort_task(io);
12254 		break;
12255 	case CTL_TASK_ABORT_TASK_SET:
12256 	case CTL_TASK_CLEAR_TASK_SET:
12257 		retval = ctl_abort_task_set(io);
12258 		break;
12259 	case CTL_TASK_CLEAR_ACA:
12260 		break;
12261 	case CTL_TASK_I_T_NEXUS_RESET:
12262 		retval = ctl_i_t_nexus_reset(io);
12263 		break;
12264 	case CTL_TASK_LUN_RESET:
12265 		retval = ctl_lun_reset(io);
12266 		break;
12267 	case CTL_TASK_TARGET_RESET:
12268 	case CTL_TASK_BUS_RESET:
12269 		retval = ctl_target_reset(io);
12270 		break;
12271 	case CTL_TASK_PORT_LOGIN:
12272 		break;
12273 	case CTL_TASK_PORT_LOGOUT:
12274 		break;
12275 	case CTL_TASK_QUERY_TASK:
12276 		retval = ctl_query_task(io, 0);
12277 		break;
12278 	case CTL_TASK_QUERY_TASK_SET:
12279 		retval = ctl_query_task(io, 1);
12280 		break;
12281 	case CTL_TASK_QUERY_ASYNC_EVENT:
12282 		retval = ctl_query_async_event(io);
12283 		break;
12284 	default:
12285 		printf("%s: got unknown task management event %d\n",
12286 		       __func__, io->taskio.task_action);
12287 		break;
12288 	}
12289 	if (retval == 0)
12290 		io->io_hdr.status = CTL_SUCCESS;
12291 	else
12292 		io->io_hdr.status = CTL_ERROR;
12293 	ctl_done(io);
12294 }
12295 
12296 /*
12297  * For HA operation.  Handle commands that come in from the other
12298  * controller.
12299  */
12300 static void
12301 ctl_handle_isc(union ctl_io *io)
12302 {
12303 	struct ctl_softc *softc = CTL_SOFTC(io);
12304 	struct ctl_lun *lun;
12305 	const struct ctl_cmd_entry *entry;
12306 	uint32_t targ_lun;
12307 
12308 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12309 	switch (io->io_hdr.msg_type) {
12310 	case CTL_MSG_SERIALIZE:
12311 		ctl_serialize_other_sc_cmd(&io->scsiio);
12312 		break;
12313 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12314 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12315 		if (targ_lun >= ctl_max_luns ||
12316 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12317 			ctl_done(io);
12318 			break;
12319 		}
12320 		mtx_lock(&lun->lun_lock);
12321 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12322 			mtx_unlock(&lun->lun_lock);
12323 			ctl_done(io);
12324 			break;
12325 		}
12326 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12327 		mtx_unlock(&lun->lun_lock);
12328 		ctl_enqueue_rtr(io);
12329 		break;
12330 	case CTL_MSG_FINISH_IO:
12331 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12332 			ctl_done(io);
12333 			break;
12334 		}
12335 		if (targ_lun >= ctl_max_luns ||
12336 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12337 			ctl_free_io(io);
12338 			break;
12339 		}
12340 		mtx_lock(&lun->lun_lock);
12341 		ctl_try_unblock_others(lun, io, TRUE);
12342 		LIST_REMOVE(&io->io_hdr, ooa_links);
12343 		mtx_unlock(&lun->lun_lock);
12344 		ctl_free_io(io);
12345 		break;
12346 	case CTL_MSG_PERS_ACTION:
12347 		ctl_hndl_per_res_out_on_other_sc(io);
12348 		ctl_free_io(io);
12349 		break;
12350 	case CTL_MSG_BAD_JUJU:
12351 		ctl_done(io);
12352 		break;
12353 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12354 		ctl_datamove_remote(io);
12355 		break;
12356 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12357 		ctl_datamove_done(io, false);
12358 		break;
12359 	case CTL_MSG_FAILOVER:
12360 		ctl_failover_lun(io);
12361 		ctl_free_io(io);
12362 		break;
12363 	default:
12364 		printf("%s: Invalid message type %d\n",
12365 		       __func__, io->io_hdr.msg_type);
12366 		ctl_free_io(io);
12367 		break;
12368 	}
12369 
12370 }
12371 
12372 /*
12373  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12374  * there is no match.
12375  */
12376 static ctl_lun_error_pattern
12377 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12378 {
12379 	const struct ctl_cmd_entry *entry;
12380 	ctl_lun_error_pattern filtered_pattern, pattern;
12381 
12382 	pattern = desc->error_pattern;
12383 
12384 	/*
12385 	 * XXX KDM we need more data passed into this function to match a
12386 	 * custom pattern, and we actually need to implement custom pattern
12387 	 * matching.
12388 	 */
12389 	if (pattern & CTL_LUN_PAT_CMD)
12390 		return (CTL_LUN_PAT_CMD);
12391 
12392 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12393 		return (CTL_LUN_PAT_ANY);
12394 
12395 	entry = ctl_get_cmd_entry(ctsio, NULL);
12396 
12397 	filtered_pattern = entry->pattern & pattern;
12398 
12399 	/*
12400 	 * If the user requested specific flags in the pattern (e.g.
12401 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12402 	 * flags.
12403 	 *
12404 	 * If the user did not specify any flags, it doesn't matter whether
12405 	 * or not the command supports the flags.
12406 	 */
12407 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12408 	     (pattern & ~CTL_LUN_PAT_MASK))
12409 		return (CTL_LUN_PAT_NONE);
12410 
12411 	/*
12412 	 * If the user asked for a range check, see if the requested LBA
12413 	 * range overlaps with this command's LBA range.
12414 	 */
12415 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12416 		uint64_t lba1;
12417 		uint64_t len1;
12418 		ctl_action action;
12419 		int retval;
12420 
12421 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12422 		if (retval != 0)
12423 			return (CTL_LUN_PAT_NONE);
12424 
12425 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12426 					      desc->lba_range.len, FALSE);
12427 		/*
12428 		 * A "pass" means that the LBA ranges don't overlap, so
12429 		 * this doesn't match the user's range criteria.
12430 		 */
12431 		if (action == CTL_ACTION_PASS)
12432 			return (CTL_LUN_PAT_NONE);
12433 	}
12434 
12435 	return (filtered_pattern);
12436 }
12437 
12438 static void
12439 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12440 {
12441 	struct ctl_error_desc *desc, *desc2;
12442 
12443 	mtx_assert(&lun->lun_lock, MA_OWNED);
12444 
12445 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12446 		ctl_lun_error_pattern pattern;
12447 		/*
12448 		 * Check to see whether this particular command matches
12449 		 * the pattern in the descriptor.
12450 		 */
12451 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12452 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12453 			continue;
12454 
12455 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12456 		case CTL_LUN_INJ_ABORTED:
12457 			ctl_set_aborted(&io->scsiio);
12458 			break;
12459 		case CTL_LUN_INJ_MEDIUM_ERR:
12460 			ctl_set_medium_error(&io->scsiio,
12461 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12462 			     CTL_FLAG_DATA_OUT);
12463 			break;
12464 		case CTL_LUN_INJ_UA:
12465 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12466 			 * OCCURRED */
12467 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12468 			break;
12469 		case CTL_LUN_INJ_CUSTOM:
12470 			/*
12471 			 * We're assuming the user knows what he is doing.
12472 			 * Just copy the sense information without doing
12473 			 * checks.
12474 			 */
12475 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12476 			      MIN(sizeof(desc->custom_sense),
12477 				  sizeof(io->scsiio.sense_data)));
12478 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12479 			io->scsiio.sense_len = SSD_FULL_SIZE;
12480 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12481 			break;
12482 		case CTL_LUN_INJ_NONE:
12483 		default:
12484 			/*
12485 			 * If this is an error injection type we don't know
12486 			 * about, clear the continuous flag (if it is set)
12487 			 * so it will get deleted below.
12488 			 */
12489 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12490 			break;
12491 		}
12492 		/*
12493 		 * By default, each error injection action is a one-shot
12494 		 */
12495 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12496 			continue;
12497 
12498 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12499 
12500 		free(desc, M_CTL);
12501 	}
12502 }
12503 
12504 #ifdef CTL_IO_DELAY
12505 static void
12506 ctl_datamove_timer_wakeup(void *arg)
12507 {
12508 	union ctl_io *io;
12509 
12510 	io = (union ctl_io *)arg;
12511 
12512 	ctl_datamove(io);
12513 }
12514 #endif /* CTL_IO_DELAY */
12515 
12516 static void
12517 ctl_datamove_done_process(union ctl_io *io)
12518 {
12519 #ifdef CTL_TIME_IO
12520 	struct bintime cur_bt;
12521 #endif
12522 
12523 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
12524 	    ("%s: unexpected I/O type %x", __func__, io->io_hdr.io_type));
12525 
12526 #ifdef CTL_TIME_IO
12527 	getbinuptime(&cur_bt);
12528 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12529 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12530 #endif
12531 	io->io_hdr.num_dmas++;
12532 
12533 	if ((io->io_hdr.port_status != 0) &&
12534 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
12535 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
12536 		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
12537 		    /*retry_count*/ io->io_hdr.port_status);
12538 	} else if (io->scsiio.kern_data_resid != 0 &&
12539 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
12540 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
12541 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
12542 		ctl_set_invalid_field_ciu(&io->scsiio);
12543 	} else if (ctl_debug & CTL_DEBUG_CDB_DATA)
12544 		ctl_data_print(io);
12545 }
12546 
12547 void
12548 ctl_datamove_done(union ctl_io *io, bool samethr)
12549 {
12550 
12551 	ctl_datamove_done_process(io);
12552 	io->scsiio.be_move_done(io, samethr);
12553 }
12554 
12555 void
12556 ctl_datamove(union ctl_io *io)
12557 {
12558 	void (*fe_datamove)(union ctl_io *io);
12559 
12560 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12561 
12562 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12563 
12564 	/* No data transferred yet.  Frontend must update this when done. */
12565 	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12566 
12567 #ifdef CTL_TIME_IO
12568 	getbinuptime(&io->io_hdr.dma_start_bt);
12569 #endif /* CTL_TIME_IO */
12570 
12571 #ifdef CTL_IO_DELAY
12572 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12573 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12574 	} else {
12575 		struct ctl_lun *lun;
12576 
12577 		lun = CTL_LUN(io);
12578 		if ((lun != NULL)
12579 		 && (lun->delay_info.datamove_delay > 0)) {
12580 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12581 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12582 			callout_reset(&io->io_hdr.delay_callout,
12583 				      lun->delay_info.datamove_delay * hz,
12584 				      ctl_datamove_timer_wakeup, io);
12585 			if (lun->delay_info.datamove_type ==
12586 			    CTL_DELAY_TYPE_ONESHOT)
12587 				lun->delay_info.datamove_delay = 0;
12588 			return;
12589 		}
12590 	}
12591 #endif
12592 
12593 	/*
12594 	 * This command has been aborted.  Set the port status, so we fail
12595 	 * the data move.
12596 	 */
12597 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12598 		printf("ctl_datamove: tag 0x%jx on (%u:%u:%u) aborted\n",
12599 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12600 		       io->io_hdr.nexus.targ_port,
12601 		       io->io_hdr.nexus.targ_lun);
12602 		io->io_hdr.port_status = 31337;
12603 		ctl_datamove_done_process(io);
12604 		io->scsiio.be_move_done(io, true);
12605 		return;
12606 	}
12607 
12608 	/* Don't confuse frontend with zero length data move. */
12609 	if (io->scsiio.kern_data_len == 0) {
12610 		ctl_datamove_done_process(io);
12611 		io->scsiio.be_move_done(io, true);
12612 		return;
12613 	}
12614 
12615 	fe_datamove = CTL_PORT(io)->fe_datamove;
12616 	fe_datamove(io);
12617 }
12618 
12619 static void
12620 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12621 {
12622 	union ctl_ha_msg msg;
12623 #ifdef CTL_TIME_IO
12624 	struct bintime cur_bt;
12625 #endif
12626 
12627 	memset(&msg, 0, sizeof(msg));
12628 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12629 	msg.hdr.original_sc = io;
12630 	msg.hdr.serializing_sc = io->io_hdr.remote_io;
12631 	msg.hdr.nexus = io->io_hdr.nexus;
12632 	msg.hdr.status = io->io_hdr.status;
12633 	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12634 	msg.scsi.tag_num = io->scsiio.tag_num;
12635 	msg.scsi.tag_type = io->scsiio.tag_type;
12636 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12637 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12638 	       io->scsiio.sense_len);
12639 	msg.scsi.sense_len = io->scsiio.sense_len;
12640 	msg.scsi.port_status = io->io_hdr.port_status;
12641 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12642 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12643 		ctl_failover_io(io, /*have_lock*/ have_lock);
12644 		return;
12645 	}
12646 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12647 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12648 	    msg.scsi.sense_len, M_WAITOK);
12649 
12650 #ifdef CTL_TIME_IO
12651 	getbinuptime(&cur_bt);
12652 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12653 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12654 #endif
12655 	io->io_hdr.num_dmas++;
12656 }
12657 
12658 /*
12659  * The DMA to the remote side is done, now we need to tell the other side
12660  * we're done so it can continue with its data movement.
12661  */
12662 static void
12663 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12664 {
12665 	union ctl_io *io;
12666 	uint32_t i;
12667 
12668 	io = rq->context;
12669 
12670 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12671 		printf("%s: ISC DMA write failed with error %d", __func__,
12672 		       rq->ret);
12673 		ctl_set_internal_failure(&io->scsiio,
12674 					 /*sks_valid*/ 1,
12675 					 /*retry_count*/ rq->ret);
12676 	}
12677 
12678 	ctl_dt_req_free(rq);
12679 
12680 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12681 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12682 	free(CTL_RSGL(io), M_CTL);
12683 	CTL_RSGL(io) = NULL;
12684 	CTL_LSGL(io) = NULL;
12685 
12686 	/*
12687 	 * The data is in local and remote memory, so now we need to send
12688 	 * status (good or back) back to the other side.
12689 	 */
12690 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12691 }
12692 
12693 /*
12694  * We've moved the data from the host/controller into local memory.  Now we
12695  * need to push it over to the remote controller's memory.
12696  */
12697 static int
12698 ctl_datamove_remote_dm_write_cb(union ctl_io *io, bool samethr)
12699 {
12700 	int retval;
12701 
12702 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12703 					  ctl_datamove_remote_write_cb);
12704 	return (retval);
12705 }
12706 
12707 static void
12708 ctl_datamove_remote_write(union ctl_io *io)
12709 {
12710 	int retval;
12711 	void (*fe_datamove)(union ctl_io *io);
12712 
12713 	/*
12714 	 * - Get the data from the host/HBA into local memory.
12715 	 * - DMA memory from the local controller to the remote controller.
12716 	 * - Send status back to the remote controller.
12717 	 */
12718 
12719 	retval = ctl_datamove_remote_sgl_setup(io);
12720 	if (retval != 0)
12721 		return;
12722 
12723 	/* Switch the pointer over so the FETD knows what to do */
12724 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12725 
12726 	/*
12727 	 * Use a custom move done callback, since we need to send completion
12728 	 * back to the other controller, not to the backend on this side.
12729 	 */
12730 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12731 
12732 	fe_datamove = CTL_PORT(io)->fe_datamove;
12733 	fe_datamove(io);
12734 }
12735 
12736 static int
12737 ctl_datamove_remote_dm_read_cb(union ctl_io *io, bool samethr)
12738 {
12739 	uint32_t i;
12740 
12741 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12742 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12743 	free(CTL_RSGL(io), M_CTL);
12744 	CTL_RSGL(io) = NULL;
12745 	CTL_LSGL(io) = NULL;
12746 
12747 	/*
12748 	 * The read is done, now we need to send status (good or bad) back
12749 	 * to the other side.
12750 	 */
12751 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12752 
12753 	return (0);
12754 }
12755 
12756 static void
12757 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12758 {
12759 	union ctl_io *io;
12760 	void (*fe_datamove)(union ctl_io *io);
12761 
12762 	io = rq->context;
12763 
12764 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12765 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12766 		       rq->ret);
12767 		ctl_set_internal_failure(&io->scsiio,
12768 					 /*sks_valid*/ 1,
12769 					 /*retry_count*/ rq->ret);
12770 	}
12771 
12772 	ctl_dt_req_free(rq);
12773 
12774 	/* Switch the pointer over so the FETD knows what to do */
12775 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12776 
12777 	/*
12778 	 * Use a custom move done callback, since we need to send completion
12779 	 * back to the other controller, not to the backend on this side.
12780 	 */
12781 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12782 
12783 	/* XXX KDM add checks like the ones in ctl_datamove? */
12784 
12785 	fe_datamove = CTL_PORT(io)->fe_datamove;
12786 	fe_datamove(io);
12787 }
12788 
12789 static int
12790 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12791 {
12792 	struct ctl_sg_entry *local_sglist;
12793 	uint32_t len_to_go;
12794 	int retval;
12795 	int i;
12796 
12797 	retval = 0;
12798 	local_sglist = CTL_LSGL(io);
12799 	len_to_go = io->scsiio.kern_data_len;
12800 
12801 	/*
12802 	 * The difficult thing here is that the size of the various
12803 	 * S/G segments may be different than the size from the
12804 	 * remote controller.  That'll make it harder when DMAing
12805 	 * the data back to the other side.
12806 	 */
12807 	for (i = 0; len_to_go > 0; i++) {
12808 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12809 		local_sglist[i].addr =
12810 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12811 
12812 		len_to_go -= local_sglist[i].len;
12813 	}
12814 	/*
12815 	 * Reset the number of S/G entries accordingly.  The original
12816 	 * number of S/G entries is available in rem_sg_entries.
12817 	 */
12818 	io->scsiio.kern_sg_entries = i;
12819 
12820 	return (retval);
12821 }
12822 
12823 static int
12824 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12825 			 ctl_ha_dt_cb callback)
12826 {
12827 	struct ctl_ha_dt_req *rq;
12828 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12829 	uint32_t local_used, remote_used, total_used;
12830 	int i, j, isc_ret;
12831 
12832 	rq = ctl_dt_req_alloc();
12833 
12834 	/*
12835 	 * If we failed to allocate the request, and if the DMA didn't fail
12836 	 * anyway, set busy status.  This is just a resource allocation
12837 	 * failure.
12838 	 */
12839 	if ((rq == NULL)
12840 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12841 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12842 		ctl_set_busy(&io->scsiio);
12843 
12844 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12845 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12846 		if (rq != NULL)
12847 			ctl_dt_req_free(rq);
12848 
12849 		/*
12850 		 * The data move failed.  We need to return status back
12851 		 * to the other controller.  No point in trying to DMA
12852 		 * data to the remote controller.
12853 		 */
12854 
12855 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12856 
12857 		return (1);
12858 	}
12859 
12860 	local_sglist = CTL_LSGL(io);
12861 	remote_sglist = CTL_RSGL(io);
12862 	local_used = 0;
12863 	remote_used = 0;
12864 	total_used = 0;
12865 
12866 	/*
12867 	 * Pull/push the data over the wire from/to the other controller.
12868 	 * This takes into account the possibility that the local and
12869 	 * remote sglists may not be identical in terms of the size of
12870 	 * the elements and the number of elements.
12871 	 *
12872 	 * One fundamental assumption here is that the length allocated for
12873 	 * both the local and remote sglists is identical.  Otherwise, we've
12874 	 * essentially got a coding error of some sort.
12875 	 */
12876 	isc_ret = CTL_HA_STATUS_SUCCESS;
12877 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12878 		uint32_t cur_len;
12879 		uint8_t *tmp_ptr;
12880 
12881 		rq->command = command;
12882 		rq->context = io;
12883 
12884 		/*
12885 		 * Both pointers should be aligned.  But it is possible
12886 		 * that the allocation length is not.  They should both
12887 		 * also have enough slack left over at the end, though,
12888 		 * to round up to the next 8 byte boundary.
12889 		 */
12890 		cur_len = MIN(local_sglist[i].len - local_used,
12891 			      remote_sglist[j].len - remote_used);
12892 		rq->size = cur_len;
12893 
12894 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12895 		tmp_ptr += local_used;
12896 
12897 #if 0
12898 		/* Use physical addresses when talking to ISC hardware */
12899 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12900 			/* XXX KDM use busdma */
12901 			rq->local = vtophys(tmp_ptr);
12902 		} else
12903 			rq->local = tmp_ptr;
12904 #else
12905 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12906 		    ("HA does not support BUS_ADDR"));
12907 		rq->local = tmp_ptr;
12908 #endif
12909 
12910 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12911 		tmp_ptr += remote_used;
12912 		rq->remote = tmp_ptr;
12913 
12914 		rq->callback = NULL;
12915 
12916 		local_used += cur_len;
12917 		if (local_used >= local_sglist[i].len) {
12918 			i++;
12919 			local_used = 0;
12920 		}
12921 
12922 		remote_used += cur_len;
12923 		if (remote_used >= remote_sglist[j].len) {
12924 			j++;
12925 			remote_used = 0;
12926 		}
12927 		total_used += cur_len;
12928 
12929 		if (total_used >= io->scsiio.kern_data_len)
12930 			rq->callback = callback;
12931 
12932 		isc_ret = ctl_dt_single(rq);
12933 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12934 			break;
12935 	}
12936 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12937 		rq->ret = isc_ret;
12938 		callback(rq);
12939 	}
12940 
12941 	return (0);
12942 }
12943 
12944 static void
12945 ctl_datamove_remote_read(union ctl_io *io)
12946 {
12947 	int retval;
12948 	uint32_t i;
12949 
12950 	/*
12951 	 * This will send an error to the other controller in the case of a
12952 	 * failure.
12953 	 */
12954 	retval = ctl_datamove_remote_sgl_setup(io);
12955 	if (retval != 0)
12956 		return;
12957 
12958 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12959 					  ctl_datamove_remote_read_cb);
12960 	if (retval != 0) {
12961 		/*
12962 		 * Make sure we free memory if there was an error..  The
12963 		 * ctl_datamove_remote_xfer() function will send the
12964 		 * datamove done message, or call the callback with an
12965 		 * error if there is a problem.
12966 		 */
12967 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12968 			free(CTL_LSGLT(io)[i].addr, M_CTL);
12969 		free(CTL_RSGL(io), M_CTL);
12970 		CTL_RSGL(io) = NULL;
12971 		CTL_LSGL(io) = NULL;
12972 	}
12973 }
12974 
12975 /*
12976  * Process a datamove request from the other controller.  This is used for
12977  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12978  * first.  Once that is complete, the data gets DMAed into the remote
12979  * controller's memory.  For reads, we DMA from the remote controller's
12980  * memory into our memory first, and then move it out to the FETD.
12981  */
12982 static void
12983 ctl_datamove_remote(union ctl_io *io)
12984 {
12985 
12986 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12987 
12988 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12989 		ctl_failover_io(io, /*have_lock*/ 0);
12990 		return;
12991 	}
12992 
12993 	/*
12994 	 * Note that we look for an aborted I/O here, but don't do some of
12995 	 * the other checks that ctl_datamove() normally does.
12996 	 * We don't need to run the datamove delay code, since that should
12997 	 * have been done if need be on the other controller.
12998 	 */
12999 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13000 		printf("%s: tag 0x%jx on (%u:%u:%u) aborted\n", __func__,
13001 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13002 		       io->io_hdr.nexus.targ_port,
13003 		       io->io_hdr.nexus.targ_lun);
13004 		io->io_hdr.port_status = 31338;
13005 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13006 		return;
13007 	}
13008 
13009 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13010 		ctl_datamove_remote_write(io);
13011 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13012 		ctl_datamove_remote_read(io);
13013 	else {
13014 		io->io_hdr.port_status = 31339;
13015 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13016 	}
13017 }
13018 
13019 static void
13020 ctl_process_done(union ctl_io *io)
13021 {
13022 	struct ctl_softc *softc = CTL_SOFTC(io);
13023 	struct ctl_port *port = CTL_PORT(io);
13024 	struct ctl_lun *lun = CTL_LUN(io);
13025 	void (*fe_done)(union ctl_io *io);
13026 	union ctl_ha_msg msg;
13027 
13028 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13029 	fe_done = port->fe_done;
13030 
13031 #ifdef CTL_TIME_IO
13032 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13033 		char str[256];
13034 		char path_str[64];
13035 		struct sbuf sb;
13036 
13037 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13038 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13039 
13040 		sbuf_cat(&sb, path_str);
13041 		switch (io->io_hdr.io_type) {
13042 		case CTL_IO_SCSI:
13043 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13044 			sbuf_printf(&sb, "\n");
13045 			sbuf_cat(&sb, path_str);
13046 			sbuf_printf(&sb, "Tag: 0x%jx/%d, Prio: %d\n",
13047 				    io->scsiio.tag_num, io->scsiio.tag_type,
13048 				    io->scsiio.priority);
13049 			break;
13050 		case CTL_IO_TASK:
13051 			sbuf_printf(&sb, "Task Action: %d Tag: 0x%jx/%d\n",
13052 				    io->taskio.task_action,
13053 				    io->taskio.tag_num, io->taskio.tag_type);
13054 			break;
13055 		default:
13056 			panic("%s: Invalid CTL I/O type %d\n",
13057 			    __func__, io->io_hdr.io_type);
13058 		}
13059 		sbuf_cat(&sb, path_str);
13060 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13061 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13062 		sbuf_finish(&sb);
13063 		printf("%s", sbuf_data(&sb));
13064 	}
13065 #endif /* CTL_TIME_IO */
13066 
13067 	switch (io->io_hdr.io_type) {
13068 	case CTL_IO_SCSI:
13069 		break;
13070 	case CTL_IO_TASK:
13071 		if (ctl_debug & CTL_DEBUG_INFO)
13072 			ctl_io_error_print(io, NULL);
13073 		fe_done(io);
13074 		return;
13075 	default:
13076 		panic("%s: Invalid CTL I/O type %d\n",
13077 		    __func__, io->io_hdr.io_type);
13078 	}
13079 
13080 	if (lun == NULL) {
13081 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13082 				 io->io_hdr.nexus.targ_mapped_lun));
13083 		goto bailout;
13084 	}
13085 
13086 	mtx_lock(&lun->lun_lock);
13087 
13088 	/*
13089 	 * Check to see if we have any informational exception and status
13090 	 * of this command can be modified to report it in form of either
13091 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13092 	 */
13093 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13094 	    io->io_hdr.status == CTL_SUCCESS &&
13095 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13096 		uint8_t mrie = lun->MODE_IE.mrie;
13097 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13098 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13099 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13100 		     mrie == SIEP_MRIE_REC_UNCOND ||
13101 		     mrie == SIEP_MRIE_NO_SENSE) &&
13102 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13103 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13104 			ctl_set_sense(&io->scsiio,
13105 			      /*current_error*/ 1,
13106 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13107 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13108 			      /*asc*/ lun->ie_asc,
13109 			      /*ascq*/ lun->ie_ascq,
13110 			      SSD_ELEM_NONE);
13111 			lun->ie_reported = 1;
13112 		}
13113 	} else if (lun->ie_reported < 0)
13114 		lun->ie_reported = 0;
13115 
13116 	/*
13117 	 * Check to see if we have any errors to inject here.  We only
13118 	 * inject errors for commands that don't already have errors set.
13119 	 */
13120 	if (!STAILQ_EMPTY(&lun->error_list) &&
13121 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13122 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13123 		ctl_inject_error(lun, io);
13124 
13125 	/*
13126 	 * XXX KDM how do we treat commands that aren't completed
13127 	 * successfully?
13128 	 *
13129 	 * XXX KDM should we also track I/O latency?
13130 	 */
13131 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13132 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13133 		int type;
13134 #ifdef CTL_TIME_IO
13135 		struct bintime bt;
13136 
13137 		getbinuptime(&bt);
13138 		bintime_sub(&bt, &io->io_hdr.start_bt);
13139 #endif
13140 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13141 		    CTL_FLAG_DATA_IN)
13142 			type = CTL_STATS_READ;
13143 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13144 		    CTL_FLAG_DATA_OUT)
13145 			type = CTL_STATS_WRITE;
13146 		else
13147 			type = CTL_STATS_NO_IO;
13148 
13149 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
13150 		lun->stats.operations[type] ++;
13151 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13152 #ifdef CTL_TIME_IO
13153 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13154 		bintime_add(&lun->stats.time[type], &bt);
13155 #endif
13156 
13157 		mtx_lock(&port->port_lock);
13158 		port->stats.bytes[type] += io->scsiio.kern_total_len;
13159 		port->stats.operations[type] ++;
13160 		port->stats.dmas[type] += io->io_hdr.num_dmas;
13161 #ifdef CTL_TIME_IO
13162 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13163 		bintime_add(&port->stats.time[type], &bt);
13164 #endif
13165 		mtx_unlock(&port->port_lock);
13166 	}
13167 
13168 	/*
13169 	 * Run through the blocked queue of this I/O and see if anything
13170 	 * can be unblocked, now that this I/O is done and will be removed.
13171 	 * We need to do it before removal to have OOA position to start.
13172 	 */
13173 	ctl_try_unblock_others(lun, io, TRUE);
13174 
13175 	/*
13176 	 * Remove this from the OOA queue.
13177 	 */
13178 	LIST_REMOVE(&io->io_hdr, ooa_links);
13179 #ifdef CTL_TIME_IO
13180 	if (LIST_EMPTY(&lun->ooa_queue))
13181 		lun->last_busy = getsbinuptime();
13182 #endif
13183 
13184 	/*
13185 	 * If the LUN has been invalidated, free it if there is nothing
13186 	 * left on its OOA queue.
13187 	 */
13188 	if ((lun->flags & CTL_LUN_INVALID)
13189 	 && LIST_EMPTY(&lun->ooa_queue)) {
13190 		mtx_unlock(&lun->lun_lock);
13191 		ctl_free_lun(lun);
13192 	} else
13193 		mtx_unlock(&lun->lun_lock);
13194 
13195 bailout:
13196 
13197 	/*
13198 	 * If this command has been aborted, make sure we set the status
13199 	 * properly.  The FETD is responsible for freeing the I/O and doing
13200 	 * whatever it needs to do to clean up its state.
13201 	 */
13202 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13203 		ctl_set_task_aborted(&io->scsiio);
13204 
13205 	/*
13206 	 * If enabled, print command error status.
13207 	 */
13208 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13209 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13210 		ctl_io_error_print(io, NULL);
13211 
13212 	/*
13213 	 * Tell the FETD or the other shelf controller we're done with this
13214 	 * command.  Note that only SCSI commands get to this point.  Task
13215 	 * management commands are completed above.
13216 	 */
13217 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13218 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13219 		memset(&msg, 0, sizeof(msg));
13220 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13221 		msg.hdr.serializing_sc = io->io_hdr.remote_io;
13222 		msg.hdr.nexus = io->io_hdr.nexus;
13223 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13224 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13225 		    M_WAITOK);
13226 	}
13227 
13228 	fe_done(io);
13229 }
13230 
13231 /*
13232  * Front end should call this if it doesn't do autosense.  When the request
13233  * sense comes back in from the initiator, we'll dequeue this and send it.
13234  */
13235 int
13236 ctl_queue_sense(union ctl_io *io)
13237 {
13238 	struct ctl_softc *softc = CTL_SOFTC(io);
13239 	struct ctl_port *port = CTL_PORT(io);
13240 	struct ctl_lun *lun;
13241 	struct scsi_sense_data *ps;
13242 	uint32_t initidx, p, targ_lun;
13243 
13244 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13245 
13246 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13247 
13248 	/*
13249 	 * LUN lookup will likely move to the ctl_work_thread() once we
13250 	 * have our new queueing infrastructure (that doesn't put things on
13251 	 * a per-LUN queue initially).  That is so that we can handle
13252 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13253 	 * can't deal with that right now.
13254 	 * If we don't have a LUN for this, just toss the sense information.
13255 	 */
13256 	mtx_lock(&softc->ctl_lock);
13257 	if (targ_lun >= ctl_max_luns ||
13258 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13259 		mtx_unlock(&softc->ctl_lock);
13260 		goto bailout;
13261 	}
13262 	mtx_lock(&lun->lun_lock);
13263 	mtx_unlock(&softc->ctl_lock);
13264 
13265 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13266 	p = initidx / CTL_MAX_INIT_PER_PORT;
13267 	if (lun->pending_sense[p] == NULL) {
13268 		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13269 		    M_CTL, M_NOWAIT | M_ZERO);
13270 	}
13271 	if ((ps = lun->pending_sense[p]) != NULL) {
13272 		ps += initidx % CTL_MAX_INIT_PER_PORT;
13273 		memset(ps, 0, sizeof(*ps));
13274 		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13275 	}
13276 	mtx_unlock(&lun->lun_lock);
13277 
13278 bailout:
13279 	ctl_free_io(io);
13280 	return (CTL_RETVAL_COMPLETE);
13281 }
13282 
13283 /*
13284  * Primary command inlet from frontend ports.  All SCSI and task I/O
13285  * requests must go through this function.
13286  */
13287 int
13288 ctl_queue(union ctl_io *io)
13289 {
13290 	struct ctl_port *port = CTL_PORT(io);
13291 
13292 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13293 
13294 #ifdef CTL_TIME_IO
13295 	io->io_hdr.start_time = time_uptime;
13296 	getbinuptime(&io->io_hdr.start_bt);
13297 #endif /* CTL_TIME_IO */
13298 
13299 	/* Map FE-specific LUN ID into global one. */
13300 	io->io_hdr.nexus.targ_mapped_lun =
13301 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13302 
13303 	switch (io->io_hdr.io_type) {
13304 	case CTL_IO_SCSI:
13305 	case CTL_IO_TASK:
13306 		if (ctl_debug & CTL_DEBUG_CDB)
13307 			ctl_io_print(io);
13308 		ctl_enqueue_incoming(io);
13309 		break;
13310 	default:
13311 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13312 		return (EINVAL);
13313 	}
13314 
13315 	return (CTL_RETVAL_COMPLETE);
13316 }
13317 
13318 int
13319 ctl_run(union ctl_io *io)
13320 {
13321 	struct ctl_port *port = CTL_PORT(io);
13322 
13323 	CTL_DEBUG_PRINT(("ctl_run cdb[0]=%02X\n", io->scsiio.cdb[0]));
13324 
13325 #ifdef CTL_TIME_IO
13326 	io->io_hdr.start_time = time_uptime;
13327 	getbinuptime(&io->io_hdr.start_bt);
13328 #endif /* CTL_TIME_IO */
13329 
13330 	/* Map FE-specific LUN ID into global one. */
13331 	io->io_hdr.nexus.targ_mapped_lun =
13332 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13333 
13334 	switch (io->io_hdr.io_type) {
13335 	case CTL_IO_SCSI:
13336 		if (ctl_debug & CTL_DEBUG_CDB)
13337 			ctl_io_print(io);
13338 		ctl_scsiio_precheck(&io->scsiio);
13339 		break;
13340 	case CTL_IO_TASK:
13341 		if (ctl_debug & CTL_DEBUG_CDB)
13342 			ctl_io_print(io);
13343 		ctl_run_task(io);
13344 		break;
13345 	default:
13346 		printf("ctl_run: unknown I/O type %d\n", io->io_hdr.io_type);
13347 		return (EINVAL);
13348 	}
13349 
13350 	return (CTL_RETVAL_COMPLETE);
13351 }
13352 
13353 #ifdef CTL_IO_DELAY
13354 static void
13355 ctl_done_timer_wakeup(void *arg)
13356 {
13357 	union ctl_io *io;
13358 
13359 	io = (union ctl_io *)arg;
13360 	ctl_done(io);
13361 }
13362 #endif /* CTL_IO_DELAY */
13363 
13364 void
13365 ctl_serseq_done(union ctl_io *io)
13366 {
13367 	struct ctl_lun *lun = CTL_LUN(io);
13368 
13369 	/* This is racy, but should not be a problem. */
13370 	if (!TAILQ_EMPTY(&io->io_hdr.blocked_queue)) {
13371 		mtx_lock(&lun->lun_lock);
13372 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13373 		ctl_try_unblock_others(lun, io, FALSE);
13374 		mtx_unlock(&lun->lun_lock);
13375 	} else
13376 		io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13377 }
13378 
13379 void
13380 ctl_done(union ctl_io *io)
13381 {
13382 
13383 	/*
13384 	 * Enable this to catch duplicate completion issues.
13385 	 */
13386 #if 0
13387 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13388 		printf("%s: type %d msg %d cdb %x iptl: "
13389 		       "%u:%u:%u tag 0x%04x "
13390 		       "flag %#x status %x\n",
13391 			__func__,
13392 			io->io_hdr.io_type,
13393 			io->io_hdr.msg_type,
13394 			io->scsiio.cdb[0],
13395 			io->io_hdr.nexus.initid,
13396 			io->io_hdr.nexus.targ_port,
13397 			io->io_hdr.nexus.targ_lun,
13398 			(io->io_hdr.io_type ==
13399 			CTL_IO_TASK) ?
13400 			io->taskio.tag_num :
13401 			io->scsiio.tag_num,
13402 		        io->io_hdr.flags,
13403 			io->io_hdr.status);
13404 	} else
13405 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13406 #endif
13407 
13408 	/*
13409 	 * This is an internal copy of an I/O, and should not go through
13410 	 * the normal done processing logic.
13411 	 */
13412 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13413 		return;
13414 
13415 #ifdef CTL_IO_DELAY
13416 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13417 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13418 	} else {
13419 		struct ctl_lun *lun = CTL_LUN(io);
13420 
13421 		if ((lun != NULL)
13422 		 && (lun->delay_info.done_delay > 0)) {
13423 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13424 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13425 			callout_reset(&io->io_hdr.delay_callout,
13426 				      lun->delay_info.done_delay * hz,
13427 				      ctl_done_timer_wakeup, io);
13428 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13429 				lun->delay_info.done_delay = 0;
13430 			return;
13431 		}
13432 	}
13433 #endif /* CTL_IO_DELAY */
13434 
13435 	ctl_enqueue_done(io);
13436 }
13437 
13438 static void
13439 ctl_work_thread(void *arg)
13440 {
13441 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13442 	struct ctl_softc *softc = thr->ctl_softc;
13443 	union ctl_io *io;
13444 	int retval;
13445 
13446 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13447 	thread_lock(curthread);
13448 	sched_prio(curthread, PUSER - 1);
13449 	thread_unlock(curthread);
13450 
13451 	while (!softc->shutdown) {
13452 		/*
13453 		 * We handle the queues in this order:
13454 		 * - ISC
13455 		 * - done queue (to free up resources, unblock other commands)
13456 		 * - incoming queue
13457 		 * - RtR queue
13458 		 *
13459 		 * If those queues are empty, we break out of the loop and
13460 		 * go to sleep.
13461 		 */
13462 		mtx_lock(&thr->queue_lock);
13463 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13464 		if (io != NULL) {
13465 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13466 			mtx_unlock(&thr->queue_lock);
13467 			ctl_handle_isc(io);
13468 			continue;
13469 		}
13470 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13471 		if (io != NULL) {
13472 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13473 			/* clear any blocked commands, call fe_done */
13474 			mtx_unlock(&thr->queue_lock);
13475 			ctl_process_done(io);
13476 			continue;
13477 		}
13478 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13479 		if (io != NULL) {
13480 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13481 			mtx_unlock(&thr->queue_lock);
13482 			if (io->io_hdr.io_type == CTL_IO_TASK)
13483 				ctl_run_task(io);
13484 			else
13485 				ctl_scsiio_precheck(&io->scsiio);
13486 			continue;
13487 		}
13488 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13489 		if (io != NULL) {
13490 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13491 			mtx_unlock(&thr->queue_lock);
13492 			retval = ctl_scsiio(&io->scsiio);
13493 			if (retval != CTL_RETVAL_COMPLETE)
13494 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13495 			continue;
13496 		}
13497 
13498 		/* Sleep until we have something to do. */
13499 		mtx_sleep(thr, &thr->queue_lock, PDROP, "-", 0);
13500 	}
13501 	thr->thread = NULL;
13502 	kthread_exit();
13503 }
13504 
13505 static void
13506 ctl_thresh_thread(void *arg)
13507 {
13508 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13509 	struct ctl_lun *lun;
13510 	struct ctl_logical_block_provisioning_page *page;
13511 	const char *attr;
13512 	union ctl_ha_msg msg;
13513 	uint64_t thres, val;
13514 	int i, e, set;
13515 
13516 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13517 	thread_lock(curthread);
13518 	sched_prio(curthread, PUSER - 1);
13519 	thread_unlock(curthread);
13520 
13521 	while (!softc->shutdown) {
13522 		mtx_lock(&softc->ctl_lock);
13523 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13524 			if ((lun->flags & CTL_LUN_DISABLED) ||
13525 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13526 			    lun->backend->lun_attr == NULL)
13527 				continue;
13528 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13529 			    softc->ha_mode == CTL_HA_MODE_XFER)
13530 				continue;
13531 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13532 				continue;
13533 			e = 0;
13534 			page = &lun->MODE_LBP;
13535 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13536 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13537 					continue;
13538 				thres = scsi_4btoul(page->descr[i].count);
13539 				thres <<= CTL_LBP_EXPONENT;
13540 				switch (page->descr[i].resource) {
13541 				case 0x01:
13542 					attr = "blocksavail";
13543 					break;
13544 				case 0x02:
13545 					attr = "blocksused";
13546 					break;
13547 				case 0xf1:
13548 					attr = "poolblocksavail";
13549 					break;
13550 				case 0xf2:
13551 					attr = "poolblocksused";
13552 					break;
13553 				default:
13554 					continue;
13555 				}
13556 				mtx_unlock(&softc->ctl_lock); // XXX
13557 				val = lun->backend->lun_attr(lun->be_lun, attr);
13558 				mtx_lock(&softc->ctl_lock);
13559 				if (val == UINT64_MAX)
13560 					continue;
13561 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13562 				    == SLBPPD_ARMING_INC)
13563 					e = (val >= thres);
13564 				else
13565 					e = (val <= thres);
13566 				if (e)
13567 					break;
13568 			}
13569 			mtx_lock(&lun->lun_lock);
13570 			if (e) {
13571 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13572 				    (uint8_t *)page, lun->ua_tpt_info);
13573 				if (lun->lasttpt == 0 ||
13574 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13575 					lun->lasttpt = time_uptime;
13576 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13577 					set = 1;
13578 				} else
13579 					set = 0;
13580 			} else {
13581 				lun->lasttpt = 0;
13582 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13583 				set = -1;
13584 			}
13585 			mtx_unlock(&lun->lun_lock);
13586 			if (set != 0 &&
13587 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13588 				/* Send msg to other side. */
13589 				bzero(&msg.ua, sizeof(msg.ua));
13590 				msg.hdr.msg_type = CTL_MSG_UA;
13591 				msg.hdr.nexus.initid = -1;
13592 				msg.hdr.nexus.targ_port = -1;
13593 				msg.hdr.nexus.targ_lun = lun->lun;
13594 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13595 				msg.ua.ua_all = 1;
13596 				msg.ua.ua_set = (set > 0);
13597 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13598 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13599 				mtx_unlock(&softc->ctl_lock); // XXX
13600 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13601 				    sizeof(msg.ua), M_WAITOK);
13602 				mtx_lock(&softc->ctl_lock);
13603 			}
13604 		}
13605 		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13606 		    PDROP, "-", CTL_LBP_PERIOD * hz);
13607 	}
13608 	softc->thresh_thread = NULL;
13609 	kthread_exit();
13610 }
13611 
13612 static void
13613 ctl_enqueue_incoming(union ctl_io *io)
13614 {
13615 	struct ctl_softc *softc = CTL_SOFTC(io);
13616 	struct ctl_thread *thr;
13617 	u_int idx;
13618 
13619 	idx = (io->io_hdr.nexus.targ_port * 127 +
13620 	       io->io_hdr.nexus.initid) % worker_threads;
13621 	thr = &softc->threads[idx];
13622 	mtx_lock(&thr->queue_lock);
13623 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13624 	mtx_unlock(&thr->queue_lock);
13625 	wakeup(thr);
13626 }
13627 
13628 static void
13629 ctl_enqueue_rtr(union ctl_io *io)
13630 {
13631 	struct ctl_softc *softc = CTL_SOFTC(io);
13632 	struct ctl_thread *thr;
13633 
13634 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13635 	mtx_lock(&thr->queue_lock);
13636 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13637 	mtx_unlock(&thr->queue_lock);
13638 	wakeup(thr);
13639 }
13640 
13641 static void
13642 ctl_enqueue_done(union ctl_io *io)
13643 {
13644 	struct ctl_softc *softc = CTL_SOFTC(io);
13645 	struct ctl_thread *thr;
13646 
13647 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13648 	mtx_lock(&thr->queue_lock);
13649 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13650 	mtx_unlock(&thr->queue_lock);
13651 	wakeup(thr);
13652 }
13653 
13654 static void
13655 ctl_enqueue_isc(union ctl_io *io)
13656 {
13657 	struct ctl_softc *softc = CTL_SOFTC(io);
13658 	struct ctl_thread *thr;
13659 
13660 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13661 	mtx_lock(&thr->queue_lock);
13662 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13663 	mtx_unlock(&thr->queue_lock);
13664 	wakeup(thr);
13665 }
13666 
13667 /*
13668  *  vim: ts=8
13669  */
13670