xref: /freebsd/sys/cam/ctl/ctl.c (revision fd6bb0db872a4212722a30b762639ae01b5644d9)
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/sysctl.h>
70 #include <sys/nv.h>
71 #include <sys/dnv.h>
72 #include <vm/uma.h>
73 
74 #include <cam/cam.h>
75 #include <cam/scsi/scsi_all.h>
76 #include <cam/scsi/scsi_cd.h>
77 #include <cam/scsi/scsi_da.h>
78 #include <cam/ctl/ctl_io.h>
79 #include <cam/ctl/ctl.h>
80 #include <cam/ctl/ctl_frontend.h>
81 #include <cam/ctl/ctl_util.h>
82 #include <cam/ctl/ctl_backend.h>
83 #include <cam/ctl/ctl_ioctl.h>
84 #include <cam/ctl/ctl_ha.h>
85 #include <cam/ctl/ctl_private.h>
86 #include <cam/ctl/ctl_debug.h>
87 #include <cam/ctl/ctl_scsi_all.h>
88 #include <cam/ctl/ctl_error.h>
89 
90 struct ctl_softc *control_softc = NULL;
91 
92 /*
93  * Template mode pages.
94  */
95 
96 /*
97  * Note that these are default values only.  The actual values will be
98  * filled in when the user does a mode sense.
99  */
100 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
101 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
102 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
103 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
104 	/*read_retry_count*/0,
105 	/*correction_span*/0,
106 	/*head_offset_count*/0,
107 	/*data_strobe_offset_cnt*/0,
108 	/*byte8*/SMS_RWER_LBPERE,
109 	/*write_retry_count*/0,
110 	/*reserved2*/0,
111 	/*recovery_time_limit*/{0, 0},
112 };
113 
114 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
115 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
116 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
117 	/*byte3*/SMS_RWER_PER,
118 	/*read_retry_count*/0,
119 	/*correction_span*/0,
120 	/*head_offset_count*/0,
121 	/*data_strobe_offset_cnt*/0,
122 	/*byte8*/SMS_RWER_LBPERE,
123 	/*write_retry_count*/0,
124 	/*reserved2*/0,
125 	/*recovery_time_limit*/{0, 0},
126 };
127 
128 const static struct scsi_format_page format_page_default = {
129 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
130 	/*page_length*/sizeof(struct scsi_format_page) - 2,
131 	/*tracks_per_zone*/ {0, 0},
132 	/*alt_sectors_per_zone*/ {0, 0},
133 	/*alt_tracks_per_zone*/ {0, 0},
134 	/*alt_tracks_per_lun*/ {0, 0},
135 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
136 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
137 	/*bytes_per_sector*/ {0, 0},
138 	/*interleave*/ {0, 0},
139 	/*track_skew*/ {0, 0},
140 	/*cylinder_skew*/ {0, 0},
141 	/*flags*/ SFP_HSEC,
142 	/*reserved*/ {0, 0, 0}
143 };
144 
145 const static struct scsi_format_page format_page_changeable = {
146 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
147 	/*page_length*/sizeof(struct scsi_format_page) - 2,
148 	/*tracks_per_zone*/ {0, 0},
149 	/*alt_sectors_per_zone*/ {0, 0},
150 	/*alt_tracks_per_zone*/ {0, 0},
151 	/*alt_tracks_per_lun*/ {0, 0},
152 	/*sectors_per_track*/ {0, 0},
153 	/*bytes_per_sector*/ {0, 0},
154 	/*interleave*/ {0, 0},
155 	/*track_skew*/ {0, 0},
156 	/*cylinder_skew*/ {0, 0},
157 	/*flags*/ 0,
158 	/*reserved*/ {0, 0, 0}
159 };
160 
161 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
162 	/*page_code*/SMS_RIGID_DISK_PAGE,
163 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
164 	/*cylinders*/ {0, 0, 0},
165 	/*heads*/ CTL_DEFAULT_HEADS,
166 	/*start_write_precomp*/ {0, 0, 0},
167 	/*start_reduced_current*/ {0, 0, 0},
168 	/*step_rate*/ {0, 0},
169 	/*landing_zone_cylinder*/ {0, 0, 0},
170 	/*rpl*/ SRDP_RPL_DISABLED,
171 	/*rotational_offset*/ 0,
172 	/*reserved1*/ 0,
173 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
174 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
175 	/*reserved2*/ {0, 0}
176 };
177 
178 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
179 	/*page_code*/SMS_RIGID_DISK_PAGE,
180 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
181 	/*cylinders*/ {0, 0, 0},
182 	/*heads*/ 0,
183 	/*start_write_precomp*/ {0, 0, 0},
184 	/*start_reduced_current*/ {0, 0, 0},
185 	/*step_rate*/ {0, 0},
186 	/*landing_zone_cylinder*/ {0, 0, 0},
187 	/*rpl*/ 0,
188 	/*rotational_offset*/ 0,
189 	/*reserved1*/ 0,
190 	/*rotation_rate*/ {0, 0},
191 	/*reserved2*/ {0, 0}
192 };
193 
194 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
195 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
196 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
197 	/*byte3*/0,
198 	/*read_retry_count*/0,
199 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
200 	/*recovery_time_limit*/{0, 0},
201 };
202 
203 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
204 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
205 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
206 	/*byte3*/SMS_VER_PER,
207 	/*read_retry_count*/0,
208 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
209 	/*recovery_time_limit*/{0, 0},
210 };
211 
212 const static struct scsi_caching_page caching_page_default = {
213 	/*page_code*/SMS_CACHING_PAGE,
214 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
215 	/*flags1*/ SCP_DISC | SCP_WCE,
216 	/*ret_priority*/ 0,
217 	/*disable_pf_transfer_len*/ {0xff, 0xff},
218 	/*min_prefetch*/ {0, 0},
219 	/*max_prefetch*/ {0xff, 0xff},
220 	/*max_pf_ceiling*/ {0xff, 0xff},
221 	/*flags2*/ 0,
222 	/*cache_segments*/ 0,
223 	/*cache_seg_size*/ {0, 0},
224 	/*reserved*/ 0,
225 	/*non_cache_seg_size*/ {0, 0, 0}
226 };
227 
228 const static struct scsi_caching_page caching_page_changeable = {
229 	/*page_code*/SMS_CACHING_PAGE,
230 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
231 	/*flags1*/ SCP_WCE | SCP_RCD,
232 	/*ret_priority*/ 0,
233 	/*disable_pf_transfer_len*/ {0, 0},
234 	/*min_prefetch*/ {0, 0},
235 	/*max_prefetch*/ {0, 0},
236 	/*max_pf_ceiling*/ {0, 0},
237 	/*flags2*/ 0,
238 	/*cache_segments*/ 0,
239 	/*cache_seg_size*/ {0, 0},
240 	/*reserved*/ 0,
241 	/*non_cache_seg_size*/ {0, 0, 0}
242 };
243 
244 const static struct scsi_control_page control_page_default = {
245 	/*page_code*/SMS_CONTROL_MODE_PAGE,
246 	/*page_length*/sizeof(struct scsi_control_page) - 2,
247 	/*rlec*/0,
248 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
249 	/*eca_and_aen*/0,
250 	/*flags4*/SCP_TAS,
251 	/*aen_holdoff_period*/{0, 0},
252 	/*busy_timeout_period*/{0, 0},
253 	/*extended_selftest_completion_time*/{0, 0}
254 };
255 
256 const static struct scsi_control_page control_page_changeable = {
257 	/*page_code*/SMS_CONTROL_MODE_PAGE,
258 	/*page_length*/sizeof(struct scsi_control_page) - 2,
259 	/*rlec*/SCP_DSENSE,
260 	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
261 	/*eca_and_aen*/SCP_SWP,
262 	/*flags4*/0,
263 	/*aen_holdoff_period*/{0, 0},
264 	/*busy_timeout_period*/{0, 0},
265 	/*extended_selftest_completion_time*/{0, 0}
266 };
267 
268 #define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
269 
270 const static struct scsi_control_ext_page control_ext_page_default = {
271 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
272 	/*subpage_code*/0x01,
273 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
274 	/*flags*/0,
275 	/*prio*/0,
276 	/*max_sense*/0
277 };
278 
279 const static struct scsi_control_ext_page control_ext_page_changeable = {
280 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
281 	/*subpage_code*/0x01,
282 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
283 	/*flags*/0,
284 	/*prio*/0,
285 	/*max_sense*/0xff
286 };
287 
288 const static struct scsi_info_exceptions_page ie_page_default = {
289 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
290 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
291 	/*info_flags*/SIEP_FLAGS_EWASC,
292 	/*mrie*/SIEP_MRIE_NO,
293 	/*interval_timer*/{0, 0, 0, 0},
294 	/*report_count*/{0, 0, 0, 1}
295 };
296 
297 const static struct scsi_info_exceptions_page ie_page_changeable = {
298 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
299 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
300 	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
301 	    SIEP_FLAGS_LOGERR,
302 	/*mrie*/0x0f,
303 	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
304 	/*report_count*/{0xff, 0xff, 0xff, 0xff}
305 };
306 
307 #define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
308 
309 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
310 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
311 	/*subpage_code*/0x02,
312 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
313 	/*flags*/0,
314 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
315 	/*descr*/{}},
316 	{{/*flags*/0,
317 	  /*resource*/0x01,
318 	  /*reserved*/{0, 0},
319 	  /*count*/{0, 0, 0, 0}},
320 	 {/*flags*/0,
321 	  /*resource*/0x02,
322 	  /*reserved*/{0, 0},
323 	  /*count*/{0, 0, 0, 0}},
324 	 {/*flags*/0,
325 	  /*resource*/0xf1,
326 	  /*reserved*/{0, 0},
327 	  /*count*/{0, 0, 0, 0}},
328 	 {/*flags*/0,
329 	  /*resource*/0xf2,
330 	  /*reserved*/{0, 0},
331 	  /*count*/{0, 0, 0, 0}}
332 	}
333 };
334 
335 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
336 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
337 	/*subpage_code*/0x02,
338 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
339 	/*flags*/SLBPP_SITUA,
340 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
341 	/*descr*/{}},
342 	{{/*flags*/0,
343 	  /*resource*/0,
344 	  /*reserved*/{0, 0},
345 	  /*count*/{0, 0, 0, 0}},
346 	 {/*flags*/0,
347 	  /*resource*/0,
348 	  /*reserved*/{0, 0},
349 	  /*count*/{0, 0, 0, 0}},
350 	 {/*flags*/0,
351 	  /*resource*/0,
352 	  /*reserved*/{0, 0},
353 	  /*count*/{0, 0, 0, 0}},
354 	 {/*flags*/0,
355 	  /*resource*/0,
356 	  /*reserved*/{0, 0},
357 	  /*count*/{0, 0, 0, 0}}
358 	}
359 };
360 
361 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
362 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
363 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
364 	/*caps1*/0x3f,
365 	/*caps2*/0x00,
366 	/*caps3*/0xf0,
367 	/*caps4*/0x00,
368 	/*caps5*/0x29,
369 	/*caps6*/0x00,
370 	/*obsolete*/{0, 0},
371 	/*nvol_levels*/{0, 0},
372 	/*buffer_size*/{8, 0},
373 	/*obsolete2*/{0, 0},
374 	/*reserved*/0,
375 	/*digital*/0,
376 	/*obsolete3*/0,
377 	/*copy_management*/0,
378 	/*reserved2*/0,
379 	/*rotation_control*/0,
380 	/*cur_write_speed*/0,
381 	/*num_speed_descr*/0,
382 };
383 
384 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
385 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
386 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
387 	/*caps1*/0,
388 	/*caps2*/0,
389 	/*caps3*/0,
390 	/*caps4*/0,
391 	/*caps5*/0,
392 	/*caps6*/0,
393 	/*obsolete*/{0, 0},
394 	/*nvol_levels*/{0, 0},
395 	/*buffer_size*/{0, 0},
396 	/*obsolete2*/{0, 0},
397 	/*reserved*/0,
398 	/*digital*/0,
399 	/*obsolete3*/0,
400 	/*copy_management*/0,
401 	/*reserved2*/0,
402 	/*rotation_control*/0,
403 	/*cur_write_speed*/0,
404 	/*num_speed_descr*/0,
405 };
406 
407 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
408 static int worker_threads = -1;
409 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
410     &worker_threads, 1, "Number of worker threads");
411 static int ctl_debug = CTL_DEBUG_NONE;
412 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
413     &ctl_debug, 0, "Enabled debug flags");
414 static int ctl_lun_map_size = 1024;
415 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
416     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
417 #ifdef  CTL_TIME_IO
418 static int ctl_time_io_secs = CTL_TIME_IO_DEFAULT_SECS;
419 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, time_io_secs, CTLFLAG_RWTUN,
420     &ctl_time_io_secs, 0, "Log requests taking more seconds");
421 #endif
422 
423 /*
424  * Maximum number of LUNs we support.  MUST be a power of 2.
425  */
426 #define	CTL_DEFAULT_MAX_LUNS	1024
427 static int ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
428 TUNABLE_INT("kern.cam.ctl.max_luns", &ctl_max_luns);
429 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_luns, CTLFLAG_RDTUN,
430     &ctl_max_luns, CTL_DEFAULT_MAX_LUNS, "Maximum number of LUNs");
431 
432 /*
433  * Maximum number of ports registered at one time.
434  */
435 #define	CTL_DEFAULT_MAX_PORTS		256
436 static int ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
437 TUNABLE_INT("kern.cam.ctl.max_ports", &ctl_max_ports);
438 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_ports, CTLFLAG_RDTUN,
439     &ctl_max_ports, CTL_DEFAULT_MAX_LUNS, "Maximum number of ports");
440 
441 /*
442  * Maximum number of initiators we support.
443  */
444 #define	CTL_MAX_INITIATORS	(CTL_MAX_INIT_PER_PORT * ctl_max_ports)
445 
446 /*
447  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
448  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
449  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
450  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
451  */
452 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
453 
454 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
455 				  int param);
456 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
457 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
458 static int ctl_init(void);
459 static int ctl_shutdown(void);
460 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
461 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
462 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
463 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
464 			      struct ctl_ooa *ooa_hdr,
465 			      struct ctl_ooa_entry *kern_entries);
466 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
467 		     struct thread *td);
468 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
469 			 struct ctl_be_lun *be_lun);
470 static int ctl_free_lun(struct ctl_lun *lun);
471 static void ctl_create_lun(struct ctl_be_lun *be_lun);
472 
473 static int ctl_do_mode_select(union ctl_io *io);
474 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
475 			   uint64_t res_key, uint64_t sa_res_key,
476 			   uint8_t type, uint32_t residx,
477 			   struct ctl_scsiio *ctsio,
478 			   struct scsi_per_res_out *cdb,
479 			   struct scsi_per_res_out_parms* param);
480 static void ctl_pro_preempt_other(struct ctl_lun *lun,
481 				  union ctl_ha_msg *msg);
482 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
483 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
484 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
485 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
486 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
487 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
488 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
489 					 int alloc_len);
490 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
491 					 int alloc_len);
492 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
493 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
494 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
495 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
496 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
497 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
498     bool seq);
499 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
500 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
501     union ctl_io *pending_io, union ctl_io *ooa_io);
502 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
503 				union ctl_io **starting_io);
504 static void ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io,
505     bool skip);
506 static void ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *io,
507     bool skip);
508 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
509 				const struct ctl_cmd_entry *entry,
510 				struct ctl_scsiio *ctsio);
511 static void ctl_failover_lun(union ctl_io *io);
512 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
513 			       struct ctl_scsiio *ctsio);
514 static int ctl_scsiio(struct ctl_scsiio *ctsio);
515 
516 static int ctl_target_reset(union ctl_io *io);
517 static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
518 			 ctl_ua_type ua_type);
519 static int ctl_lun_reset(union ctl_io *io);
520 static int ctl_abort_task(union ctl_io *io);
521 static int ctl_abort_task_set(union ctl_io *io);
522 static int ctl_query_task(union ctl_io *io, int task_set);
523 static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
524 			      ctl_ua_type ua_type);
525 static int ctl_i_t_nexus_reset(union ctl_io *io);
526 static int ctl_query_async_event(union ctl_io *io);
527 static void ctl_run_task(union ctl_io *io);
528 #ifdef CTL_IO_DELAY
529 static void ctl_datamove_timer_wakeup(void *arg);
530 static void ctl_done_timer_wakeup(void *arg);
531 #endif /* CTL_IO_DELAY */
532 
533 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
534 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
535 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
536 static void ctl_datamove_remote_write(union ctl_io *io);
537 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
538 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
539 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
540 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
541 				    ctl_ha_dt_cb callback);
542 static void ctl_datamove_remote_read(union ctl_io *io);
543 static void ctl_datamove_remote(union ctl_io *io);
544 static void ctl_process_done(union ctl_io *io);
545 static void ctl_lun_thread(void *arg);
546 static void ctl_thresh_thread(void *arg);
547 static void ctl_work_thread(void *arg);
548 static void ctl_enqueue_incoming(union ctl_io *io);
549 static void ctl_enqueue_rtr(union ctl_io *io);
550 static void ctl_enqueue_done(union ctl_io *io);
551 static void ctl_enqueue_isc(union ctl_io *io);
552 static const struct ctl_cmd_entry *
553     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
554 static const struct ctl_cmd_entry *
555     ctl_validate_command(struct ctl_scsiio *ctsio);
556 static int ctl_cmd_applicable(uint8_t lun_type,
557     const struct ctl_cmd_entry *entry);
558 static int ctl_ha_init(void);
559 static int ctl_ha_shutdown(void);
560 
561 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
562 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
563 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
564 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
565 
566 /*
567  * Load the serialization table.  This isn't very pretty, but is probably
568  * the easiest way to do it.
569  */
570 #include "ctl_ser_table.c"
571 
572 /*
573  * We only need to define open, close and ioctl routines for this driver.
574  */
575 static struct cdevsw ctl_cdevsw = {
576 	.d_version =	D_VERSION,
577 	.d_flags =	0,
578 	.d_open =	ctl_open,
579 	.d_close =	ctl_close,
580 	.d_ioctl =	ctl_ioctl,
581 	.d_name =	"ctl",
582 };
583 
584 
585 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
586 
587 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
588 
589 static moduledata_t ctl_moduledata = {
590 	"ctl",
591 	ctl_module_event_handler,
592 	NULL
593 };
594 
595 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
596 MODULE_VERSION(ctl, 1);
597 
598 static struct ctl_frontend ha_frontend =
599 {
600 	.name = "ha",
601 	.init = ctl_ha_init,
602 	.shutdown = ctl_ha_shutdown,
603 };
604 
605 static int
606 ctl_ha_init(void)
607 {
608 	struct ctl_softc *softc = control_softc;
609 
610 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
611 	                    &softc->othersc_pool) != 0)
612 		return (ENOMEM);
613 	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
614 		ctl_pool_free(softc->othersc_pool);
615 		return (EIO);
616 	}
617 	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
618 	    != CTL_HA_STATUS_SUCCESS) {
619 		ctl_ha_msg_destroy(softc);
620 		ctl_pool_free(softc->othersc_pool);
621 		return (EIO);
622 	}
623 	return (0);
624 };
625 
626 static int
627 ctl_ha_shutdown(void)
628 {
629 	struct ctl_softc *softc = control_softc;
630 	struct ctl_port *port;
631 
632 	ctl_ha_msg_shutdown(softc);
633 	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
634 		return (EIO);
635 	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
636 		return (EIO);
637 	ctl_pool_free(softc->othersc_pool);
638 	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
639 		ctl_port_deregister(port);
640 		free(port->port_name, M_CTL);
641 		free(port, M_CTL);
642 	}
643 	return (0);
644 };
645 
646 static void
647 ctl_ha_datamove(union ctl_io *io)
648 {
649 	struct ctl_lun *lun = CTL_LUN(io);
650 	struct ctl_sg_entry *sgl;
651 	union ctl_ha_msg msg;
652 	uint32_t sg_entries_sent;
653 	int do_sg_copy, i, j;
654 
655 	memset(&msg.dt, 0, sizeof(msg.dt));
656 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
657 	msg.hdr.original_sc = io->io_hdr.remote_io;
658 	msg.hdr.serializing_sc = io;
659 	msg.hdr.nexus = io->io_hdr.nexus;
660 	msg.hdr.status = io->io_hdr.status;
661 	msg.dt.flags = io->io_hdr.flags;
662 
663 	/*
664 	 * We convert everything into a S/G list here.  We can't
665 	 * pass by reference, only by value between controllers.
666 	 * So we can't pass a pointer to the S/G list, only as many
667 	 * S/G entries as we can fit in here.  If it's possible for
668 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
669 	 * then we need to break this up into multiple transfers.
670 	 */
671 	if (io->scsiio.kern_sg_entries == 0) {
672 		msg.dt.kern_sg_entries = 1;
673 #if 0
674 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
675 			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
676 		} else {
677 			/* XXX KDM use busdma here! */
678 			msg.dt.sg_list[0].addr =
679 			    (void *)vtophys(io->scsiio.kern_data_ptr);
680 		}
681 #else
682 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
683 		    ("HA does not support BUS_ADDR"));
684 		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
685 #endif
686 		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
687 		do_sg_copy = 0;
688 	} else {
689 		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
690 		do_sg_copy = 1;
691 	}
692 
693 	msg.dt.kern_data_len = io->scsiio.kern_data_len;
694 	msg.dt.kern_total_len = io->scsiio.kern_total_len;
695 	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
696 	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
697 	msg.dt.sg_sequence = 0;
698 
699 	/*
700 	 * Loop until we've sent all of the S/G entries.  On the
701 	 * other end, we'll recompose these S/G entries into one
702 	 * contiguous list before processing.
703 	 */
704 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
705 	    msg.dt.sg_sequence++) {
706 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
707 		    sizeof(msg.dt.sg_list[0])),
708 		    msg.dt.kern_sg_entries - sg_entries_sent);
709 		if (do_sg_copy != 0) {
710 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
711 			for (i = sg_entries_sent, j = 0;
712 			     i < msg.dt.cur_sg_entries; i++, j++) {
713 #if 0
714 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
715 					msg.dt.sg_list[j].addr = sgl[i].addr;
716 				} else {
717 					/* XXX KDM use busdma here! */
718 					msg.dt.sg_list[j].addr =
719 					    (void *)vtophys(sgl[i].addr);
720 				}
721 #else
722 				KASSERT((io->io_hdr.flags &
723 				    CTL_FLAG_BUS_ADDR) == 0,
724 				    ("HA does not support BUS_ADDR"));
725 				msg.dt.sg_list[j].addr = sgl[i].addr;
726 #endif
727 				msg.dt.sg_list[j].len = sgl[i].len;
728 			}
729 		}
730 
731 		sg_entries_sent += msg.dt.cur_sg_entries;
732 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
733 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
734 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
735 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
736 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
737 			io->io_hdr.port_status = 31341;
738 			io->scsiio.be_move_done(io);
739 			return;
740 		}
741 		msg.dt.sent_sg_entries = sg_entries_sent;
742 	}
743 
744 	/*
745 	 * Officially handover the request from us to peer.
746 	 * If failover has just happened, then we must return error.
747 	 * If failover happen just after, then it is not our problem.
748 	 */
749 	if (lun)
750 		mtx_lock(&lun->lun_lock);
751 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
752 		if (lun)
753 			mtx_unlock(&lun->lun_lock);
754 		io->io_hdr.port_status = 31342;
755 		io->scsiio.be_move_done(io);
756 		return;
757 	}
758 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
759 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
760 	if (lun)
761 		mtx_unlock(&lun->lun_lock);
762 }
763 
764 static void
765 ctl_ha_done(union ctl_io *io)
766 {
767 	union ctl_ha_msg msg;
768 
769 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
770 		memset(&msg, 0, sizeof(msg));
771 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
772 		msg.hdr.original_sc = io->io_hdr.remote_io;
773 		msg.hdr.nexus = io->io_hdr.nexus;
774 		msg.hdr.status = io->io_hdr.status;
775 		msg.scsi.scsi_status = io->scsiio.scsi_status;
776 		msg.scsi.tag_num = io->scsiio.tag_num;
777 		msg.scsi.tag_type = io->scsiio.tag_type;
778 		msg.scsi.sense_len = io->scsiio.sense_len;
779 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
780 		    io->scsiio.sense_len);
781 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
782 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
783 		    msg.scsi.sense_len, M_WAITOK);
784 	}
785 	ctl_free_io(io);
786 }
787 
788 static void
789 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
790 			    union ctl_ha_msg *msg_info)
791 {
792 	struct ctl_scsiio *ctsio;
793 
794 	if (msg_info->hdr.original_sc == NULL) {
795 		printf("%s: original_sc == NULL!\n", __func__);
796 		/* XXX KDM now what? */
797 		return;
798 	}
799 
800 	ctsio = &msg_info->hdr.original_sc->scsiio;
801 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
802 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
803 	ctsio->io_hdr.status = msg_info->hdr.status;
804 	ctsio->scsi_status = msg_info->scsi.scsi_status;
805 	ctsio->sense_len = msg_info->scsi.sense_len;
806 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
807 	       msg_info->scsi.sense_len);
808 	ctl_enqueue_isc((union ctl_io *)ctsio);
809 }
810 
811 static void
812 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
813 				union ctl_ha_msg *msg_info)
814 {
815 	struct ctl_scsiio *ctsio;
816 
817 	if (msg_info->hdr.serializing_sc == NULL) {
818 		printf("%s: serializing_sc == NULL!\n", __func__);
819 		/* XXX KDM now what? */
820 		return;
821 	}
822 
823 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
824 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
825 	ctl_enqueue_isc((union ctl_io *)ctsio);
826 }
827 
828 void
829 ctl_isc_announce_lun(struct ctl_lun *lun)
830 {
831 	struct ctl_softc *softc = lun->ctl_softc;
832 	union ctl_ha_msg *msg;
833 	struct ctl_ha_msg_lun_pr_key pr_key;
834 	int i, k;
835 
836 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
837 		return;
838 	mtx_lock(&lun->lun_lock);
839 	i = sizeof(msg->lun);
840 	if (lun->lun_devid)
841 		i += lun->lun_devid->len;
842 	i += sizeof(pr_key) * lun->pr_key_count;
843 alloc:
844 	mtx_unlock(&lun->lun_lock);
845 	msg = malloc(i, M_CTL, M_WAITOK);
846 	mtx_lock(&lun->lun_lock);
847 	k = sizeof(msg->lun);
848 	if (lun->lun_devid)
849 		k += lun->lun_devid->len;
850 	k += sizeof(pr_key) * lun->pr_key_count;
851 	if (i < k) {
852 		free(msg, M_CTL);
853 		i = k;
854 		goto alloc;
855 	}
856 	bzero(&msg->lun, sizeof(msg->lun));
857 	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
858 	msg->hdr.nexus.targ_lun = lun->lun;
859 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
860 	msg->lun.flags = lun->flags;
861 	msg->lun.pr_generation = lun->pr_generation;
862 	msg->lun.pr_res_idx = lun->pr_res_idx;
863 	msg->lun.pr_res_type = lun->pr_res_type;
864 	msg->lun.pr_key_count = lun->pr_key_count;
865 	i = 0;
866 	if (lun->lun_devid) {
867 		msg->lun.lun_devid_len = lun->lun_devid->len;
868 		memcpy(&msg->lun.data[i], lun->lun_devid->data,
869 		    msg->lun.lun_devid_len);
870 		i += msg->lun.lun_devid_len;
871 	}
872 	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
873 		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
874 			continue;
875 		pr_key.pr_iid = k;
876 		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
877 		i += sizeof(pr_key);
878 	}
879 	mtx_unlock(&lun->lun_lock);
880 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
881 	    M_WAITOK);
882 	free(msg, M_CTL);
883 
884 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
885 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
886 			ctl_isc_announce_mode(lun, -1,
887 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
888 			    lun->mode_pages.index[i].subpage);
889 		}
890 	}
891 }
892 
893 void
894 ctl_isc_announce_port(struct ctl_port *port)
895 {
896 	struct ctl_softc *softc = port->ctl_softc;
897 	union ctl_ha_msg *msg;
898 	int i;
899 
900 	if (port->targ_port < softc->port_min ||
901 	    port->targ_port >= softc->port_max ||
902 	    softc->ha_link != CTL_HA_LINK_ONLINE)
903 		return;
904 	i = sizeof(msg->port) + strlen(port->port_name) + 1;
905 	if (port->lun_map)
906 		i += port->lun_map_size * sizeof(uint32_t);
907 	if (port->port_devid)
908 		i += port->port_devid->len;
909 	if (port->target_devid)
910 		i += port->target_devid->len;
911 	if (port->init_devid)
912 		i += port->init_devid->len;
913 	msg = malloc(i, M_CTL, M_WAITOK);
914 	bzero(&msg->port, sizeof(msg->port));
915 	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
916 	msg->hdr.nexus.targ_port = port->targ_port;
917 	msg->port.port_type = port->port_type;
918 	msg->port.physical_port = port->physical_port;
919 	msg->port.virtual_port = port->virtual_port;
920 	msg->port.status = port->status;
921 	i = 0;
922 	msg->port.name_len = sprintf(&msg->port.data[i],
923 	    "%d:%s", softc->ha_id, port->port_name) + 1;
924 	i += msg->port.name_len;
925 	if (port->lun_map) {
926 		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
927 		memcpy(&msg->port.data[i], port->lun_map,
928 		    msg->port.lun_map_len);
929 		i += msg->port.lun_map_len;
930 	}
931 	if (port->port_devid) {
932 		msg->port.port_devid_len = port->port_devid->len;
933 		memcpy(&msg->port.data[i], port->port_devid->data,
934 		    msg->port.port_devid_len);
935 		i += msg->port.port_devid_len;
936 	}
937 	if (port->target_devid) {
938 		msg->port.target_devid_len = port->target_devid->len;
939 		memcpy(&msg->port.data[i], port->target_devid->data,
940 		    msg->port.target_devid_len);
941 		i += msg->port.target_devid_len;
942 	}
943 	if (port->init_devid) {
944 		msg->port.init_devid_len = port->init_devid->len;
945 		memcpy(&msg->port.data[i], port->init_devid->data,
946 		    msg->port.init_devid_len);
947 		i += msg->port.init_devid_len;
948 	}
949 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
950 	    M_WAITOK);
951 	free(msg, M_CTL);
952 }
953 
954 void
955 ctl_isc_announce_iid(struct ctl_port *port, int iid)
956 {
957 	struct ctl_softc *softc = port->ctl_softc;
958 	union ctl_ha_msg *msg;
959 	int i, l;
960 
961 	if (port->targ_port < softc->port_min ||
962 	    port->targ_port >= softc->port_max ||
963 	    softc->ha_link != CTL_HA_LINK_ONLINE)
964 		return;
965 	mtx_lock(&softc->ctl_lock);
966 	i = sizeof(msg->iid);
967 	l = 0;
968 	if (port->wwpn_iid[iid].name)
969 		l = strlen(port->wwpn_iid[iid].name) + 1;
970 	i += l;
971 	msg = malloc(i, M_CTL, M_NOWAIT);
972 	if (msg == NULL) {
973 		mtx_unlock(&softc->ctl_lock);
974 		return;
975 	}
976 	bzero(&msg->iid, sizeof(msg->iid));
977 	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
978 	msg->hdr.nexus.targ_port = port->targ_port;
979 	msg->hdr.nexus.initid = iid;
980 	msg->iid.in_use = port->wwpn_iid[iid].in_use;
981 	msg->iid.name_len = l;
982 	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
983 	if (port->wwpn_iid[iid].name)
984 		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
985 	mtx_unlock(&softc->ctl_lock);
986 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
987 	free(msg, M_CTL);
988 }
989 
990 void
991 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
992     uint8_t page, uint8_t subpage)
993 {
994 	struct ctl_softc *softc = lun->ctl_softc;
995 	union ctl_ha_msg msg;
996 	u_int i;
997 
998 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
999 		return;
1000 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1001 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1002 		    page && lun->mode_pages.index[i].subpage == subpage)
1003 			break;
1004 	}
1005 	if (i == CTL_NUM_MODE_PAGES)
1006 		return;
1007 
1008 	/* Don't try to replicate pages not present on this device. */
1009 	if (lun->mode_pages.index[i].page_data == NULL)
1010 		return;
1011 
1012 	bzero(&msg.mode, sizeof(msg.mode));
1013 	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
1014 	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
1015 	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
1016 	msg.hdr.nexus.targ_lun = lun->lun;
1017 	msg.hdr.nexus.targ_mapped_lun = lun->lun;
1018 	msg.mode.page_code = page;
1019 	msg.mode.subpage = subpage;
1020 	msg.mode.page_len = lun->mode_pages.index[i].page_len;
1021 	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
1022 	    msg.mode.page_len);
1023 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
1024 	    M_WAITOK);
1025 }
1026 
1027 static void
1028 ctl_isc_ha_link_up(struct ctl_softc *softc)
1029 {
1030 	struct ctl_port *port;
1031 	struct ctl_lun *lun;
1032 	union ctl_ha_msg msg;
1033 	int i;
1034 
1035 	/* Announce this node parameters to peer for validation. */
1036 	msg.login.msg_type = CTL_MSG_LOGIN;
1037 	msg.login.version = CTL_HA_VERSION;
1038 	msg.login.ha_mode = softc->ha_mode;
1039 	msg.login.ha_id = softc->ha_id;
1040 	msg.login.max_luns = ctl_max_luns;
1041 	msg.login.max_ports = ctl_max_ports;
1042 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1043 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1044 	    M_WAITOK);
1045 
1046 	STAILQ_FOREACH(port, &softc->port_list, links) {
1047 		ctl_isc_announce_port(port);
1048 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1049 			if (port->wwpn_iid[i].in_use)
1050 				ctl_isc_announce_iid(port, i);
1051 		}
1052 	}
1053 	STAILQ_FOREACH(lun, &softc->lun_list, links)
1054 		ctl_isc_announce_lun(lun);
1055 }
1056 
1057 static void
1058 ctl_isc_ha_link_down(struct ctl_softc *softc)
1059 {
1060 	struct ctl_port *port;
1061 	struct ctl_lun *lun;
1062 	union ctl_io *io;
1063 	int i;
1064 
1065 	mtx_lock(&softc->ctl_lock);
1066 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1067 		mtx_lock(&lun->lun_lock);
1068 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1069 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1070 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1071 		}
1072 		mtx_unlock(&lun->lun_lock);
1073 
1074 		mtx_unlock(&softc->ctl_lock);
1075 		io = ctl_alloc_io(softc->othersc_pool);
1076 		mtx_lock(&softc->ctl_lock);
1077 		ctl_zero_io(io);
1078 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1079 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1080 		ctl_enqueue_isc(io);
1081 	}
1082 
1083 	STAILQ_FOREACH(port, &softc->port_list, links) {
1084 		if (port->targ_port >= softc->port_min &&
1085 		    port->targ_port < softc->port_max)
1086 			continue;
1087 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1088 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1089 			port->wwpn_iid[i].in_use = 0;
1090 			free(port->wwpn_iid[i].name, M_CTL);
1091 			port->wwpn_iid[i].name = NULL;
1092 		}
1093 	}
1094 	mtx_unlock(&softc->ctl_lock);
1095 }
1096 
1097 static void
1098 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1099 {
1100 	struct ctl_lun *lun;
1101 	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1102 
1103 	mtx_lock(&softc->ctl_lock);
1104 	if (msg->hdr.nexus.targ_mapped_lun >= ctl_max_luns ||
1105 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1106 		mtx_unlock(&softc->ctl_lock);
1107 		return;
1108 	}
1109 	mtx_lock(&lun->lun_lock);
1110 	mtx_unlock(&softc->ctl_lock);
1111 	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1112 		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1113 	if (msg->ua.ua_all) {
1114 		if (msg->ua.ua_set)
1115 			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1116 		else
1117 			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1118 	} else {
1119 		if (msg->ua.ua_set)
1120 			ctl_est_ua(lun, iid, msg->ua.ua_type);
1121 		else
1122 			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1123 	}
1124 	mtx_unlock(&lun->lun_lock);
1125 }
1126 
1127 static void
1128 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1129 {
1130 	struct ctl_lun *lun;
1131 	struct ctl_ha_msg_lun_pr_key pr_key;
1132 	int i, k;
1133 	ctl_lun_flags oflags;
1134 	uint32_t targ_lun;
1135 
1136 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1137 	mtx_lock(&softc->ctl_lock);
1138 	if (targ_lun >= ctl_max_luns ||
1139 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1140 		mtx_unlock(&softc->ctl_lock);
1141 		return;
1142 	}
1143 	mtx_lock(&lun->lun_lock);
1144 	mtx_unlock(&softc->ctl_lock);
1145 	if (lun->flags & CTL_LUN_DISABLED) {
1146 		mtx_unlock(&lun->lun_lock);
1147 		return;
1148 	}
1149 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1150 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1151 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1152 		mtx_unlock(&lun->lun_lock);
1153 		printf("%s: Received conflicting HA LUN %d\n",
1154 		    __func__, targ_lun);
1155 		return;
1156 	} else {
1157 		/* Record whether peer is primary. */
1158 		oflags = lun->flags;
1159 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1160 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1161 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1162 		else
1163 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1164 		if (oflags != lun->flags)
1165 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1166 
1167 		/* If peer is primary and we are not -- use data */
1168 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1169 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1170 			lun->pr_generation = msg->lun.pr_generation;
1171 			lun->pr_res_idx = msg->lun.pr_res_idx;
1172 			lun->pr_res_type = msg->lun.pr_res_type;
1173 			lun->pr_key_count = msg->lun.pr_key_count;
1174 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1175 				ctl_clr_prkey(lun, k);
1176 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1177 				memcpy(&pr_key, &msg->lun.data[i],
1178 				    sizeof(pr_key));
1179 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1180 				ctl_set_prkey(lun, pr_key.pr_iid,
1181 				    pr_key.pr_key);
1182 				i += sizeof(pr_key);
1183 			}
1184 		}
1185 
1186 		mtx_unlock(&lun->lun_lock);
1187 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1188 		    __func__, targ_lun,
1189 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1190 		    "primary" : "secondary"));
1191 
1192 		/* If we are primary but peer doesn't know -- notify */
1193 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1194 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1195 			ctl_isc_announce_lun(lun);
1196 	}
1197 }
1198 
1199 static void
1200 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1201 {
1202 	struct ctl_port *port;
1203 	struct ctl_lun *lun;
1204 	int i, new;
1205 
1206 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1207 	if (port == NULL) {
1208 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1209 		    msg->hdr.nexus.targ_port));
1210 		new = 1;
1211 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1212 		port->frontend = &ha_frontend;
1213 		port->targ_port = msg->hdr.nexus.targ_port;
1214 		port->fe_datamove = ctl_ha_datamove;
1215 		port->fe_done = ctl_ha_done;
1216 	} else if (port->frontend == &ha_frontend) {
1217 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1218 		    msg->hdr.nexus.targ_port));
1219 		new = 0;
1220 	} else {
1221 		printf("%s: Received conflicting HA port %d\n",
1222 		    __func__, msg->hdr.nexus.targ_port);
1223 		return;
1224 	}
1225 	port->port_type = msg->port.port_type;
1226 	port->physical_port = msg->port.physical_port;
1227 	port->virtual_port = msg->port.virtual_port;
1228 	port->status = msg->port.status;
1229 	i = 0;
1230 	free(port->port_name, M_CTL);
1231 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1232 	    M_CTL);
1233 	i += msg->port.name_len;
1234 	if (msg->port.lun_map_len != 0) {
1235 		if (port->lun_map == NULL ||
1236 		    port->lun_map_size * sizeof(uint32_t) <
1237 		    msg->port.lun_map_len) {
1238 			port->lun_map_size = 0;
1239 			free(port->lun_map, M_CTL);
1240 			port->lun_map = malloc(msg->port.lun_map_len,
1241 			    M_CTL, M_WAITOK);
1242 		}
1243 		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1244 		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1245 		i += msg->port.lun_map_len;
1246 	} else {
1247 		port->lun_map_size = 0;
1248 		free(port->lun_map, M_CTL);
1249 		port->lun_map = NULL;
1250 	}
1251 	if (msg->port.port_devid_len != 0) {
1252 		if (port->port_devid == NULL ||
1253 		    port->port_devid->len < msg->port.port_devid_len) {
1254 			free(port->port_devid, M_CTL);
1255 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1256 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1257 		}
1258 		memcpy(port->port_devid->data, &msg->port.data[i],
1259 		    msg->port.port_devid_len);
1260 		port->port_devid->len = msg->port.port_devid_len;
1261 		i += msg->port.port_devid_len;
1262 	} else {
1263 		free(port->port_devid, M_CTL);
1264 		port->port_devid = NULL;
1265 	}
1266 	if (msg->port.target_devid_len != 0) {
1267 		if (port->target_devid == NULL ||
1268 		    port->target_devid->len < msg->port.target_devid_len) {
1269 			free(port->target_devid, M_CTL);
1270 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1271 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1272 		}
1273 		memcpy(port->target_devid->data, &msg->port.data[i],
1274 		    msg->port.target_devid_len);
1275 		port->target_devid->len = msg->port.target_devid_len;
1276 		i += msg->port.target_devid_len;
1277 	} else {
1278 		free(port->target_devid, M_CTL);
1279 		port->target_devid = NULL;
1280 	}
1281 	if (msg->port.init_devid_len != 0) {
1282 		if (port->init_devid == NULL ||
1283 		    port->init_devid->len < msg->port.init_devid_len) {
1284 			free(port->init_devid, M_CTL);
1285 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1286 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1287 		}
1288 		memcpy(port->init_devid->data, &msg->port.data[i],
1289 		    msg->port.init_devid_len);
1290 		port->init_devid->len = msg->port.init_devid_len;
1291 		i += msg->port.init_devid_len;
1292 	} else {
1293 		free(port->init_devid, M_CTL);
1294 		port->init_devid = NULL;
1295 	}
1296 	if (new) {
1297 		if (ctl_port_register(port) != 0) {
1298 			printf("%s: ctl_port_register() failed with error\n",
1299 			    __func__);
1300 		}
1301 	}
1302 	mtx_lock(&softc->ctl_lock);
1303 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1304 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1305 			continue;
1306 		mtx_lock(&lun->lun_lock);
1307 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1308 		mtx_unlock(&lun->lun_lock);
1309 	}
1310 	mtx_unlock(&softc->ctl_lock);
1311 }
1312 
1313 static void
1314 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1315 {
1316 	struct ctl_port *port;
1317 	int iid;
1318 
1319 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1320 	if (port == NULL) {
1321 		printf("%s: Received IID for unknown port %d\n",
1322 		    __func__, msg->hdr.nexus.targ_port);
1323 		return;
1324 	}
1325 	iid = msg->hdr.nexus.initid;
1326 	if (port->wwpn_iid[iid].in_use != 0 &&
1327 	    msg->iid.in_use == 0)
1328 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1329 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1330 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1331 	free(port->wwpn_iid[iid].name, M_CTL);
1332 	if (msg->iid.name_len) {
1333 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1334 		    msg->iid.name_len, M_CTL);
1335 	} else
1336 		port->wwpn_iid[iid].name = NULL;
1337 }
1338 
1339 static void
1340 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1341 {
1342 
1343 	if (msg->login.version != CTL_HA_VERSION) {
1344 		printf("CTL HA peers have different versions %d != %d\n",
1345 		    msg->login.version, CTL_HA_VERSION);
1346 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1347 		return;
1348 	}
1349 	if (msg->login.ha_mode != softc->ha_mode) {
1350 		printf("CTL HA peers have different ha_mode %d != %d\n",
1351 		    msg->login.ha_mode, softc->ha_mode);
1352 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1353 		return;
1354 	}
1355 	if (msg->login.ha_id == softc->ha_id) {
1356 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1357 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1358 		return;
1359 	}
1360 	if (msg->login.max_luns != ctl_max_luns ||
1361 	    msg->login.max_ports != ctl_max_ports ||
1362 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1363 		printf("CTL HA peers have different limits\n");
1364 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1365 		return;
1366 	}
1367 }
1368 
1369 static void
1370 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1371 {
1372 	struct ctl_lun *lun;
1373 	u_int i;
1374 	uint32_t initidx, targ_lun;
1375 
1376 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1377 	mtx_lock(&softc->ctl_lock);
1378 	if (targ_lun >= ctl_max_luns ||
1379 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1380 		mtx_unlock(&softc->ctl_lock);
1381 		return;
1382 	}
1383 	mtx_lock(&lun->lun_lock);
1384 	mtx_unlock(&softc->ctl_lock);
1385 	if (lun->flags & CTL_LUN_DISABLED) {
1386 		mtx_unlock(&lun->lun_lock);
1387 		return;
1388 	}
1389 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1390 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1391 		    msg->mode.page_code &&
1392 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1393 			break;
1394 	}
1395 	if (i == CTL_NUM_MODE_PAGES) {
1396 		mtx_unlock(&lun->lun_lock);
1397 		return;
1398 	}
1399 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1400 	    lun->mode_pages.index[i].page_len);
1401 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1402 	if (initidx != -1)
1403 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1404 	mtx_unlock(&lun->lun_lock);
1405 }
1406 
1407 /*
1408  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1409  * subsystem come in here.
1410  */
1411 static void
1412 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1413 {
1414 	struct ctl_softc *softc = control_softc;
1415 	union ctl_io *io;
1416 	struct ctl_prio *presio;
1417 	ctl_ha_status isc_status;
1418 
1419 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1420 	if (event == CTL_HA_EVT_MSG_RECV) {
1421 		union ctl_ha_msg *msg, msgbuf;
1422 
1423 		if (param > sizeof(msgbuf))
1424 			msg = malloc(param, M_CTL, M_WAITOK);
1425 		else
1426 			msg = &msgbuf;
1427 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1428 		    M_WAITOK);
1429 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1430 			printf("%s: Error receiving message: %d\n",
1431 			    __func__, isc_status);
1432 			if (msg != &msgbuf)
1433 				free(msg, M_CTL);
1434 			return;
1435 		}
1436 
1437 		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1438 		switch (msg->hdr.msg_type) {
1439 		case CTL_MSG_SERIALIZE:
1440 			io = ctl_alloc_io(softc->othersc_pool);
1441 			ctl_zero_io(io);
1442 			// populate ctsio from msg
1443 			io->io_hdr.io_type = CTL_IO_SCSI;
1444 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1445 			io->io_hdr.remote_io = msg->hdr.original_sc;
1446 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1447 					    CTL_FLAG_IO_ACTIVE;
1448 			/*
1449 			 * If we're in serialization-only mode, we don't
1450 			 * want to go through full done processing.  Thus
1451 			 * the COPY flag.
1452 			 *
1453 			 * XXX KDM add another flag that is more specific.
1454 			 */
1455 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1456 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1457 			io->io_hdr.nexus = msg->hdr.nexus;
1458 			io->scsiio.tag_num = msg->scsi.tag_num;
1459 			io->scsiio.tag_type = msg->scsi.tag_type;
1460 #ifdef CTL_TIME_IO
1461 			io->io_hdr.start_time = time_uptime;
1462 			getbinuptime(&io->io_hdr.start_bt);
1463 #endif /* CTL_TIME_IO */
1464 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1465 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1466 			       CTL_MAX_CDBLEN);
1467 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1468 				const struct ctl_cmd_entry *entry;
1469 
1470 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1471 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1472 				io->io_hdr.flags |=
1473 					entry->flags & CTL_FLAG_DATA_MASK;
1474 			}
1475 			ctl_enqueue_isc(io);
1476 			break;
1477 
1478 		/* Performed on the Originating SC, XFER mode only */
1479 		case CTL_MSG_DATAMOVE: {
1480 			struct ctl_sg_entry *sgl;
1481 			int i, j;
1482 
1483 			io = msg->hdr.original_sc;
1484 			if (io == NULL) {
1485 				printf("%s: original_sc == NULL!\n", __func__);
1486 				/* XXX KDM do something here */
1487 				break;
1488 			}
1489 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1490 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1491 			/*
1492 			 * Keep track of this, we need to send it back over
1493 			 * when the datamove is complete.
1494 			 */
1495 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1496 			if (msg->hdr.status == CTL_SUCCESS)
1497 				io->io_hdr.status = msg->hdr.status;
1498 
1499 			if (msg->dt.sg_sequence == 0) {
1500 #ifdef CTL_TIME_IO
1501 				getbinuptime(&io->io_hdr.dma_start_bt);
1502 #endif
1503 				i = msg->dt.kern_sg_entries +
1504 				    msg->dt.kern_data_len /
1505 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1506 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1507 				    M_WAITOK | M_ZERO);
1508 				CTL_RSGL(io) = sgl;
1509 				CTL_LSGL(io) = &sgl[msg->dt.kern_sg_entries];
1510 
1511 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1512 
1513 				io->scsiio.kern_sg_entries =
1514 					msg->dt.kern_sg_entries;
1515 				io->scsiio.rem_sg_entries =
1516 					msg->dt.kern_sg_entries;
1517 				io->scsiio.kern_data_len =
1518 					msg->dt.kern_data_len;
1519 				io->scsiio.kern_total_len =
1520 					msg->dt.kern_total_len;
1521 				io->scsiio.kern_data_resid =
1522 					msg->dt.kern_data_resid;
1523 				io->scsiio.kern_rel_offset =
1524 					msg->dt.kern_rel_offset;
1525 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1526 				io->io_hdr.flags |= msg->dt.flags &
1527 				    CTL_FLAG_BUS_ADDR;
1528 			} else
1529 				sgl = (struct ctl_sg_entry *)
1530 					io->scsiio.kern_data_ptr;
1531 
1532 			for (i = msg->dt.sent_sg_entries, j = 0;
1533 			     i < (msg->dt.sent_sg_entries +
1534 			     msg->dt.cur_sg_entries); i++, j++) {
1535 				sgl[i].addr = msg->dt.sg_list[j].addr;
1536 				sgl[i].len = msg->dt.sg_list[j].len;
1537 			}
1538 
1539 			/*
1540 			 * If this is the last piece of the I/O, we've got
1541 			 * the full S/G list.  Queue processing in the thread.
1542 			 * Otherwise wait for the next piece.
1543 			 */
1544 			if (msg->dt.sg_last != 0)
1545 				ctl_enqueue_isc(io);
1546 			break;
1547 		}
1548 		/* Performed on the Serializing (primary) SC, XFER mode only */
1549 		case CTL_MSG_DATAMOVE_DONE: {
1550 			if (msg->hdr.serializing_sc == NULL) {
1551 				printf("%s: serializing_sc == NULL!\n",
1552 				       __func__);
1553 				/* XXX KDM now what? */
1554 				break;
1555 			}
1556 			/*
1557 			 * We grab the sense information here in case
1558 			 * there was a failure, so we can return status
1559 			 * back to the initiator.
1560 			 */
1561 			io = msg->hdr.serializing_sc;
1562 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1563 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1564 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1565 			io->io_hdr.port_status = msg->scsi.port_status;
1566 			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1567 			if (msg->hdr.status != CTL_STATUS_NONE) {
1568 				io->io_hdr.status = msg->hdr.status;
1569 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1570 				io->scsiio.sense_len = msg->scsi.sense_len;
1571 				memcpy(&io->scsiio.sense_data,
1572 				    &msg->scsi.sense_data,
1573 				    msg->scsi.sense_len);
1574 				if (msg->hdr.status == CTL_SUCCESS)
1575 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1576 			}
1577 			ctl_enqueue_isc(io);
1578 			break;
1579 		}
1580 
1581 		/* Preformed on Originating SC, SER_ONLY mode */
1582 		case CTL_MSG_R2R:
1583 			io = msg->hdr.original_sc;
1584 			if (io == NULL) {
1585 				printf("%s: original_sc == NULL!\n",
1586 				    __func__);
1587 				break;
1588 			}
1589 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1590 			io->io_hdr.msg_type = CTL_MSG_R2R;
1591 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1592 			ctl_enqueue_isc(io);
1593 			break;
1594 
1595 		/*
1596 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1597 		 * mode.
1598 		 * Performed on the Originating (i.e. secondary) SC in XFER
1599 		 * mode
1600 		 */
1601 		case CTL_MSG_FINISH_IO:
1602 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1603 				ctl_isc_handler_finish_xfer(softc, msg);
1604 			else
1605 				ctl_isc_handler_finish_ser_only(softc, msg);
1606 			break;
1607 
1608 		/* Preformed on Originating SC */
1609 		case CTL_MSG_BAD_JUJU:
1610 			io = msg->hdr.original_sc;
1611 			if (io == NULL) {
1612 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1613 				       __func__);
1614 				break;
1615 			}
1616 			ctl_copy_sense_data(msg, io);
1617 			/*
1618 			 * IO should have already been cleaned up on other
1619 			 * SC so clear this flag so we won't send a message
1620 			 * back to finish the IO there.
1621 			 */
1622 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1623 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1624 
1625 			/* io = msg->hdr.serializing_sc; */
1626 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1627 			ctl_enqueue_isc(io);
1628 			break;
1629 
1630 		/* Handle resets sent from the other side */
1631 		case CTL_MSG_MANAGE_TASKS: {
1632 			struct ctl_taskio *taskio;
1633 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1634 			    softc->othersc_pool);
1635 			ctl_zero_io((union ctl_io *)taskio);
1636 			taskio->io_hdr.io_type = CTL_IO_TASK;
1637 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1638 			taskio->io_hdr.nexus = msg->hdr.nexus;
1639 			taskio->task_action = msg->task.task_action;
1640 			taskio->tag_num = msg->task.tag_num;
1641 			taskio->tag_type = msg->task.tag_type;
1642 #ifdef CTL_TIME_IO
1643 			taskio->io_hdr.start_time = time_uptime;
1644 			getbinuptime(&taskio->io_hdr.start_bt);
1645 #endif /* CTL_TIME_IO */
1646 			ctl_run_task((union ctl_io *)taskio);
1647 			break;
1648 		}
1649 		/* Persistent Reserve action which needs attention */
1650 		case CTL_MSG_PERS_ACTION:
1651 			presio = (struct ctl_prio *)ctl_alloc_io(
1652 			    softc->othersc_pool);
1653 			ctl_zero_io((union ctl_io *)presio);
1654 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1655 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1656 			presio->io_hdr.nexus = msg->hdr.nexus;
1657 			presio->pr_msg = msg->pr;
1658 			ctl_enqueue_isc((union ctl_io *)presio);
1659 			break;
1660 		case CTL_MSG_UA:
1661 			ctl_isc_ua(softc, msg, param);
1662 			break;
1663 		case CTL_MSG_PORT_SYNC:
1664 			ctl_isc_port_sync(softc, msg, param);
1665 			break;
1666 		case CTL_MSG_LUN_SYNC:
1667 			ctl_isc_lun_sync(softc, msg, param);
1668 			break;
1669 		case CTL_MSG_IID_SYNC:
1670 			ctl_isc_iid_sync(softc, msg, param);
1671 			break;
1672 		case CTL_MSG_LOGIN:
1673 			ctl_isc_login(softc, msg, param);
1674 			break;
1675 		case CTL_MSG_MODE_SYNC:
1676 			ctl_isc_mode_sync(softc, msg, param);
1677 			break;
1678 		default:
1679 			printf("Received HA message of unknown type %d\n",
1680 			    msg->hdr.msg_type);
1681 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1682 			break;
1683 		}
1684 		if (msg != &msgbuf)
1685 			free(msg, M_CTL);
1686 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1687 		printf("CTL: HA link status changed from %d to %d\n",
1688 		    softc->ha_link, param);
1689 		if (param == softc->ha_link)
1690 			return;
1691 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1692 			softc->ha_link = param;
1693 			ctl_isc_ha_link_down(softc);
1694 		} else {
1695 			softc->ha_link = param;
1696 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1697 				ctl_isc_ha_link_up(softc);
1698 		}
1699 		return;
1700 	} else {
1701 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1702 		return;
1703 	}
1704 }
1705 
1706 static void
1707 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1708 {
1709 
1710 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1711 	    src->scsi.sense_len);
1712 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1713 	dest->scsiio.sense_len = src->scsi.sense_len;
1714 	dest->io_hdr.status = src->hdr.status;
1715 }
1716 
1717 static void
1718 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1719 {
1720 
1721 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1722 	    src->scsiio.sense_len);
1723 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1724 	dest->scsi.sense_len = src->scsiio.sense_len;
1725 	dest->hdr.status = src->io_hdr.status;
1726 }
1727 
1728 void
1729 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1730 {
1731 	struct ctl_softc *softc = lun->ctl_softc;
1732 	ctl_ua_type *pu;
1733 
1734 	if (initidx < softc->init_min || initidx >= softc->init_max)
1735 		return;
1736 	mtx_assert(&lun->lun_lock, MA_OWNED);
1737 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1738 	if (pu == NULL)
1739 		return;
1740 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1741 }
1742 
1743 void
1744 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1745 {
1746 	int i;
1747 
1748 	mtx_assert(&lun->lun_lock, MA_OWNED);
1749 	if (lun->pending_ua[port] == NULL)
1750 		return;
1751 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1752 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1753 			continue;
1754 		lun->pending_ua[port][i] |= ua;
1755 	}
1756 }
1757 
1758 void
1759 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1760 {
1761 	struct ctl_softc *softc = lun->ctl_softc;
1762 	int i;
1763 
1764 	mtx_assert(&lun->lun_lock, MA_OWNED);
1765 	for (i = softc->port_min; i < softc->port_max; i++)
1766 		ctl_est_ua_port(lun, i, except, ua);
1767 }
1768 
1769 void
1770 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1771 {
1772 	struct ctl_softc *softc = lun->ctl_softc;
1773 	ctl_ua_type *pu;
1774 
1775 	if (initidx < softc->init_min || initidx >= softc->init_max)
1776 		return;
1777 	mtx_assert(&lun->lun_lock, MA_OWNED);
1778 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1779 	if (pu == NULL)
1780 		return;
1781 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1782 }
1783 
1784 void
1785 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1786 {
1787 	struct ctl_softc *softc = lun->ctl_softc;
1788 	int i, j;
1789 
1790 	mtx_assert(&lun->lun_lock, MA_OWNED);
1791 	for (i = softc->port_min; i < softc->port_max; i++) {
1792 		if (lun->pending_ua[i] == NULL)
1793 			continue;
1794 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1795 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1796 				continue;
1797 			lun->pending_ua[i][j] &= ~ua;
1798 		}
1799 	}
1800 }
1801 
1802 void
1803 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1804     ctl_ua_type ua_type)
1805 {
1806 	struct ctl_lun *lun;
1807 
1808 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1809 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1810 		mtx_lock(&lun->lun_lock);
1811 		ctl_clr_ua(lun, initidx, ua_type);
1812 		mtx_unlock(&lun->lun_lock);
1813 	}
1814 }
1815 
1816 static int
1817 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1818 {
1819 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1820 	struct ctl_lun *lun;
1821 	struct ctl_lun_req ireq;
1822 	int error, value;
1823 
1824 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1825 	error = sysctl_handle_int(oidp, &value, 0, req);
1826 	if ((error != 0) || (req->newptr == NULL))
1827 		return (error);
1828 
1829 	mtx_lock(&softc->ctl_lock);
1830 	if (value == 0)
1831 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1832 	else
1833 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1834 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1835 		mtx_unlock(&softc->ctl_lock);
1836 		bzero(&ireq, sizeof(ireq));
1837 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1838 		ireq.reqdata.modify.lun_id = lun->lun;
1839 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1840 		    curthread);
1841 		if (ireq.status != CTL_LUN_OK) {
1842 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1843 			    __func__, ireq.status, ireq.error_str);
1844 		}
1845 		mtx_lock(&softc->ctl_lock);
1846 	}
1847 	mtx_unlock(&softc->ctl_lock);
1848 	return (0);
1849 }
1850 
1851 static int
1852 ctl_init(void)
1853 {
1854 	struct make_dev_args args;
1855 	struct ctl_softc *softc;
1856 	int i, error;
1857 
1858 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1859 			       M_WAITOK | M_ZERO);
1860 
1861 	make_dev_args_init(&args);
1862 	args.mda_devsw = &ctl_cdevsw;
1863 	args.mda_uid = UID_ROOT;
1864 	args.mda_gid = GID_OPERATOR;
1865 	args.mda_mode = 0600;
1866 	args.mda_si_drv1 = softc;
1867 	args.mda_si_drv2 = NULL;
1868 	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1869 	if (error != 0) {
1870 		free(softc, M_DEVBUF);
1871 		control_softc = NULL;
1872 		return (error);
1873 	}
1874 
1875 	sysctl_ctx_init(&softc->sysctl_ctx);
1876 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1877 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1878 		CTLFLAG_RD, 0, "CAM Target Layer");
1879 
1880 	if (softc->sysctl_tree == NULL) {
1881 		printf("%s: unable to allocate sysctl tree\n", __func__);
1882 		destroy_dev(softc->dev);
1883 		free(softc, M_DEVBUF);
1884 		control_softc = NULL;
1885 		return (ENOMEM);
1886 	}
1887 
1888 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1889 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1890 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1891 	softc->flags = 0;
1892 
1893 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1894 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1895 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1896 
1897 	if (ctl_max_luns <= 0 || powerof2(ctl_max_luns) == 0) {
1898 		printf("Bad value %d for kern.cam.ctl.max_luns, must be a power of two, using %d\n",
1899 		    ctl_max_luns, CTL_DEFAULT_MAX_LUNS);
1900 		ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
1901 	}
1902 	softc->ctl_luns = malloc(sizeof(struct ctl_lun *) * ctl_max_luns,
1903 	    M_DEVBUF, M_WAITOK | M_ZERO);
1904 	softc->ctl_lun_mask = malloc(sizeof(uint32_t) *
1905 	    ((ctl_max_luns + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1906 	if (ctl_max_ports <= 0 || powerof2(ctl_max_ports) == 0) {
1907 		printf("Bad value %d for kern.cam.ctl.max_ports, must be a power of two, using %d\n",
1908 		    ctl_max_ports, CTL_DEFAULT_MAX_PORTS);
1909 		ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
1910 	}
1911 	softc->ctl_port_mask = malloc(sizeof(uint32_t) *
1912 	  ((ctl_max_ports + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1913 	softc->ctl_ports = malloc(sizeof(struct ctl_port *) * ctl_max_ports,
1914 	     M_DEVBUF, M_WAITOK | M_ZERO);
1915 
1916 
1917 	/*
1918 	 * In Copan's HA scheme, the "master" and "slave" roles are
1919 	 * figured out through the slot the controller is in.  Although it
1920 	 * is an active/active system, someone has to be in charge.
1921 	 */
1922 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1923 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1924 	    "HA head ID (0 - no HA)");
1925 	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1926 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1927 		softc->is_single = 1;
1928 		softc->port_cnt = ctl_max_ports;
1929 		softc->port_min = 0;
1930 	} else {
1931 		softc->port_cnt = ctl_max_ports / NUM_HA_SHELVES;
1932 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1933 	}
1934 	softc->port_max = softc->port_min + softc->port_cnt;
1935 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1936 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1937 
1938 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1939 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1940 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1941 
1942 	STAILQ_INIT(&softc->lun_list);
1943 	STAILQ_INIT(&softc->pending_lun_queue);
1944 	STAILQ_INIT(&softc->fe_list);
1945 	STAILQ_INIT(&softc->port_list);
1946 	STAILQ_INIT(&softc->be_list);
1947 	ctl_tpc_init(softc);
1948 
1949 	if (worker_threads <= 0)
1950 		worker_threads = max(1, mp_ncpus / 4);
1951 	if (worker_threads > CTL_MAX_THREADS)
1952 		worker_threads = CTL_MAX_THREADS;
1953 
1954 	for (i = 0; i < worker_threads; i++) {
1955 		struct ctl_thread *thr = &softc->threads[i];
1956 
1957 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1958 		thr->ctl_softc = softc;
1959 		STAILQ_INIT(&thr->incoming_queue);
1960 		STAILQ_INIT(&thr->rtr_queue);
1961 		STAILQ_INIT(&thr->done_queue);
1962 		STAILQ_INIT(&thr->isc_queue);
1963 
1964 		error = kproc_kthread_add(ctl_work_thread, thr,
1965 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1966 		if (error != 0) {
1967 			printf("error creating CTL work thread!\n");
1968 			return (error);
1969 		}
1970 	}
1971 	error = kproc_kthread_add(ctl_lun_thread, softc,
1972 	    &softc->ctl_proc, &softc->lun_thread, 0, 0, "ctl", "lun");
1973 	if (error != 0) {
1974 		printf("error creating CTL lun thread!\n");
1975 		return (error);
1976 	}
1977 	error = kproc_kthread_add(ctl_thresh_thread, softc,
1978 	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
1979 	if (error != 0) {
1980 		printf("error creating CTL threshold thread!\n");
1981 		return (error);
1982 	}
1983 
1984 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1985 	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1986 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1987 
1988 	if (softc->is_single == 0) {
1989 		if (ctl_frontend_register(&ha_frontend) != 0)
1990 			softc->is_single = 1;
1991 	}
1992 	return (0);
1993 }
1994 
1995 static int
1996 ctl_shutdown(void)
1997 {
1998 	struct ctl_softc *softc = control_softc;
1999 	int i;
2000 
2001 	if (softc->is_single == 0)
2002 		ctl_frontend_deregister(&ha_frontend);
2003 
2004 	destroy_dev(softc->dev);
2005 
2006 	/* Shutdown CTL threads. */
2007 	softc->shutdown = 1;
2008 	for (i = 0; i < worker_threads; i++) {
2009 		struct ctl_thread *thr = &softc->threads[i];
2010 		while (thr->thread != NULL) {
2011 			wakeup(thr);
2012 			if (thr->thread != NULL)
2013 				pause("CTL thr shutdown", 1);
2014 		}
2015 		mtx_destroy(&thr->queue_lock);
2016 	}
2017 	while (softc->lun_thread != NULL) {
2018 		wakeup(&softc->pending_lun_queue);
2019 		if (softc->lun_thread != NULL)
2020 			pause("CTL thr shutdown", 1);
2021 	}
2022 	while (softc->thresh_thread != NULL) {
2023 		wakeup(softc->thresh_thread);
2024 		if (softc->thresh_thread != NULL)
2025 			pause("CTL thr shutdown", 1);
2026 	}
2027 
2028 	ctl_tpc_shutdown(softc);
2029 	uma_zdestroy(softc->io_zone);
2030 	mtx_destroy(&softc->ctl_lock);
2031 
2032 	free(softc->ctl_luns, M_DEVBUF);
2033 	free(softc->ctl_lun_mask, M_DEVBUF);
2034 	free(softc->ctl_port_mask, M_DEVBUF);
2035 	free(softc->ctl_ports, M_DEVBUF);
2036 
2037 	sysctl_ctx_free(&softc->sysctl_ctx);
2038 
2039 	free(softc, M_DEVBUF);
2040 	control_softc = NULL;
2041 	return (0);
2042 }
2043 
2044 static int
2045 ctl_module_event_handler(module_t mod, int what, void *arg)
2046 {
2047 
2048 	switch (what) {
2049 	case MOD_LOAD:
2050 		return (ctl_init());
2051 	case MOD_UNLOAD:
2052 		return (ctl_shutdown());
2053 	default:
2054 		return (EOPNOTSUPP);
2055 	}
2056 }
2057 
2058 /*
2059  * XXX KDM should we do some access checks here?  Bump a reference count to
2060  * prevent a CTL module from being unloaded while someone has it open?
2061  */
2062 static int
2063 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2064 {
2065 	return (0);
2066 }
2067 
2068 static int
2069 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2070 {
2071 	return (0);
2072 }
2073 
2074 /*
2075  * Remove an initiator by port number and initiator ID.
2076  * Returns 0 for success, -1 for failure.
2077  */
2078 int
2079 ctl_remove_initiator(struct ctl_port *port, int iid)
2080 {
2081 	struct ctl_softc *softc = port->ctl_softc;
2082 	int last;
2083 
2084 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2085 
2086 	if (iid > CTL_MAX_INIT_PER_PORT) {
2087 		printf("%s: initiator ID %u > maximun %u!\n",
2088 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2089 		return (-1);
2090 	}
2091 
2092 	mtx_lock(&softc->ctl_lock);
2093 	last = (--port->wwpn_iid[iid].in_use == 0);
2094 	port->wwpn_iid[iid].last_use = time_uptime;
2095 	mtx_unlock(&softc->ctl_lock);
2096 	if (last)
2097 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2098 	ctl_isc_announce_iid(port, iid);
2099 
2100 	return (0);
2101 }
2102 
2103 /*
2104  * Add an initiator to the initiator map.
2105  * Returns iid for success, < 0 for failure.
2106  */
2107 int
2108 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2109 {
2110 	struct ctl_softc *softc = port->ctl_softc;
2111 	time_t best_time;
2112 	int i, best;
2113 
2114 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2115 
2116 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2117 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2118 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2119 		free(name, M_CTL);
2120 		return (-1);
2121 	}
2122 
2123 	mtx_lock(&softc->ctl_lock);
2124 
2125 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2126 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2127 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2128 				iid = i;
2129 				break;
2130 			}
2131 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2132 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2133 				iid = i;
2134 				break;
2135 			}
2136 		}
2137 	}
2138 
2139 	if (iid < 0) {
2140 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2141 			if (port->wwpn_iid[i].in_use == 0 &&
2142 			    port->wwpn_iid[i].wwpn == 0 &&
2143 			    port->wwpn_iid[i].name == NULL) {
2144 				iid = i;
2145 				break;
2146 			}
2147 		}
2148 	}
2149 
2150 	if (iid < 0) {
2151 		best = -1;
2152 		best_time = INT32_MAX;
2153 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2154 			if (port->wwpn_iid[i].in_use == 0) {
2155 				if (port->wwpn_iid[i].last_use < best_time) {
2156 					best = i;
2157 					best_time = port->wwpn_iid[i].last_use;
2158 				}
2159 			}
2160 		}
2161 		iid = best;
2162 	}
2163 
2164 	if (iid < 0) {
2165 		mtx_unlock(&softc->ctl_lock);
2166 		free(name, M_CTL);
2167 		return (-2);
2168 	}
2169 
2170 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2171 		/*
2172 		 * This is not an error yet.
2173 		 */
2174 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2175 #if 0
2176 			printf("%s: port %d iid %u WWPN %#jx arrived"
2177 			    " again\n", __func__, port->targ_port,
2178 			    iid, (uintmax_t)wwpn);
2179 #endif
2180 			goto take;
2181 		}
2182 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2183 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2184 #if 0
2185 			printf("%s: port %d iid %u name '%s' arrived"
2186 			    " again\n", __func__, port->targ_port,
2187 			    iid, name);
2188 #endif
2189 			goto take;
2190 		}
2191 
2192 		/*
2193 		 * This is an error, but what do we do about it?  The
2194 		 * driver is telling us we have a new WWPN for this
2195 		 * initiator ID, so we pretty much need to use it.
2196 		 */
2197 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2198 		    " but WWPN %#jx '%s' is still at that address\n",
2199 		    __func__, port->targ_port, iid, wwpn, name,
2200 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2201 		    port->wwpn_iid[iid].name);
2202 	}
2203 take:
2204 	free(port->wwpn_iid[iid].name, M_CTL);
2205 	port->wwpn_iid[iid].name = name;
2206 	port->wwpn_iid[iid].wwpn = wwpn;
2207 	port->wwpn_iid[iid].in_use++;
2208 	mtx_unlock(&softc->ctl_lock);
2209 	ctl_isc_announce_iid(port, iid);
2210 
2211 	return (iid);
2212 }
2213 
2214 static int
2215 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2216 {
2217 	int len;
2218 
2219 	switch (port->port_type) {
2220 	case CTL_PORT_FC:
2221 	{
2222 		struct scsi_transportid_fcp *id =
2223 		    (struct scsi_transportid_fcp *)buf;
2224 		if (port->wwpn_iid[iid].wwpn == 0)
2225 			return (0);
2226 		memset(id, 0, sizeof(*id));
2227 		id->format_protocol = SCSI_PROTO_FC;
2228 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2229 		return (sizeof(*id));
2230 	}
2231 	case CTL_PORT_ISCSI:
2232 	{
2233 		struct scsi_transportid_iscsi_port *id =
2234 		    (struct scsi_transportid_iscsi_port *)buf;
2235 		if (port->wwpn_iid[iid].name == NULL)
2236 			return (0);
2237 		memset(id, 0, 256);
2238 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2239 		    SCSI_PROTO_ISCSI;
2240 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2241 		len = roundup2(min(len, 252), 4);
2242 		scsi_ulto2b(len, id->additional_length);
2243 		return (sizeof(*id) + len);
2244 	}
2245 	case CTL_PORT_SAS:
2246 	{
2247 		struct scsi_transportid_sas *id =
2248 		    (struct scsi_transportid_sas *)buf;
2249 		if (port->wwpn_iid[iid].wwpn == 0)
2250 			return (0);
2251 		memset(id, 0, sizeof(*id));
2252 		id->format_protocol = SCSI_PROTO_SAS;
2253 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2254 		return (sizeof(*id));
2255 	}
2256 	default:
2257 	{
2258 		struct scsi_transportid_spi *id =
2259 		    (struct scsi_transportid_spi *)buf;
2260 		memset(id, 0, sizeof(*id));
2261 		id->format_protocol = SCSI_PROTO_SPI;
2262 		scsi_ulto2b(iid, id->scsi_addr);
2263 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2264 		return (sizeof(*id));
2265 	}
2266 	}
2267 }
2268 
2269 /*
2270  * Serialize a command that went down the "wrong" side, and so was sent to
2271  * this controller for execution.  The logic is a little different than the
2272  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2273  * sent back to the other side, but in the success case, we execute the
2274  * command on this side (XFER mode) or tell the other side to execute it
2275  * (SER_ONLY mode).
2276  */
2277 static void
2278 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2279 {
2280 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2281 	struct ctl_port *port = CTL_PORT(ctsio);
2282 	union ctl_ha_msg msg_info;
2283 	struct ctl_lun *lun;
2284 	const struct ctl_cmd_entry *entry;
2285 	union ctl_io *bio;
2286 	uint32_t targ_lun;
2287 
2288 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2289 
2290 	/* Make sure that we know about this port. */
2291 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2292 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2293 					 /*retry_count*/ 1);
2294 		goto badjuju;
2295 	}
2296 
2297 	/* Make sure that we know about this LUN. */
2298 	mtx_lock(&softc->ctl_lock);
2299 	if (targ_lun >= ctl_max_luns ||
2300 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2301 		mtx_unlock(&softc->ctl_lock);
2302 
2303 		/*
2304 		 * The other node would not send this request to us unless
2305 		 * received announce that we are primary node for this LUN.
2306 		 * If this LUN does not exist now, it is probably result of
2307 		 * a race, so respond to initiator in the most opaque way.
2308 		 */
2309 		ctl_set_busy(ctsio);
2310 		goto badjuju;
2311 	}
2312 	mtx_lock(&lun->lun_lock);
2313 	mtx_unlock(&softc->ctl_lock);
2314 
2315 	/*
2316 	 * If the LUN is invalid, pretend that it doesn't exist.
2317 	 * It will go away as soon as all pending I/Os completed.
2318 	 */
2319 	if (lun->flags & CTL_LUN_DISABLED) {
2320 		mtx_unlock(&lun->lun_lock);
2321 		ctl_set_busy(ctsio);
2322 		goto badjuju;
2323 	}
2324 
2325 	entry = ctl_get_cmd_entry(ctsio, NULL);
2326 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2327 		mtx_unlock(&lun->lun_lock);
2328 		goto badjuju;
2329 	}
2330 
2331 	CTL_LUN(ctsio) = lun;
2332 	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2333 
2334 	/*
2335 	 * Every I/O goes into the OOA queue for a
2336 	 * particular LUN, and stays there until completion.
2337 	 */
2338 #ifdef CTL_TIME_IO
2339 	if (TAILQ_EMPTY(&lun->ooa_queue))
2340 		lun->idle_time += getsbinuptime() - lun->last_busy;
2341 #endif
2342 	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2343 
2344 	bio = (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq, ooa_links);
2345 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
2346 	case CTL_ACTION_BLOCK:
2347 		ctsio->io_hdr.blocker = bio;
2348 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
2349 				  blocked_links);
2350 		mtx_unlock(&lun->lun_lock);
2351 		break;
2352 	case CTL_ACTION_PASS:
2353 	case CTL_ACTION_SKIP:
2354 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2355 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2356 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2357 			mtx_unlock(&lun->lun_lock);
2358 		} else {
2359 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2360 			mtx_unlock(&lun->lun_lock);
2361 
2362 			/* send msg back to other side */
2363 			msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2364 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2365 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2366 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2367 			    sizeof(msg_info.hdr), M_WAITOK);
2368 		}
2369 		break;
2370 	case CTL_ACTION_OVERLAP:
2371 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2372 		mtx_unlock(&lun->lun_lock);
2373 		ctl_set_overlapped_cmd(ctsio);
2374 		goto badjuju;
2375 	case CTL_ACTION_OVERLAP_TAG:
2376 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2377 		mtx_unlock(&lun->lun_lock);
2378 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2379 		goto badjuju;
2380 	case CTL_ACTION_ERROR:
2381 	default:
2382 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2383 		mtx_unlock(&lun->lun_lock);
2384 
2385 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2386 					 /*retry_count*/ 0);
2387 badjuju:
2388 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2389 		msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2390 		msg_info.hdr.serializing_sc = NULL;
2391 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2392 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2393 		    sizeof(msg_info.scsi), M_WAITOK);
2394 		ctl_free_io((union ctl_io *)ctsio);
2395 		break;
2396 	}
2397 }
2398 
2399 /*
2400  * Returns 0 for success, errno for failure.
2401  */
2402 static void
2403 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2404 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2405 {
2406 	union ctl_io *io;
2407 
2408 	mtx_lock(&lun->lun_lock);
2409 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2410 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2411 	     ooa_links)) {
2412 		struct ctl_ooa_entry *entry;
2413 
2414 		/*
2415 		 * If we've got more than we can fit, just count the
2416 		 * remaining entries.
2417 		 */
2418 		if (*cur_fill_num >= ooa_hdr->alloc_num)
2419 			continue;
2420 
2421 		entry = &kern_entries[*cur_fill_num];
2422 
2423 		entry->tag_num = io->scsiio.tag_num;
2424 		entry->lun_num = lun->lun;
2425 #ifdef CTL_TIME_IO
2426 		entry->start_bt = io->io_hdr.start_bt;
2427 #endif
2428 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2429 		entry->cdb_len = io->scsiio.cdb_len;
2430 		if (io->io_hdr.blocker != NULL)
2431 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2432 
2433 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2434 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2435 
2436 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2437 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2438 
2439 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2440 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2441 
2442 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2443 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2444 	}
2445 	mtx_unlock(&lun->lun_lock);
2446 }
2447 
2448 /*
2449  * Escape characters that are illegal or not recommended in XML.
2450  */
2451 int
2452 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2453 {
2454 	char *end = str + size;
2455 	int retval;
2456 
2457 	retval = 0;
2458 
2459 	for (; *str && str < end; str++) {
2460 		switch (*str) {
2461 		case '&':
2462 			retval = sbuf_printf(sb, "&amp;");
2463 			break;
2464 		case '>':
2465 			retval = sbuf_printf(sb, "&gt;");
2466 			break;
2467 		case '<':
2468 			retval = sbuf_printf(sb, "&lt;");
2469 			break;
2470 		default:
2471 			retval = sbuf_putc(sb, *str);
2472 			break;
2473 		}
2474 
2475 		if (retval != 0)
2476 			break;
2477 
2478 	}
2479 
2480 	return (retval);
2481 }
2482 
2483 static void
2484 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2485 {
2486 	struct scsi_vpd_id_descriptor *desc;
2487 	int i;
2488 
2489 	if (id == NULL || id->len < 4)
2490 		return;
2491 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2492 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2493 	case SVPD_ID_TYPE_T10:
2494 		sbuf_printf(sb, "t10.");
2495 		break;
2496 	case SVPD_ID_TYPE_EUI64:
2497 		sbuf_printf(sb, "eui.");
2498 		break;
2499 	case SVPD_ID_TYPE_NAA:
2500 		sbuf_printf(sb, "naa.");
2501 		break;
2502 	case SVPD_ID_TYPE_SCSI_NAME:
2503 		break;
2504 	}
2505 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2506 	case SVPD_ID_CODESET_BINARY:
2507 		for (i = 0; i < desc->length; i++)
2508 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2509 		break;
2510 	case SVPD_ID_CODESET_ASCII:
2511 		sbuf_printf(sb, "%.*s", (int)desc->length,
2512 		    (char *)desc->identifier);
2513 		break;
2514 	case SVPD_ID_CODESET_UTF8:
2515 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2516 		break;
2517 	}
2518 }
2519 
2520 static int
2521 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2522 	  struct thread *td)
2523 {
2524 	struct ctl_softc *softc = dev->si_drv1;
2525 	struct ctl_port *port;
2526 	struct ctl_lun *lun;
2527 	int retval;
2528 
2529 	retval = 0;
2530 
2531 	switch (cmd) {
2532 	case CTL_IO:
2533 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2534 		break;
2535 	case CTL_ENABLE_PORT:
2536 	case CTL_DISABLE_PORT:
2537 	case CTL_SET_PORT_WWNS: {
2538 		struct ctl_port *port;
2539 		struct ctl_port_entry *entry;
2540 
2541 		entry = (struct ctl_port_entry *)addr;
2542 
2543 		mtx_lock(&softc->ctl_lock);
2544 		STAILQ_FOREACH(port, &softc->port_list, links) {
2545 			int action, done;
2546 
2547 			if (port->targ_port < softc->port_min ||
2548 			    port->targ_port >= softc->port_max)
2549 				continue;
2550 
2551 			action = 0;
2552 			done = 0;
2553 			if ((entry->port_type == CTL_PORT_NONE)
2554 			 && (entry->targ_port == port->targ_port)) {
2555 				/*
2556 				 * If the user only wants to enable or
2557 				 * disable or set WWNs on a specific port,
2558 				 * do the operation and we're done.
2559 				 */
2560 				action = 1;
2561 				done = 1;
2562 			} else if (entry->port_type & port->port_type) {
2563 				/*
2564 				 * Compare the user's type mask with the
2565 				 * particular frontend type to see if we
2566 				 * have a match.
2567 				 */
2568 				action = 1;
2569 				done = 0;
2570 
2571 				/*
2572 				 * Make sure the user isn't trying to set
2573 				 * WWNs on multiple ports at the same time.
2574 				 */
2575 				if (cmd == CTL_SET_PORT_WWNS) {
2576 					printf("%s: Can't set WWNs on "
2577 					       "multiple ports\n", __func__);
2578 					retval = EINVAL;
2579 					break;
2580 				}
2581 			}
2582 			if (action == 0)
2583 				continue;
2584 
2585 			/*
2586 			 * XXX KDM we have to drop the lock here, because
2587 			 * the online/offline operations can potentially
2588 			 * block.  We need to reference count the frontends
2589 			 * so they can't go away,
2590 			 */
2591 			if (cmd == CTL_ENABLE_PORT) {
2592 				mtx_unlock(&softc->ctl_lock);
2593 				ctl_port_online(port);
2594 				mtx_lock(&softc->ctl_lock);
2595 			} else if (cmd == CTL_DISABLE_PORT) {
2596 				mtx_unlock(&softc->ctl_lock);
2597 				ctl_port_offline(port);
2598 				mtx_lock(&softc->ctl_lock);
2599 			} else if (cmd == CTL_SET_PORT_WWNS) {
2600 				ctl_port_set_wwns(port,
2601 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2602 				    1 : 0, entry->wwnn,
2603 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2604 				    1 : 0, entry->wwpn);
2605 			}
2606 			if (done != 0)
2607 				break;
2608 		}
2609 		mtx_unlock(&softc->ctl_lock);
2610 		break;
2611 	}
2612 	case CTL_GET_OOA: {
2613 		struct ctl_ooa *ooa_hdr;
2614 		struct ctl_ooa_entry *entries;
2615 		uint32_t cur_fill_num;
2616 
2617 		ooa_hdr = (struct ctl_ooa *)addr;
2618 
2619 		if ((ooa_hdr->alloc_len == 0)
2620 		 || (ooa_hdr->alloc_num == 0)) {
2621 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2622 			       "must be non-zero\n", __func__,
2623 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2624 			retval = EINVAL;
2625 			break;
2626 		}
2627 
2628 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2629 		    sizeof(struct ctl_ooa_entry))) {
2630 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2631 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2632 			       __func__, ooa_hdr->alloc_len,
2633 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2634 			retval = EINVAL;
2635 			break;
2636 		}
2637 
2638 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2639 		if (entries == NULL) {
2640 			printf("%s: could not allocate %d bytes for OOA "
2641 			       "dump\n", __func__, ooa_hdr->alloc_len);
2642 			retval = ENOMEM;
2643 			break;
2644 		}
2645 
2646 		mtx_lock(&softc->ctl_lock);
2647 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2648 		    (ooa_hdr->lun_num >= ctl_max_luns ||
2649 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2650 			mtx_unlock(&softc->ctl_lock);
2651 			free(entries, M_CTL);
2652 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2653 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2654 			retval = EINVAL;
2655 			break;
2656 		}
2657 
2658 		cur_fill_num = 0;
2659 
2660 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2661 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2662 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2663 				    ooa_hdr, entries);
2664 			}
2665 		} else {
2666 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2667 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2668 			    entries);
2669 		}
2670 		mtx_unlock(&softc->ctl_lock);
2671 
2672 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2673 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2674 			sizeof(struct ctl_ooa_entry);
2675 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2676 		if (retval != 0) {
2677 			printf("%s: error copying out %d bytes for OOA dump\n",
2678 			       __func__, ooa_hdr->fill_len);
2679 		}
2680 
2681 		getbinuptime(&ooa_hdr->cur_bt);
2682 
2683 		if (cur_fill_num > ooa_hdr->alloc_num) {
2684 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2685 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2686 		} else {
2687 			ooa_hdr->dropped_num = 0;
2688 			ooa_hdr->status = CTL_OOA_OK;
2689 		}
2690 
2691 		free(entries, M_CTL);
2692 		break;
2693 	}
2694 	case CTL_DELAY_IO: {
2695 		struct ctl_io_delay_info *delay_info;
2696 
2697 		delay_info = (struct ctl_io_delay_info *)addr;
2698 
2699 #ifdef CTL_IO_DELAY
2700 		mtx_lock(&softc->ctl_lock);
2701 		if (delay_info->lun_id >= ctl_max_luns ||
2702 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2703 			mtx_unlock(&softc->ctl_lock);
2704 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2705 			break;
2706 		}
2707 		mtx_lock(&lun->lun_lock);
2708 		mtx_unlock(&softc->ctl_lock);
2709 		delay_info->status = CTL_DELAY_STATUS_OK;
2710 		switch (delay_info->delay_type) {
2711 		case CTL_DELAY_TYPE_CONT:
2712 		case CTL_DELAY_TYPE_ONESHOT:
2713 			break;
2714 		default:
2715 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2716 			break;
2717 		}
2718 		switch (delay_info->delay_loc) {
2719 		case CTL_DELAY_LOC_DATAMOVE:
2720 			lun->delay_info.datamove_type = delay_info->delay_type;
2721 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2722 			break;
2723 		case CTL_DELAY_LOC_DONE:
2724 			lun->delay_info.done_type = delay_info->delay_type;
2725 			lun->delay_info.done_delay = delay_info->delay_secs;
2726 			break;
2727 		default:
2728 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2729 			break;
2730 		}
2731 		mtx_unlock(&lun->lun_lock);
2732 #else
2733 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2734 #endif /* CTL_IO_DELAY */
2735 		break;
2736 	}
2737 	case CTL_ERROR_INJECT: {
2738 		struct ctl_error_desc *err_desc, *new_err_desc;
2739 
2740 		err_desc = (struct ctl_error_desc *)addr;
2741 
2742 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2743 				      M_WAITOK | M_ZERO);
2744 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2745 
2746 		mtx_lock(&softc->ctl_lock);
2747 		if (err_desc->lun_id >= ctl_max_luns ||
2748 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2749 			mtx_unlock(&softc->ctl_lock);
2750 			free(new_err_desc, M_CTL);
2751 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2752 			       __func__, (uintmax_t)err_desc->lun_id);
2753 			retval = EINVAL;
2754 			break;
2755 		}
2756 		mtx_lock(&lun->lun_lock);
2757 		mtx_unlock(&softc->ctl_lock);
2758 
2759 		/*
2760 		 * We could do some checking here to verify the validity
2761 		 * of the request, but given the complexity of error
2762 		 * injection requests, the checking logic would be fairly
2763 		 * complex.
2764 		 *
2765 		 * For now, if the request is invalid, it just won't get
2766 		 * executed and might get deleted.
2767 		 */
2768 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2769 
2770 		/*
2771 		 * XXX KDM check to make sure the serial number is unique,
2772 		 * in case we somehow manage to wrap.  That shouldn't
2773 		 * happen for a very long time, but it's the right thing to
2774 		 * do.
2775 		 */
2776 		new_err_desc->serial = lun->error_serial;
2777 		err_desc->serial = lun->error_serial;
2778 		lun->error_serial++;
2779 
2780 		mtx_unlock(&lun->lun_lock);
2781 		break;
2782 	}
2783 	case CTL_ERROR_INJECT_DELETE: {
2784 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2785 		int delete_done;
2786 
2787 		delete_desc = (struct ctl_error_desc *)addr;
2788 		delete_done = 0;
2789 
2790 		mtx_lock(&softc->ctl_lock);
2791 		if (delete_desc->lun_id >= ctl_max_luns ||
2792 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2793 			mtx_unlock(&softc->ctl_lock);
2794 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2795 			       __func__, (uintmax_t)delete_desc->lun_id);
2796 			retval = EINVAL;
2797 			break;
2798 		}
2799 		mtx_lock(&lun->lun_lock);
2800 		mtx_unlock(&softc->ctl_lock);
2801 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2802 			if (desc->serial != delete_desc->serial)
2803 				continue;
2804 
2805 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2806 				      links);
2807 			free(desc, M_CTL);
2808 			delete_done = 1;
2809 		}
2810 		mtx_unlock(&lun->lun_lock);
2811 		if (delete_done == 0) {
2812 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2813 			       "error serial %ju on LUN %u\n", __func__,
2814 			       delete_desc->serial, delete_desc->lun_id);
2815 			retval = EINVAL;
2816 			break;
2817 		}
2818 		break;
2819 	}
2820 	case CTL_DUMP_STRUCTS: {
2821 		int j, k;
2822 		struct ctl_port *port;
2823 		struct ctl_frontend *fe;
2824 
2825 		mtx_lock(&softc->ctl_lock);
2826 		printf("CTL Persistent Reservation information start:\n");
2827 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2828 			mtx_lock(&lun->lun_lock);
2829 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2830 				mtx_unlock(&lun->lun_lock);
2831 				continue;
2832 			}
2833 
2834 			for (j = 0; j < ctl_max_ports; j++) {
2835 				if (lun->pr_keys[j] == NULL)
2836 					continue;
2837 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2838 					if (lun->pr_keys[j][k] == 0)
2839 						continue;
2840 					printf("  LUN %ju port %d iid %d key "
2841 					       "%#jx\n", lun->lun, j, k,
2842 					       (uintmax_t)lun->pr_keys[j][k]);
2843 				}
2844 			}
2845 			mtx_unlock(&lun->lun_lock);
2846 		}
2847 		printf("CTL Persistent Reservation information end\n");
2848 		printf("CTL Ports:\n");
2849 		STAILQ_FOREACH(port, &softc->port_list, links) {
2850 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2851 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2852 			       port->frontend->name, port->port_type,
2853 			       port->physical_port, port->virtual_port,
2854 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2855 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2856 				if (port->wwpn_iid[j].in_use == 0 &&
2857 				    port->wwpn_iid[j].wwpn == 0 &&
2858 				    port->wwpn_iid[j].name == NULL)
2859 					continue;
2860 
2861 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2862 				    j, port->wwpn_iid[j].in_use,
2863 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2864 				    port->wwpn_iid[j].name);
2865 			}
2866 		}
2867 		printf("CTL Port information end\n");
2868 		mtx_unlock(&softc->ctl_lock);
2869 		/*
2870 		 * XXX KDM calling this without a lock.  We'd likely want
2871 		 * to drop the lock before calling the frontend's dump
2872 		 * routine anyway.
2873 		 */
2874 		printf("CTL Frontends:\n");
2875 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2876 			printf("  Frontend '%s'\n", fe->name);
2877 			if (fe->fe_dump != NULL)
2878 				fe->fe_dump();
2879 		}
2880 		printf("CTL Frontend information end\n");
2881 		break;
2882 	}
2883 	case CTL_LUN_REQ: {
2884 		struct ctl_lun_req *lun_req;
2885 		struct ctl_backend_driver *backend;
2886 		void *packed;
2887 		nvlist_t *tmp_args_nvl;
2888 		size_t packed_len;
2889 
2890 		lun_req = (struct ctl_lun_req *)addr;
2891 		tmp_args_nvl = lun_req->args_nvl;
2892 
2893 		backend = ctl_backend_find(lun_req->backend);
2894 		if (backend == NULL) {
2895 			lun_req->status = CTL_LUN_ERROR;
2896 			snprintf(lun_req->error_str,
2897 				 sizeof(lun_req->error_str),
2898 				 "Backend \"%s\" not found.",
2899 				 lun_req->backend);
2900 			break;
2901 		}
2902 
2903 		if (lun_req->args != NULL) {
2904 			packed = malloc(lun_req->args_len, M_CTL, M_WAITOK);
2905 			if (copyin(lun_req->args, packed, lun_req->args_len) != 0) {
2906 				free(packed, M_CTL);
2907 				lun_req->status = CTL_LUN_ERROR;
2908 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2909 				    "Cannot copyin args.");
2910 				break;
2911 			}
2912 			lun_req->args_nvl = nvlist_unpack(packed,
2913 			    lun_req->args_len, 0);
2914 			free(packed, M_CTL);
2915 
2916 			if (lun_req->args_nvl == NULL) {
2917 				lun_req->status = CTL_LUN_ERROR;
2918 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2919 				    "Cannot unpack args nvlist.");
2920 				break;
2921 			}
2922 		} else
2923 			lun_req->args_nvl = nvlist_create(0);
2924 
2925 		retval = backend->ioctl(dev, cmd, addr, flag, td);
2926 		nvlist_destroy(lun_req->args_nvl);
2927 		lun_req->args_nvl = tmp_args_nvl;
2928 
2929 		if (lun_req->result_nvl != NULL) {
2930 			if (lun_req->result != NULL) {
2931 				packed = nvlist_pack(lun_req->result_nvl,
2932 				    &packed_len);
2933 				if (packed == NULL) {
2934 					lun_req->status = CTL_LUN_ERROR;
2935 					snprintf(lun_req->error_str,
2936 					    sizeof(lun_req->error_str),
2937 					    "Cannot pack result nvlist.");
2938 					break;
2939 				}
2940 
2941 				if (packed_len > lun_req->result_len) {
2942 					lun_req->status = CTL_LUN_ERROR;
2943 					snprintf(lun_req->error_str,
2944 					    sizeof(lun_req->error_str),
2945 					    "Result nvlist too large.");
2946 					free(packed, M_NVLIST);
2947 					break;
2948 				}
2949 
2950 				if (copyout(packed, lun_req->result, packed_len)) {
2951 					lun_req->status = CTL_LUN_ERROR;
2952 					snprintf(lun_req->error_str,
2953 					    sizeof(lun_req->error_str),
2954 					    "Cannot copyout() the result.");
2955 					free(packed, M_NVLIST);
2956 					break;
2957 				}
2958 
2959 				lun_req->result_len = packed_len;
2960 				free(packed, M_NVLIST);
2961 			}
2962 
2963 			nvlist_destroy(lun_req->result_nvl);
2964 		}
2965 		break;
2966 	}
2967 	case CTL_LUN_LIST: {
2968 		struct sbuf *sb;
2969 		struct ctl_lun_list *list;
2970 		const char *name, *value;
2971 		void *cookie;
2972 		int type;
2973 
2974 		list = (struct ctl_lun_list *)addr;
2975 
2976 		/*
2977 		 * Allocate a fixed length sbuf here, based on the length
2978 		 * of the user's buffer.  We could allocate an auto-extending
2979 		 * buffer, and then tell the user how much larger our
2980 		 * amount of data is than his buffer, but that presents
2981 		 * some problems:
2982 		 *
2983 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2984 		 *     we can't hold a lock while calling them with an
2985 		 *     auto-extending buffer.
2986  		 *
2987 		 * 2.  There is not currently a LUN reference counting
2988 		 *     mechanism, outside of outstanding transactions on
2989 		 *     the LUN's OOA queue.  So a LUN could go away on us
2990 		 *     while we're getting the LUN number, backend-specific
2991 		 *     information, etc.  Thus, given the way things
2992 		 *     currently work, we need to hold the CTL lock while
2993 		 *     grabbing LUN information.
2994 		 *
2995 		 * So, from the user's standpoint, the best thing to do is
2996 		 * allocate what he thinks is a reasonable buffer length,
2997 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2998 		 * double the buffer length and try again.  (And repeat
2999 		 * that until he succeeds.)
3000 		 */
3001 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3002 		if (sb == NULL) {
3003 			list->status = CTL_LUN_LIST_ERROR;
3004 			snprintf(list->error_str, sizeof(list->error_str),
3005 				 "Unable to allocate %d bytes for LUN list",
3006 				 list->alloc_len);
3007 			break;
3008 		}
3009 
3010 		sbuf_printf(sb, "<ctllunlist>\n");
3011 
3012 		mtx_lock(&softc->ctl_lock);
3013 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3014 			mtx_lock(&lun->lun_lock);
3015 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3016 					     (uintmax_t)lun->lun);
3017 
3018 			/*
3019 			 * Bail out as soon as we see that we've overfilled
3020 			 * the buffer.
3021 			 */
3022 			if (retval != 0)
3023 				break;
3024 
3025 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3026 					     "</backend_type>\n",
3027 					     (lun->backend == NULL) ?  "none" :
3028 					     lun->backend->name);
3029 
3030 			if (retval != 0)
3031 				break;
3032 
3033 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3034 					     lun->be_lun->lun_type);
3035 
3036 			if (retval != 0)
3037 				break;
3038 
3039 			if (lun->backend == NULL) {
3040 				retval = sbuf_printf(sb, "</lun>\n");
3041 				if (retval != 0)
3042 					break;
3043 				continue;
3044 			}
3045 
3046 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3047 					     (lun->be_lun->maxlba > 0) ?
3048 					     lun->be_lun->maxlba + 1 : 0);
3049 
3050 			if (retval != 0)
3051 				break;
3052 
3053 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3054 					     lun->be_lun->blocksize);
3055 
3056 			if (retval != 0)
3057 				break;
3058 
3059 			retval = sbuf_printf(sb, "\t<serial_number>");
3060 
3061 			if (retval != 0)
3062 				break;
3063 
3064 			retval = ctl_sbuf_printf_esc(sb,
3065 			    lun->be_lun->serial_num,
3066 			    sizeof(lun->be_lun->serial_num));
3067 
3068 			if (retval != 0)
3069 				break;
3070 
3071 			retval = sbuf_printf(sb, "</serial_number>\n");
3072 
3073 			if (retval != 0)
3074 				break;
3075 
3076 			retval = sbuf_printf(sb, "\t<device_id>");
3077 
3078 			if (retval != 0)
3079 				break;
3080 
3081 			retval = ctl_sbuf_printf_esc(sb,
3082 			    lun->be_lun->device_id,
3083 			    sizeof(lun->be_lun->device_id));
3084 
3085 			if (retval != 0)
3086 				break;
3087 
3088 			retval = sbuf_printf(sb, "</device_id>\n");
3089 
3090 			if (retval != 0)
3091 				break;
3092 
3093 			if (lun->backend->lun_info != NULL) {
3094 				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3095 				if (retval != 0)
3096 					break;
3097 			}
3098 
3099 			cookie = NULL;
3100 			while ((name = nvlist_next(lun->be_lun->options, &type,
3101 			    &cookie)) != NULL) {
3102 				sbuf_printf(sb, "\t<%s>", name);
3103 
3104 				if (type == NV_TYPE_STRING) {
3105 					value = dnvlist_get_string(
3106 					    lun->be_lun->options, name, NULL);
3107 					if (value != NULL)
3108 						sbuf_printf(sb, "%s", value);
3109 				}
3110 
3111 				sbuf_printf(sb, "</%s>\n", name);
3112 			}
3113 
3114 			retval = sbuf_printf(sb, "</lun>\n");
3115 
3116 			if (retval != 0)
3117 				break;
3118 			mtx_unlock(&lun->lun_lock);
3119 		}
3120 		if (lun != NULL)
3121 			mtx_unlock(&lun->lun_lock);
3122 		mtx_unlock(&softc->ctl_lock);
3123 
3124 		if ((retval != 0)
3125 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3126 			retval = 0;
3127 			sbuf_delete(sb);
3128 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3129 			snprintf(list->error_str, sizeof(list->error_str),
3130 				 "Out of space, %d bytes is too small",
3131 				 list->alloc_len);
3132 			break;
3133 		}
3134 
3135 		sbuf_finish(sb);
3136 
3137 		retval = copyout(sbuf_data(sb), list->lun_xml,
3138 				 sbuf_len(sb) + 1);
3139 
3140 		list->fill_len = sbuf_len(sb) + 1;
3141 		list->status = CTL_LUN_LIST_OK;
3142 		sbuf_delete(sb);
3143 		break;
3144 	}
3145 	case CTL_ISCSI: {
3146 		struct ctl_iscsi *ci;
3147 		struct ctl_frontend *fe;
3148 
3149 		ci = (struct ctl_iscsi *)addr;
3150 
3151 		fe = ctl_frontend_find("iscsi");
3152 		if (fe == NULL) {
3153 			ci->status = CTL_ISCSI_ERROR;
3154 			snprintf(ci->error_str, sizeof(ci->error_str),
3155 			    "Frontend \"iscsi\" not found.");
3156 			break;
3157 		}
3158 
3159 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3160 		break;
3161 	}
3162 	case CTL_PORT_REQ: {
3163 		struct ctl_req *req;
3164 		struct ctl_frontend *fe;
3165 		void *packed;
3166 		nvlist_t *tmp_args_nvl;
3167 		size_t packed_len;
3168 
3169 		req = (struct ctl_req *)addr;
3170 		tmp_args_nvl = req->args_nvl;
3171 
3172 		fe = ctl_frontend_find(req->driver);
3173 		if (fe == NULL) {
3174 			req->status = CTL_LUN_ERROR;
3175 			snprintf(req->error_str, sizeof(req->error_str),
3176 			    "Frontend \"%s\" not found.", req->driver);
3177 			break;
3178 		}
3179 
3180 		if (req->args != NULL) {
3181 			packed = malloc(req->args_len, M_CTL, M_WAITOK);
3182 			if (copyin(req->args, packed, req->args_len) != 0) {
3183 				free(packed, M_CTL);
3184 				req->status = CTL_LUN_ERROR;
3185 				snprintf(req->error_str, sizeof(req->error_str),
3186 				    "Cannot copyin args.");
3187 				break;
3188 			}
3189 			req->args_nvl = nvlist_unpack(packed,
3190 			    req->args_len, 0);
3191 			free(packed, M_CTL);
3192 
3193 			if (req->args_nvl == NULL) {
3194 				req->status = CTL_LUN_ERROR;
3195 				snprintf(req->error_str, sizeof(req->error_str),
3196 				    "Cannot unpack args nvlist.");
3197 				break;
3198 			}
3199 		} else
3200 			req->args_nvl = nvlist_create(0);
3201 
3202 		if (fe->ioctl)
3203 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3204 		else
3205 			retval = ENODEV;
3206 
3207 		nvlist_destroy(req->args_nvl);
3208 		req->args_nvl = tmp_args_nvl;
3209 
3210 		if (req->result_nvl != NULL) {
3211 			if (req->result != NULL) {
3212 				packed = nvlist_pack(req->result_nvl,
3213 				    &packed_len);
3214 				if (packed == NULL) {
3215 					req->status = CTL_LUN_ERROR;
3216 					snprintf(req->error_str,
3217 					    sizeof(req->error_str),
3218 					    "Cannot pack result nvlist.");
3219 					break;
3220 				}
3221 
3222 				if (packed_len > req->result_len) {
3223 					req->status = CTL_LUN_ERROR;
3224 					snprintf(req->error_str,
3225 					    sizeof(req->error_str),
3226 					    "Result nvlist too large.");
3227 					free(packed, M_NVLIST);
3228 					break;
3229 				}
3230 
3231 				if (copyout(packed, req->result, packed_len)) {
3232 					req->status = CTL_LUN_ERROR;
3233 					snprintf(req->error_str,
3234 					    sizeof(req->error_str),
3235 					    "Cannot copyout() the result.");
3236 					free(packed, M_NVLIST);
3237 					break;
3238 				}
3239 
3240 				req->result_len = packed_len;
3241 				free(packed, M_NVLIST);
3242 			}
3243 
3244 			nvlist_destroy(req->result_nvl);
3245 		}
3246 		break;
3247 	}
3248 	case CTL_PORT_LIST: {
3249 		struct sbuf *sb;
3250 		struct ctl_port *port;
3251 		struct ctl_lun_list *list;
3252 		const char *name, *value;
3253 		void *cookie;
3254 		int j, type;
3255 		uint32_t plun;
3256 
3257 		list = (struct ctl_lun_list *)addr;
3258 
3259 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3260 		if (sb == NULL) {
3261 			list->status = CTL_LUN_LIST_ERROR;
3262 			snprintf(list->error_str, sizeof(list->error_str),
3263 				 "Unable to allocate %d bytes for LUN list",
3264 				 list->alloc_len);
3265 			break;
3266 		}
3267 
3268 		sbuf_printf(sb, "<ctlportlist>\n");
3269 
3270 		mtx_lock(&softc->ctl_lock);
3271 		STAILQ_FOREACH(port, &softc->port_list, links) {
3272 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3273 					     (uintmax_t)port->targ_port);
3274 
3275 			/*
3276 			 * Bail out as soon as we see that we've overfilled
3277 			 * the buffer.
3278 			 */
3279 			if (retval != 0)
3280 				break;
3281 
3282 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3283 			    "</frontend_type>\n", port->frontend->name);
3284 			if (retval != 0)
3285 				break;
3286 
3287 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3288 					     port->port_type);
3289 			if (retval != 0)
3290 				break;
3291 
3292 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3293 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3294 			if (retval != 0)
3295 				break;
3296 
3297 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3298 			    port->port_name);
3299 			if (retval != 0)
3300 				break;
3301 
3302 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3303 			    port->physical_port);
3304 			if (retval != 0)
3305 				break;
3306 
3307 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3308 			    port->virtual_port);
3309 			if (retval != 0)
3310 				break;
3311 
3312 			if (port->target_devid != NULL) {
3313 				sbuf_printf(sb, "\t<target>");
3314 				ctl_id_sbuf(port->target_devid, sb);
3315 				sbuf_printf(sb, "</target>\n");
3316 			}
3317 
3318 			if (port->port_devid != NULL) {
3319 				sbuf_printf(sb, "\t<port>");
3320 				ctl_id_sbuf(port->port_devid, sb);
3321 				sbuf_printf(sb, "</port>\n");
3322 			}
3323 
3324 			if (port->port_info != NULL) {
3325 				retval = port->port_info(port->onoff_arg, sb);
3326 				if (retval != 0)
3327 					break;
3328 			}
3329 
3330 			cookie = NULL;
3331 			while ((name = nvlist_next(port->options, &type,
3332 			    &cookie)) != NULL) {
3333 				sbuf_printf(sb, "\t<%s>", name);
3334 
3335 				if (type == NV_TYPE_STRING) {
3336 					value = dnvlist_get_string(port->options,
3337 					    name, NULL);
3338 					if (value != NULL)
3339 						sbuf_printf(sb, "%s", value);
3340 				}
3341 
3342 				sbuf_printf(sb, "</%s>\n", name);
3343 			}
3344 
3345 			if (port->lun_map != NULL) {
3346 				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3347 				for (j = 0; j < port->lun_map_size; j++) {
3348 					plun = ctl_lun_map_from_port(port, j);
3349 					if (plun == UINT32_MAX)
3350 						continue;
3351 					sbuf_printf(sb,
3352 					    "\t<lun id=\"%u\">%u</lun>\n",
3353 					    j, plun);
3354 				}
3355 			}
3356 
3357 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3358 				if (port->wwpn_iid[j].in_use == 0 ||
3359 				    (port->wwpn_iid[j].wwpn == 0 &&
3360 				     port->wwpn_iid[j].name == NULL))
3361 					continue;
3362 
3363 				if (port->wwpn_iid[j].name != NULL)
3364 					retval = sbuf_printf(sb,
3365 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3366 					    j, port->wwpn_iid[j].name);
3367 				else
3368 					retval = sbuf_printf(sb,
3369 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3370 					    j, port->wwpn_iid[j].wwpn);
3371 				if (retval != 0)
3372 					break;
3373 			}
3374 			if (retval != 0)
3375 				break;
3376 
3377 			retval = sbuf_printf(sb, "</targ_port>\n");
3378 			if (retval != 0)
3379 				break;
3380 		}
3381 		mtx_unlock(&softc->ctl_lock);
3382 
3383 		if ((retval != 0)
3384 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3385 			retval = 0;
3386 			sbuf_delete(sb);
3387 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3388 			snprintf(list->error_str, sizeof(list->error_str),
3389 				 "Out of space, %d bytes is too small",
3390 				 list->alloc_len);
3391 			break;
3392 		}
3393 
3394 		sbuf_finish(sb);
3395 
3396 		retval = copyout(sbuf_data(sb), list->lun_xml,
3397 				 sbuf_len(sb) + 1);
3398 
3399 		list->fill_len = sbuf_len(sb) + 1;
3400 		list->status = CTL_LUN_LIST_OK;
3401 		sbuf_delete(sb);
3402 		break;
3403 	}
3404 	case CTL_LUN_MAP: {
3405 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3406 		struct ctl_port *port;
3407 
3408 		mtx_lock(&softc->ctl_lock);
3409 		if (lm->port < softc->port_min ||
3410 		    lm->port >= softc->port_max ||
3411 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3412 			mtx_unlock(&softc->ctl_lock);
3413 			return (ENXIO);
3414 		}
3415 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3416 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3417 				if (ctl_lun_map_to_port(port, lun->lun) ==
3418 				    UINT32_MAX)
3419 					continue;
3420 				mtx_lock(&lun->lun_lock);
3421 				ctl_est_ua_port(lun, lm->port, -1,
3422 				    CTL_UA_LUN_CHANGE);
3423 				mtx_unlock(&lun->lun_lock);
3424 			}
3425 		}
3426 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3427 		if (lm->plun != UINT32_MAX) {
3428 			if (lm->lun == UINT32_MAX)
3429 				retval = ctl_lun_map_unset(port, lm->plun);
3430 			else if (lm->lun < ctl_max_luns &&
3431 			    softc->ctl_luns[lm->lun] != NULL)
3432 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3433 			else
3434 				return (ENXIO);
3435 		} else {
3436 			if (lm->lun == UINT32_MAX)
3437 				retval = ctl_lun_map_deinit(port);
3438 			else
3439 				retval = ctl_lun_map_init(port);
3440 		}
3441 		if (port->status & CTL_PORT_STATUS_ONLINE)
3442 			ctl_isc_announce_port(port);
3443 		break;
3444 	}
3445 	case CTL_GET_LUN_STATS: {
3446 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3447 		int i;
3448 
3449 		/*
3450 		 * XXX KDM no locking here.  If the LUN list changes,
3451 		 * things can blow up.
3452 		 */
3453 		i = 0;
3454 		stats->status = CTL_SS_OK;
3455 		stats->fill_len = 0;
3456 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3457 			if (lun->lun < stats->first_item)
3458 				continue;
3459 			if (stats->fill_len + sizeof(lun->stats) >
3460 			    stats->alloc_len) {
3461 				stats->status = CTL_SS_NEED_MORE_SPACE;
3462 				break;
3463 			}
3464 			retval = copyout(&lun->stats, &stats->stats[i++],
3465 					 sizeof(lun->stats));
3466 			if (retval != 0)
3467 				break;
3468 			stats->fill_len += sizeof(lun->stats);
3469 		}
3470 		stats->num_items = softc->num_luns;
3471 		stats->flags = CTL_STATS_FLAG_NONE;
3472 #ifdef CTL_TIME_IO
3473 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3474 #endif
3475 		getnanouptime(&stats->timestamp);
3476 		break;
3477 	}
3478 	case CTL_GET_PORT_STATS: {
3479 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3480 		int i;
3481 
3482 		/*
3483 		 * XXX KDM no locking here.  If the LUN list changes,
3484 		 * things can blow up.
3485 		 */
3486 		i = 0;
3487 		stats->status = CTL_SS_OK;
3488 		stats->fill_len = 0;
3489 		STAILQ_FOREACH(port, &softc->port_list, links) {
3490 			if (port->targ_port < stats->first_item)
3491 				continue;
3492 			if (stats->fill_len + sizeof(port->stats) >
3493 			    stats->alloc_len) {
3494 				stats->status = CTL_SS_NEED_MORE_SPACE;
3495 				break;
3496 			}
3497 			retval = copyout(&port->stats, &stats->stats[i++],
3498 					 sizeof(port->stats));
3499 			if (retval != 0)
3500 				break;
3501 			stats->fill_len += sizeof(port->stats);
3502 		}
3503 		stats->num_items = softc->num_ports;
3504 		stats->flags = CTL_STATS_FLAG_NONE;
3505 #ifdef CTL_TIME_IO
3506 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3507 #endif
3508 		getnanouptime(&stats->timestamp);
3509 		break;
3510 	}
3511 	default: {
3512 		/* XXX KDM should we fix this? */
3513 #if 0
3514 		struct ctl_backend_driver *backend;
3515 		unsigned int type;
3516 		int found;
3517 
3518 		found = 0;
3519 
3520 		/*
3521 		 * We encode the backend type as the ioctl type for backend
3522 		 * ioctls.  So parse it out here, and then search for a
3523 		 * backend of this type.
3524 		 */
3525 		type = _IOC_TYPE(cmd);
3526 
3527 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3528 			if (backend->type == type) {
3529 				found = 1;
3530 				break;
3531 			}
3532 		}
3533 		if (found == 0) {
3534 			printf("ctl: unknown ioctl command %#lx or backend "
3535 			       "%d\n", cmd, type);
3536 			retval = EINVAL;
3537 			break;
3538 		}
3539 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3540 #endif
3541 		retval = ENOTTY;
3542 		break;
3543 	}
3544 	}
3545 	return (retval);
3546 }
3547 
3548 uint32_t
3549 ctl_get_initindex(struct ctl_nexus *nexus)
3550 {
3551 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3552 }
3553 
3554 int
3555 ctl_lun_map_init(struct ctl_port *port)
3556 {
3557 	struct ctl_softc *softc = port->ctl_softc;
3558 	struct ctl_lun *lun;
3559 	int size = ctl_lun_map_size;
3560 	uint32_t i;
3561 
3562 	if (port->lun_map == NULL || port->lun_map_size < size) {
3563 		port->lun_map_size = 0;
3564 		free(port->lun_map, M_CTL);
3565 		port->lun_map = malloc(size * sizeof(uint32_t),
3566 		    M_CTL, M_NOWAIT);
3567 	}
3568 	if (port->lun_map == NULL)
3569 		return (ENOMEM);
3570 	for (i = 0; i < size; i++)
3571 		port->lun_map[i] = UINT32_MAX;
3572 	port->lun_map_size = size;
3573 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3574 		if (port->lun_disable != NULL) {
3575 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3576 				port->lun_disable(port->targ_lun_arg, lun->lun);
3577 		}
3578 		ctl_isc_announce_port(port);
3579 	}
3580 	return (0);
3581 }
3582 
3583 int
3584 ctl_lun_map_deinit(struct ctl_port *port)
3585 {
3586 	struct ctl_softc *softc = port->ctl_softc;
3587 	struct ctl_lun *lun;
3588 
3589 	if (port->lun_map == NULL)
3590 		return (0);
3591 	port->lun_map_size = 0;
3592 	free(port->lun_map, M_CTL);
3593 	port->lun_map = NULL;
3594 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3595 		if (port->lun_enable != NULL) {
3596 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3597 				port->lun_enable(port->targ_lun_arg, lun->lun);
3598 		}
3599 		ctl_isc_announce_port(port);
3600 	}
3601 	return (0);
3602 }
3603 
3604 int
3605 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3606 {
3607 	int status;
3608 	uint32_t old;
3609 
3610 	if (port->lun_map == NULL) {
3611 		status = ctl_lun_map_init(port);
3612 		if (status != 0)
3613 			return (status);
3614 	}
3615 	if (plun >= port->lun_map_size)
3616 		return (EINVAL);
3617 	old = port->lun_map[plun];
3618 	port->lun_map[plun] = glun;
3619 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3620 		if (port->lun_enable != NULL)
3621 			port->lun_enable(port->targ_lun_arg, plun);
3622 		ctl_isc_announce_port(port);
3623 	}
3624 	return (0);
3625 }
3626 
3627 int
3628 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3629 {
3630 	uint32_t old;
3631 
3632 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3633 		return (0);
3634 	old = port->lun_map[plun];
3635 	port->lun_map[plun] = UINT32_MAX;
3636 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3637 		if (port->lun_disable != NULL)
3638 			port->lun_disable(port->targ_lun_arg, plun);
3639 		ctl_isc_announce_port(port);
3640 	}
3641 	return (0);
3642 }
3643 
3644 uint32_t
3645 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3646 {
3647 
3648 	if (port == NULL)
3649 		return (UINT32_MAX);
3650 	if (port->lun_map == NULL)
3651 		return (lun_id);
3652 	if (lun_id > port->lun_map_size)
3653 		return (UINT32_MAX);
3654 	return (port->lun_map[lun_id]);
3655 }
3656 
3657 uint32_t
3658 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3659 {
3660 	uint32_t i;
3661 
3662 	if (port == NULL)
3663 		return (UINT32_MAX);
3664 	if (port->lun_map == NULL)
3665 		return (lun_id);
3666 	for (i = 0; i < port->lun_map_size; i++) {
3667 		if (port->lun_map[i] == lun_id)
3668 			return (i);
3669 	}
3670 	return (UINT32_MAX);
3671 }
3672 
3673 uint32_t
3674 ctl_decode_lun(uint64_t encoded)
3675 {
3676 	uint8_t lun[8];
3677 	uint32_t result = 0xffffffff;
3678 
3679 	be64enc(lun, encoded);
3680 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3681 	case RPL_LUNDATA_ATYP_PERIPH:
3682 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3683 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3684 			result = lun[1];
3685 		break;
3686 	case RPL_LUNDATA_ATYP_FLAT:
3687 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3688 		    lun[6] == 0 && lun[7] == 0)
3689 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3690 		break;
3691 	case RPL_LUNDATA_ATYP_EXTLUN:
3692 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3693 		case 0x02:
3694 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3695 			case 0x00:
3696 				result = lun[1];
3697 				break;
3698 			case 0x10:
3699 				result = (lun[1] << 16) + (lun[2] << 8) +
3700 				    lun[3];
3701 				break;
3702 			case 0x20:
3703 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3704 					result = (lun[2] << 24) +
3705 					    (lun[3] << 16) + (lun[4] << 8) +
3706 					    lun[5];
3707 				break;
3708 			}
3709 			break;
3710 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3711 			result = 0xffffffff;
3712 			break;
3713 		}
3714 		break;
3715 	}
3716 	return (result);
3717 }
3718 
3719 uint64_t
3720 ctl_encode_lun(uint32_t decoded)
3721 {
3722 	uint64_t l = decoded;
3723 
3724 	if (l <= 0xff)
3725 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3726 	if (l <= 0x3fff)
3727 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3728 	if (l <= 0xffffff)
3729 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3730 		    (l << 32));
3731 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3732 }
3733 
3734 int
3735 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3736 {
3737 	int i;
3738 
3739 	for (i = first; i < last; i++) {
3740 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3741 			return (i);
3742 	}
3743 	return (-1);
3744 }
3745 
3746 int
3747 ctl_set_mask(uint32_t *mask, uint32_t bit)
3748 {
3749 	uint32_t chunk, piece;
3750 
3751 	chunk = bit >> 5;
3752 	piece = bit % (sizeof(uint32_t) * 8);
3753 
3754 	if ((mask[chunk] & (1 << piece)) != 0)
3755 		return (-1);
3756 	else
3757 		mask[chunk] |= (1 << piece);
3758 
3759 	return (0);
3760 }
3761 
3762 int
3763 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3764 {
3765 	uint32_t chunk, piece;
3766 
3767 	chunk = bit >> 5;
3768 	piece = bit % (sizeof(uint32_t) * 8);
3769 
3770 	if ((mask[chunk] & (1 << piece)) == 0)
3771 		return (-1);
3772 	else
3773 		mask[chunk] &= ~(1 << piece);
3774 
3775 	return (0);
3776 }
3777 
3778 int
3779 ctl_is_set(uint32_t *mask, uint32_t bit)
3780 {
3781 	uint32_t chunk, piece;
3782 
3783 	chunk = bit >> 5;
3784 	piece = bit % (sizeof(uint32_t) * 8);
3785 
3786 	if ((mask[chunk] & (1 << piece)) == 0)
3787 		return (0);
3788 	else
3789 		return (1);
3790 }
3791 
3792 static uint64_t
3793 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3794 {
3795 	uint64_t *t;
3796 
3797 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3798 	if (t == NULL)
3799 		return (0);
3800 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3801 }
3802 
3803 static void
3804 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3805 {
3806 	uint64_t *t;
3807 
3808 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3809 	if (t == NULL)
3810 		return;
3811 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3812 }
3813 
3814 static void
3815 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3816 {
3817 	uint64_t *p;
3818 	u_int i;
3819 
3820 	i = residx/CTL_MAX_INIT_PER_PORT;
3821 	if (lun->pr_keys[i] != NULL)
3822 		return;
3823 	mtx_unlock(&lun->lun_lock);
3824 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3825 	    M_WAITOK | M_ZERO);
3826 	mtx_lock(&lun->lun_lock);
3827 	if (lun->pr_keys[i] == NULL)
3828 		lun->pr_keys[i] = p;
3829 	else
3830 		free(p, M_CTL);
3831 }
3832 
3833 static void
3834 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3835 {
3836 	uint64_t *t;
3837 
3838 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3839 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3840 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3841 }
3842 
3843 /*
3844  * ctl_softc, pool_name, total_ctl_io are passed in.
3845  * npool is passed out.
3846  */
3847 int
3848 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3849 		uint32_t total_ctl_io, void **npool)
3850 {
3851 	struct ctl_io_pool *pool;
3852 
3853 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3854 					    M_NOWAIT | M_ZERO);
3855 	if (pool == NULL)
3856 		return (ENOMEM);
3857 
3858 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3859 	pool->ctl_softc = ctl_softc;
3860 #ifdef IO_POOLS
3861 	pool->zone = uma_zsecond_create(pool->name, NULL,
3862 	    NULL, NULL, NULL, ctl_softc->io_zone);
3863 	/* uma_prealloc(pool->zone, total_ctl_io); */
3864 #else
3865 	pool->zone = ctl_softc->io_zone;
3866 #endif
3867 
3868 	*npool = pool;
3869 	return (0);
3870 }
3871 
3872 void
3873 ctl_pool_free(struct ctl_io_pool *pool)
3874 {
3875 
3876 	if (pool == NULL)
3877 		return;
3878 
3879 #ifdef IO_POOLS
3880 	uma_zdestroy(pool->zone);
3881 #endif
3882 	free(pool, M_CTL);
3883 }
3884 
3885 union ctl_io *
3886 ctl_alloc_io(void *pool_ref)
3887 {
3888 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3889 	union ctl_io *io;
3890 
3891 	io = uma_zalloc(pool->zone, M_WAITOK);
3892 	if (io != NULL) {
3893 		io->io_hdr.pool = pool_ref;
3894 		CTL_SOFTC(io) = pool->ctl_softc;
3895 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3896 	}
3897 	return (io);
3898 }
3899 
3900 union ctl_io *
3901 ctl_alloc_io_nowait(void *pool_ref)
3902 {
3903 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3904 	union ctl_io *io;
3905 
3906 	io = uma_zalloc(pool->zone, M_NOWAIT);
3907 	if (io != NULL) {
3908 		io->io_hdr.pool = pool_ref;
3909 		CTL_SOFTC(io) = pool->ctl_softc;
3910 		TAILQ_INIT(&io->io_hdr.blocked_queue);
3911 	}
3912 	return (io);
3913 }
3914 
3915 void
3916 ctl_free_io(union ctl_io *io)
3917 {
3918 	struct ctl_io_pool *pool;
3919 
3920 	if (io == NULL)
3921 		return;
3922 
3923 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3924 	uma_zfree(pool->zone, io);
3925 }
3926 
3927 void
3928 ctl_zero_io(union ctl_io *io)
3929 {
3930 	struct ctl_io_pool *pool;
3931 
3932 	if (io == NULL)
3933 		return;
3934 
3935 	/*
3936 	 * May need to preserve linked list pointers at some point too.
3937 	 */
3938 	pool = io->io_hdr.pool;
3939 	memset(io, 0, sizeof(*io));
3940 	io->io_hdr.pool = pool;
3941 	CTL_SOFTC(io) = pool->ctl_softc;
3942 	TAILQ_INIT(&io->io_hdr.blocked_queue);
3943 }
3944 
3945 int
3946 ctl_expand_number(const char *buf, uint64_t *num)
3947 {
3948 	char *endptr;
3949 	uint64_t number;
3950 	unsigned shift;
3951 
3952 	number = strtoq(buf, &endptr, 0);
3953 
3954 	switch (tolower((unsigned char)*endptr)) {
3955 	case 'e':
3956 		shift = 60;
3957 		break;
3958 	case 'p':
3959 		shift = 50;
3960 		break;
3961 	case 't':
3962 		shift = 40;
3963 		break;
3964 	case 'g':
3965 		shift = 30;
3966 		break;
3967 	case 'm':
3968 		shift = 20;
3969 		break;
3970 	case 'k':
3971 		shift = 10;
3972 		break;
3973 	case 'b':
3974 	case '\0': /* No unit. */
3975 		*num = number;
3976 		return (0);
3977 	default:
3978 		/* Unrecognized unit. */
3979 		return (-1);
3980 	}
3981 
3982 	if ((number << shift) >> shift != number) {
3983 		/* Overflow */
3984 		return (-1);
3985 	}
3986 	*num = number << shift;
3987 	return (0);
3988 }
3989 
3990 
3991 /*
3992  * This routine could be used in the future to load default and/or saved
3993  * mode page parameters for a particuar lun.
3994  */
3995 static int
3996 ctl_init_page_index(struct ctl_lun *lun)
3997 {
3998 	int i, page_code;
3999 	struct ctl_page_index *page_index;
4000 	const char *value;
4001 	uint64_t ival;
4002 
4003 	memcpy(&lun->mode_pages.index, page_index_template,
4004 	       sizeof(page_index_template));
4005 
4006 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4007 
4008 		page_index = &lun->mode_pages.index[i];
4009 		if (lun->be_lun->lun_type == T_DIRECT &&
4010 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4011 			continue;
4012 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4013 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4014 			continue;
4015 		if (lun->be_lun->lun_type == T_CDROM &&
4016 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4017 			continue;
4018 
4019 		page_code = page_index->page_code & SMPH_PC_MASK;
4020 		switch (page_code) {
4021 		case SMS_RW_ERROR_RECOVERY_PAGE: {
4022 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4023 			    ("subpage %#x for page %#x is incorrect!",
4024 			    page_index->subpage, page_code));
4025 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4026 			       &rw_er_page_default,
4027 			       sizeof(rw_er_page_default));
4028 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4029 			       &rw_er_page_changeable,
4030 			       sizeof(rw_er_page_changeable));
4031 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4032 			       &rw_er_page_default,
4033 			       sizeof(rw_er_page_default));
4034 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4035 			       &rw_er_page_default,
4036 			       sizeof(rw_er_page_default));
4037 			page_index->page_data =
4038 				(uint8_t *)lun->mode_pages.rw_er_page;
4039 			break;
4040 		}
4041 		case SMS_FORMAT_DEVICE_PAGE: {
4042 			struct scsi_format_page *format_page;
4043 
4044 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4045 			    ("subpage %#x for page %#x is incorrect!",
4046 			    page_index->subpage, page_code));
4047 
4048 			/*
4049 			 * Sectors per track are set above.  Bytes per
4050 			 * sector need to be set here on a per-LUN basis.
4051 			 */
4052 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4053 			       &format_page_default,
4054 			       sizeof(format_page_default));
4055 			memcpy(&lun->mode_pages.format_page[
4056 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4057 			       sizeof(format_page_changeable));
4058 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4059 			       &format_page_default,
4060 			       sizeof(format_page_default));
4061 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4062 			       &format_page_default,
4063 			       sizeof(format_page_default));
4064 
4065 			format_page = &lun->mode_pages.format_page[
4066 				CTL_PAGE_CURRENT];
4067 			scsi_ulto2b(lun->be_lun->blocksize,
4068 				    format_page->bytes_per_sector);
4069 
4070 			format_page = &lun->mode_pages.format_page[
4071 				CTL_PAGE_DEFAULT];
4072 			scsi_ulto2b(lun->be_lun->blocksize,
4073 				    format_page->bytes_per_sector);
4074 
4075 			format_page = &lun->mode_pages.format_page[
4076 				CTL_PAGE_SAVED];
4077 			scsi_ulto2b(lun->be_lun->blocksize,
4078 				    format_page->bytes_per_sector);
4079 
4080 			page_index->page_data =
4081 				(uint8_t *)lun->mode_pages.format_page;
4082 			break;
4083 		}
4084 		case SMS_RIGID_DISK_PAGE: {
4085 			struct scsi_rigid_disk_page *rigid_disk_page;
4086 			uint32_t sectors_per_cylinder;
4087 			uint64_t cylinders;
4088 #ifndef	__XSCALE__
4089 			int shift;
4090 #endif /* !__XSCALE__ */
4091 
4092 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4093 			    ("subpage %#x for page %#x is incorrect!",
4094 			    page_index->subpage, page_code));
4095 
4096 			/*
4097 			 * Rotation rate and sectors per track are set
4098 			 * above.  We calculate the cylinders here based on
4099 			 * capacity.  Due to the number of heads and
4100 			 * sectors per track we're using, smaller arrays
4101 			 * may turn out to have 0 cylinders.  Linux and
4102 			 * FreeBSD don't pay attention to these mode pages
4103 			 * to figure out capacity, but Solaris does.  It
4104 			 * seems to deal with 0 cylinders just fine, and
4105 			 * works out a fake geometry based on the capacity.
4106 			 */
4107 			memcpy(&lun->mode_pages.rigid_disk_page[
4108 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4109 			       sizeof(rigid_disk_page_default));
4110 			memcpy(&lun->mode_pages.rigid_disk_page[
4111 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4112 			       sizeof(rigid_disk_page_changeable));
4113 
4114 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4115 				CTL_DEFAULT_HEADS;
4116 
4117 			/*
4118 			 * The divide method here will be more accurate,
4119 			 * probably, but results in floating point being
4120 			 * used in the kernel on i386 (__udivdi3()).  On the
4121 			 * XScale, though, __udivdi3() is implemented in
4122 			 * software.
4123 			 *
4124 			 * The shift method for cylinder calculation is
4125 			 * accurate if sectors_per_cylinder is a power of
4126 			 * 2.  Otherwise it might be slightly off -- you
4127 			 * might have a bit of a truncation problem.
4128 			 */
4129 #ifdef	__XSCALE__
4130 			cylinders = (lun->be_lun->maxlba + 1) /
4131 				sectors_per_cylinder;
4132 #else
4133 			for (shift = 31; shift > 0; shift--) {
4134 				if (sectors_per_cylinder & (1 << shift))
4135 					break;
4136 			}
4137 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4138 #endif
4139 
4140 			/*
4141 			 * We've basically got 3 bytes, or 24 bits for the
4142 			 * cylinder size in the mode page.  If we're over,
4143 			 * just round down to 2^24.
4144 			 */
4145 			if (cylinders > 0xffffff)
4146 				cylinders = 0xffffff;
4147 
4148 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4149 				CTL_PAGE_DEFAULT];
4150 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4151 
4152 			if ((value = dnvlist_get_string(lun->be_lun->options,
4153 			    "rpm", NULL)) != NULL) {
4154 				scsi_ulto2b(strtol(value, NULL, 0),
4155 				     rigid_disk_page->rotation_rate);
4156 			}
4157 
4158 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4159 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4160 			       sizeof(rigid_disk_page_default));
4161 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4162 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4163 			       sizeof(rigid_disk_page_default));
4164 
4165 			page_index->page_data =
4166 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4167 			break;
4168 		}
4169 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4170 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4171 			    ("subpage %#x for page %#x is incorrect!",
4172 			    page_index->subpage, page_code));
4173 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4174 			       &verify_er_page_default,
4175 			       sizeof(verify_er_page_default));
4176 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4177 			       &verify_er_page_changeable,
4178 			       sizeof(verify_er_page_changeable));
4179 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4180 			       &verify_er_page_default,
4181 			       sizeof(verify_er_page_default));
4182 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4183 			       &verify_er_page_default,
4184 			       sizeof(verify_er_page_default));
4185 			page_index->page_data =
4186 				(uint8_t *)lun->mode_pages.verify_er_page;
4187 			break;
4188 		}
4189 		case SMS_CACHING_PAGE: {
4190 			struct scsi_caching_page *caching_page;
4191 
4192 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4193 			    ("subpage %#x for page %#x is incorrect!",
4194 			    page_index->subpage, page_code));
4195 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4196 			       &caching_page_default,
4197 			       sizeof(caching_page_default));
4198 			memcpy(&lun->mode_pages.caching_page[
4199 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4200 			       sizeof(caching_page_changeable));
4201 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4202 			       &caching_page_default,
4203 			       sizeof(caching_page_default));
4204 			caching_page = &lun->mode_pages.caching_page[
4205 			    CTL_PAGE_SAVED];
4206 			value = dnvlist_get_string(lun->be_lun->options,
4207 			    "writecache", NULL);
4208 			if (value != NULL && strcmp(value, "off") == 0)
4209 				caching_page->flags1 &= ~SCP_WCE;
4210 			value = dnvlist_get_string(lun->be_lun->options,
4211 			    "readcache", NULL);
4212 			if (value != NULL && strcmp(value, "off") == 0)
4213 				caching_page->flags1 |= SCP_RCD;
4214 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4215 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4216 			       sizeof(caching_page_default));
4217 			page_index->page_data =
4218 				(uint8_t *)lun->mode_pages.caching_page;
4219 			break;
4220 		}
4221 		case SMS_CONTROL_MODE_PAGE: {
4222 			switch (page_index->subpage) {
4223 			case SMS_SUBPAGE_PAGE_0: {
4224 				struct scsi_control_page *control_page;
4225 
4226 				memcpy(&lun->mode_pages.control_page[
4227 				    CTL_PAGE_DEFAULT],
4228 				       &control_page_default,
4229 				       sizeof(control_page_default));
4230 				memcpy(&lun->mode_pages.control_page[
4231 				    CTL_PAGE_CHANGEABLE],
4232 				       &control_page_changeable,
4233 				       sizeof(control_page_changeable));
4234 				memcpy(&lun->mode_pages.control_page[
4235 				    CTL_PAGE_SAVED],
4236 				       &control_page_default,
4237 				       sizeof(control_page_default));
4238 				control_page = &lun->mode_pages.control_page[
4239 				    CTL_PAGE_SAVED];
4240 				value = dnvlist_get_string(lun->be_lun->options,
4241 				    "reordering", NULL);
4242 				if (value != NULL &&
4243 				    strcmp(value, "unrestricted") == 0) {
4244 					control_page->queue_flags &=
4245 					    ~SCP_QUEUE_ALG_MASK;
4246 					control_page->queue_flags |=
4247 					    SCP_QUEUE_ALG_UNRESTRICTED;
4248 				}
4249 				memcpy(&lun->mode_pages.control_page[
4250 				    CTL_PAGE_CURRENT],
4251 				       &lun->mode_pages.control_page[
4252 				    CTL_PAGE_SAVED],
4253 				       sizeof(control_page_default));
4254 				page_index->page_data =
4255 				    (uint8_t *)lun->mode_pages.control_page;
4256 				break;
4257 			}
4258 			case 0x01:
4259 				memcpy(&lun->mode_pages.control_ext_page[
4260 				    CTL_PAGE_DEFAULT],
4261 				       &control_ext_page_default,
4262 				       sizeof(control_ext_page_default));
4263 				memcpy(&lun->mode_pages.control_ext_page[
4264 				    CTL_PAGE_CHANGEABLE],
4265 				       &control_ext_page_changeable,
4266 				       sizeof(control_ext_page_changeable));
4267 				memcpy(&lun->mode_pages.control_ext_page[
4268 				    CTL_PAGE_SAVED],
4269 				       &control_ext_page_default,
4270 				       sizeof(control_ext_page_default));
4271 				memcpy(&lun->mode_pages.control_ext_page[
4272 				    CTL_PAGE_CURRENT],
4273 				       &lun->mode_pages.control_ext_page[
4274 				    CTL_PAGE_SAVED],
4275 				       sizeof(control_ext_page_default));
4276 				page_index->page_data =
4277 				    (uint8_t *)lun->mode_pages.control_ext_page;
4278 				break;
4279 			default:
4280 				panic("subpage %#x for page %#x is incorrect!",
4281 				      page_index->subpage, page_code);
4282 			}
4283 			break;
4284 		}
4285 		case SMS_INFO_EXCEPTIONS_PAGE: {
4286 			switch (page_index->subpage) {
4287 			case SMS_SUBPAGE_PAGE_0:
4288 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4289 				       &ie_page_default,
4290 				       sizeof(ie_page_default));
4291 				memcpy(&lun->mode_pages.ie_page[
4292 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4293 				       sizeof(ie_page_changeable));
4294 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4295 				       &ie_page_default,
4296 				       sizeof(ie_page_default));
4297 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4298 				       &ie_page_default,
4299 				       sizeof(ie_page_default));
4300 				page_index->page_data =
4301 					(uint8_t *)lun->mode_pages.ie_page;
4302 				break;
4303 			case 0x02: {
4304 				struct ctl_logical_block_provisioning_page *page;
4305 
4306 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4307 				       &lbp_page_default,
4308 				       sizeof(lbp_page_default));
4309 				memcpy(&lun->mode_pages.lbp_page[
4310 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4311 				       sizeof(lbp_page_changeable));
4312 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4313 				       &lbp_page_default,
4314 				       sizeof(lbp_page_default));
4315 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4316 				value = dnvlist_get_string(lun->be_lun->options,
4317 				    "avail-threshold", NULL);
4318 				if (value != NULL &&
4319 				    ctl_expand_number(value, &ival) == 0) {
4320 					page->descr[0].flags |= SLBPPD_ENABLED |
4321 					    SLBPPD_ARMING_DEC;
4322 					if (lun->be_lun->blocksize)
4323 						ival /= lun->be_lun->blocksize;
4324 					else
4325 						ival /= 512;
4326 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4327 					    page->descr[0].count);
4328 				}
4329 				value = dnvlist_get_string(lun->be_lun->options,
4330 				    "used-threshold", NULL);
4331 				if (value != NULL &&
4332 				    ctl_expand_number(value, &ival) == 0) {
4333 					page->descr[1].flags |= SLBPPD_ENABLED |
4334 					    SLBPPD_ARMING_INC;
4335 					if (lun->be_lun->blocksize)
4336 						ival /= lun->be_lun->blocksize;
4337 					else
4338 						ival /= 512;
4339 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4340 					    page->descr[1].count);
4341 				}
4342 				value = dnvlist_get_string(lun->be_lun->options,
4343 				    "pool-avail-threshold", NULL);
4344 				if (value != NULL &&
4345 				    ctl_expand_number(value, &ival) == 0) {
4346 					page->descr[2].flags |= SLBPPD_ENABLED |
4347 					    SLBPPD_ARMING_DEC;
4348 					if (lun->be_lun->blocksize)
4349 						ival /= lun->be_lun->blocksize;
4350 					else
4351 						ival /= 512;
4352 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4353 					    page->descr[2].count);
4354 				}
4355 				value = dnvlist_get_string(lun->be_lun->options,
4356 				    "pool-used-threshold", NULL);
4357 				if (value != NULL &&
4358 				    ctl_expand_number(value, &ival) == 0) {
4359 					page->descr[3].flags |= SLBPPD_ENABLED |
4360 					    SLBPPD_ARMING_INC;
4361 					if (lun->be_lun->blocksize)
4362 						ival /= lun->be_lun->blocksize;
4363 					else
4364 						ival /= 512;
4365 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4366 					    page->descr[3].count);
4367 				}
4368 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4369 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4370 				       sizeof(lbp_page_default));
4371 				page_index->page_data =
4372 					(uint8_t *)lun->mode_pages.lbp_page;
4373 				break;
4374 			}
4375 			default:
4376 				panic("subpage %#x for page %#x is incorrect!",
4377 				      page_index->subpage, page_code);
4378 			}
4379 			break;
4380 		}
4381 		case SMS_CDDVD_CAPS_PAGE:{
4382 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4383 			    ("subpage %#x for page %#x is incorrect!",
4384 			    page_index->subpage, page_code));
4385 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4386 			       &cddvd_page_default,
4387 			       sizeof(cddvd_page_default));
4388 			memcpy(&lun->mode_pages.cddvd_page[
4389 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4390 			       sizeof(cddvd_page_changeable));
4391 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4392 			       &cddvd_page_default,
4393 			       sizeof(cddvd_page_default));
4394 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4395 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4396 			       sizeof(cddvd_page_default));
4397 			page_index->page_data =
4398 				(uint8_t *)lun->mode_pages.cddvd_page;
4399 			break;
4400 		}
4401 		default:
4402 			panic("invalid page code value %#x", page_code);
4403 		}
4404 	}
4405 
4406 	return (CTL_RETVAL_COMPLETE);
4407 }
4408 
4409 static int
4410 ctl_init_log_page_index(struct ctl_lun *lun)
4411 {
4412 	struct ctl_page_index *page_index;
4413 	int i, j, k, prev;
4414 
4415 	memcpy(&lun->log_pages.index, log_page_index_template,
4416 	       sizeof(log_page_index_template));
4417 
4418 	prev = -1;
4419 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4420 
4421 		page_index = &lun->log_pages.index[i];
4422 		if (lun->be_lun->lun_type == T_DIRECT &&
4423 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4424 			continue;
4425 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4426 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4427 			continue;
4428 		if (lun->be_lun->lun_type == T_CDROM &&
4429 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4430 			continue;
4431 
4432 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4433 		    lun->backend->lun_attr == NULL)
4434 			continue;
4435 
4436 		if (page_index->page_code != prev) {
4437 			lun->log_pages.pages_page[j] = page_index->page_code;
4438 			prev = page_index->page_code;
4439 			j++;
4440 		}
4441 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4442 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4443 		k++;
4444 	}
4445 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4446 	lun->log_pages.index[0].page_len = j;
4447 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4448 	lun->log_pages.index[1].page_len = k * 2;
4449 	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4450 	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4451 	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4452 	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4453 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4454 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4455 
4456 	return (CTL_RETVAL_COMPLETE);
4457 }
4458 
4459 static int
4460 hex2bin(const char *str, uint8_t *buf, int buf_size)
4461 {
4462 	int i;
4463 	u_char c;
4464 
4465 	memset(buf, 0, buf_size);
4466 	while (isspace(str[0]))
4467 		str++;
4468 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4469 		str += 2;
4470 	buf_size *= 2;
4471 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4472 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4473 			str++;
4474 		c = str[i];
4475 		if (isdigit(c))
4476 			c -= '0';
4477 		else if (isalpha(c))
4478 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4479 		else
4480 			break;
4481 		if (c >= 16)
4482 			break;
4483 		if ((i & 1) == 0)
4484 			buf[i / 2] |= (c << 4);
4485 		else
4486 			buf[i / 2] |= c;
4487 	}
4488 	return ((i + 1) / 2);
4489 }
4490 
4491 /*
4492  * LUN allocation.
4493  *
4494  * Requirements:
4495  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4496  *   wants us to allocate the LUN and he can block.
4497  * - ctl_softc is always set
4498  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4499  *
4500  * Returns 0 for success, non-zero (errno) for failure.
4501  */
4502 static int
4503 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4504 	      struct ctl_be_lun *const be_lun)
4505 {
4506 	struct ctl_lun *nlun, *lun;
4507 	struct scsi_vpd_id_descriptor *desc;
4508 	struct scsi_vpd_id_t10 *t10id;
4509 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4510 	int lun_number, lun_malloced;
4511 	int devidlen, idlen1, idlen2 = 0, len;
4512 
4513 	if (be_lun == NULL)
4514 		return (EINVAL);
4515 
4516 	/*
4517 	 * We currently only support Direct Access or Processor LUN types.
4518 	 */
4519 	switch (be_lun->lun_type) {
4520 	case T_DIRECT:
4521 	case T_PROCESSOR:
4522 	case T_CDROM:
4523 		break;
4524 	case T_SEQUENTIAL:
4525 	case T_CHANGER:
4526 	default:
4527 		be_lun->lun_config_status(be_lun->be_lun,
4528 					  CTL_LUN_CONFIG_FAILURE);
4529 		break;
4530 	}
4531 	if (ctl_lun == NULL) {
4532 		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4533 		lun_malloced = 1;
4534 	} else {
4535 		lun_malloced = 0;
4536 		lun = ctl_lun;
4537 	}
4538 
4539 	memset(lun, 0, sizeof(*lun));
4540 	if (lun_malloced)
4541 		lun->flags = CTL_LUN_MALLOCED;
4542 
4543 	lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4544 	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4545 	lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4546 	    M_DEVBUF, M_WAITOK | M_ZERO);
4547 	lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4548 	    M_DEVBUF, M_WAITOK | M_ZERO);
4549 
4550 	/* Generate LUN ID. */
4551 	devidlen = max(CTL_DEVID_MIN_LEN,
4552 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4553 	idlen1 = sizeof(*t10id) + devidlen;
4554 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4555 	scsiname = dnvlist_get_string(be_lun->options, "scsiname", NULL);
4556 	if (scsiname != NULL) {
4557 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4558 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4559 	}
4560 	eui = dnvlist_get_string(be_lun->options, "eui", NULL);
4561 	if (eui != NULL) {
4562 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4563 	}
4564 	naa = dnvlist_get_string(be_lun->options, "naa", NULL);
4565 	if (naa != NULL) {
4566 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4567 	}
4568 	uuid = dnvlist_get_string(be_lun->options, "uuid", NULL);
4569 	if (uuid != NULL) {
4570 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4571 	}
4572 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4573 	    M_CTL, M_WAITOK | M_ZERO);
4574 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4575 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4576 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4577 	desc->length = idlen1;
4578 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4579 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4580 	if ((vendor = dnvlist_get_string(be_lun->options, "vendor", NULL)) == NULL) {
4581 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4582 	} else {
4583 		strncpy(t10id->vendor, vendor,
4584 		    min(sizeof(t10id->vendor), strlen(vendor)));
4585 	}
4586 	strncpy((char *)t10id->vendor_spec_id,
4587 	    (char *)be_lun->device_id, devidlen);
4588 	if (scsiname != NULL) {
4589 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4590 		    desc->length);
4591 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4592 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4593 		    SVPD_ID_TYPE_SCSI_NAME;
4594 		desc->length = idlen2;
4595 		strlcpy(desc->identifier, scsiname, idlen2);
4596 	}
4597 	if (eui != NULL) {
4598 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4599 		    desc->length);
4600 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4601 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4602 		    SVPD_ID_TYPE_EUI64;
4603 		desc->length = hex2bin(eui, desc->identifier, 16);
4604 		desc->length = desc->length > 12 ? 16 :
4605 		    (desc->length > 8 ? 12 : 8);
4606 		len -= 16 - desc->length;
4607 	}
4608 	if (naa != NULL) {
4609 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4610 		    desc->length);
4611 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4612 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4613 		    SVPD_ID_TYPE_NAA;
4614 		desc->length = hex2bin(naa, desc->identifier, 16);
4615 		desc->length = desc->length > 8 ? 16 : 8;
4616 		len -= 16 - desc->length;
4617 	}
4618 	if (uuid != NULL) {
4619 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4620 		    desc->length);
4621 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4622 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4623 		    SVPD_ID_TYPE_UUID;
4624 		desc->identifier[0] = 0x10;
4625 		hex2bin(uuid, &desc->identifier[2], 16);
4626 		desc->length = 18;
4627 	}
4628 	lun->lun_devid->len = len;
4629 
4630 	mtx_lock(&ctl_softc->ctl_lock);
4631 	/*
4632 	 * See if the caller requested a particular LUN number.  If so, see
4633 	 * if it is available.  Otherwise, allocate the first available LUN.
4634 	 */
4635 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4636 		if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4637 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4638 			mtx_unlock(&ctl_softc->ctl_lock);
4639 			if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4640 				printf("ctl: requested LUN ID %d is higher "
4641 				       "than ctl_max_luns - 1 (%d)\n",
4642 				       be_lun->req_lun_id, ctl_max_luns - 1);
4643 			} else {
4644 				/*
4645 				 * XXX KDM return an error, or just assign
4646 				 * another LUN ID in this case??
4647 				 */
4648 				printf("ctl: requested LUN ID %d is already "
4649 				       "in use\n", be_lun->req_lun_id);
4650 			}
4651 fail:
4652 			free(lun->lun_devid, M_CTL);
4653 			if (lun->flags & CTL_LUN_MALLOCED)
4654 				free(lun, M_CTL);
4655 			be_lun->lun_config_status(be_lun->be_lun,
4656 						  CTL_LUN_CONFIG_FAILURE);
4657 			return (ENOSPC);
4658 		}
4659 		lun_number = be_lun->req_lun_id;
4660 	} else {
4661 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4662 		if (lun_number == -1) {
4663 			mtx_unlock(&ctl_softc->ctl_lock);
4664 			printf("ctl: can't allocate LUN, out of LUNs\n");
4665 			goto fail;
4666 		}
4667 	}
4668 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4669 	mtx_unlock(&ctl_softc->ctl_lock);
4670 
4671 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4672 	lun->lun = lun_number;
4673 	lun->be_lun = be_lun;
4674 	/*
4675 	 * The processor LUN is always enabled.  Disk LUNs come on line
4676 	 * disabled, and must be enabled by the backend.
4677 	 */
4678 	lun->flags |= CTL_LUN_DISABLED;
4679 	lun->backend = be_lun->be;
4680 	be_lun->ctl_lun = lun;
4681 	be_lun->lun_id = lun_number;
4682 	atomic_add_int(&be_lun->be->num_luns, 1);
4683 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4684 		lun->flags |= CTL_LUN_EJECTED;
4685 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4686 		lun->flags |= CTL_LUN_NO_MEDIA;
4687 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4688 		lun->flags |= CTL_LUN_STOPPED;
4689 
4690 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4691 		lun->flags |= CTL_LUN_PRIMARY_SC;
4692 
4693 	value = dnvlist_get_string(be_lun->options, "removable", NULL);
4694 	if (value != NULL) {
4695 		if (strcmp(value, "on") == 0)
4696 			lun->flags |= CTL_LUN_REMOVABLE;
4697 	} else if (be_lun->lun_type == T_CDROM)
4698 		lun->flags |= CTL_LUN_REMOVABLE;
4699 
4700 	lun->ctl_softc = ctl_softc;
4701 #ifdef CTL_TIME_IO
4702 	lun->last_busy = getsbinuptime();
4703 #endif
4704 	TAILQ_INIT(&lun->ooa_queue);
4705 	STAILQ_INIT(&lun->error_list);
4706 	lun->ie_reported = 1;
4707 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4708 	ctl_tpc_lun_init(lun);
4709 	if (lun->flags & CTL_LUN_REMOVABLE) {
4710 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4711 		    M_CTL, M_WAITOK);
4712 	}
4713 
4714 	/*
4715 	 * Initialize the mode and log page index.
4716 	 */
4717 	ctl_init_page_index(lun);
4718 	ctl_init_log_page_index(lun);
4719 
4720 	/* Setup statistics gathering */
4721 	lun->stats.item = lun_number;
4722 
4723 	/*
4724 	 * Now, before we insert this lun on the lun list, set the lun
4725 	 * inventory changed UA for all other luns.
4726 	 */
4727 	mtx_lock(&ctl_softc->ctl_lock);
4728 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4729 		mtx_lock(&nlun->lun_lock);
4730 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4731 		mtx_unlock(&nlun->lun_lock);
4732 	}
4733 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4734 	ctl_softc->ctl_luns[lun_number] = lun;
4735 	ctl_softc->num_luns++;
4736 	mtx_unlock(&ctl_softc->ctl_lock);
4737 
4738 	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4739 	return (0);
4740 }
4741 
4742 /*
4743  * Delete a LUN.
4744  * Assumptions:
4745  * - LUN has already been marked invalid and any pending I/O has been taken
4746  *   care of.
4747  */
4748 static int
4749 ctl_free_lun(struct ctl_lun *lun)
4750 {
4751 	struct ctl_softc *softc = lun->ctl_softc;
4752 	struct ctl_lun *nlun;
4753 	int i;
4754 
4755 	KASSERT(TAILQ_EMPTY(&lun->ooa_queue),
4756 	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4757 
4758 	mtx_lock(&softc->ctl_lock);
4759 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4760 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4761 	softc->ctl_luns[lun->lun] = NULL;
4762 	softc->num_luns--;
4763 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4764 		mtx_lock(&nlun->lun_lock);
4765 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4766 		mtx_unlock(&nlun->lun_lock);
4767 	}
4768 	mtx_unlock(&softc->ctl_lock);
4769 
4770 	/*
4771 	 * Tell the backend to free resources, if this LUN has a backend.
4772 	 */
4773 	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4774 	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4775 
4776 	lun->ie_reportcnt = UINT32_MAX;
4777 	callout_drain(&lun->ie_callout);
4778 	ctl_tpc_lun_shutdown(lun);
4779 	mtx_destroy(&lun->lun_lock);
4780 	free(lun->lun_devid, M_CTL);
4781 	for (i = 0; i < ctl_max_ports; i++)
4782 		free(lun->pending_ua[i], M_CTL);
4783 	free(lun->pending_ua, M_DEVBUF);
4784 	for (i = 0; i < ctl_max_ports; i++)
4785 		free(lun->pr_keys[i], M_CTL);
4786 	free(lun->pr_keys, M_DEVBUF);
4787 	free(lun->write_buffer, M_CTL);
4788 	free(lun->prevent, M_CTL);
4789 	if (lun->flags & CTL_LUN_MALLOCED)
4790 		free(lun, M_CTL);
4791 
4792 	return (0);
4793 }
4794 
4795 static void
4796 ctl_create_lun(struct ctl_be_lun *be_lun)
4797 {
4798 
4799 	/*
4800 	 * ctl_alloc_lun() should handle all potential failure cases.
4801 	 */
4802 	ctl_alloc_lun(control_softc, NULL, be_lun);
4803 }
4804 
4805 int
4806 ctl_add_lun(struct ctl_be_lun *be_lun)
4807 {
4808 	struct ctl_softc *softc = control_softc;
4809 
4810 	mtx_lock(&softc->ctl_lock);
4811 	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4812 	mtx_unlock(&softc->ctl_lock);
4813 	wakeup(&softc->pending_lun_queue);
4814 
4815 	return (0);
4816 }
4817 
4818 int
4819 ctl_enable_lun(struct ctl_be_lun *be_lun)
4820 {
4821 	struct ctl_softc *softc;
4822 	struct ctl_port *port, *nport;
4823 	struct ctl_lun *lun;
4824 	int retval;
4825 
4826 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4827 	softc = lun->ctl_softc;
4828 
4829 	mtx_lock(&softc->ctl_lock);
4830 	mtx_lock(&lun->lun_lock);
4831 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4832 		/*
4833 		 * eh?  Why did we get called if the LUN is already
4834 		 * enabled?
4835 		 */
4836 		mtx_unlock(&lun->lun_lock);
4837 		mtx_unlock(&softc->ctl_lock);
4838 		return (0);
4839 	}
4840 	lun->flags &= ~CTL_LUN_DISABLED;
4841 	mtx_unlock(&lun->lun_lock);
4842 
4843 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4844 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4845 		    port->lun_map != NULL || port->lun_enable == NULL)
4846 			continue;
4847 
4848 		/*
4849 		 * Drop the lock while we call the FETD's enable routine.
4850 		 * This can lead to a callback into CTL (at least in the
4851 		 * case of the internal initiator frontend.
4852 		 */
4853 		mtx_unlock(&softc->ctl_lock);
4854 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4855 		mtx_lock(&softc->ctl_lock);
4856 		if (retval != 0) {
4857 			printf("%s: FETD %s port %d returned error "
4858 			       "%d for lun_enable on lun %jd\n",
4859 			       __func__, port->port_name, port->targ_port,
4860 			       retval, (intmax_t)lun->lun);
4861 		}
4862 	}
4863 
4864 	mtx_unlock(&softc->ctl_lock);
4865 	ctl_isc_announce_lun(lun);
4866 
4867 	return (0);
4868 }
4869 
4870 int
4871 ctl_disable_lun(struct ctl_be_lun *be_lun)
4872 {
4873 	struct ctl_softc *softc;
4874 	struct ctl_port *port;
4875 	struct ctl_lun *lun;
4876 	int retval;
4877 
4878 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4879 	softc = lun->ctl_softc;
4880 
4881 	mtx_lock(&softc->ctl_lock);
4882 	mtx_lock(&lun->lun_lock);
4883 	if (lun->flags & CTL_LUN_DISABLED) {
4884 		mtx_unlock(&lun->lun_lock);
4885 		mtx_unlock(&softc->ctl_lock);
4886 		return (0);
4887 	}
4888 	lun->flags |= CTL_LUN_DISABLED;
4889 	mtx_unlock(&lun->lun_lock);
4890 
4891 	STAILQ_FOREACH(port, &softc->port_list, links) {
4892 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4893 		    port->lun_map != NULL || port->lun_disable == NULL)
4894 			continue;
4895 
4896 		/*
4897 		 * Drop the lock before we call the frontend's disable
4898 		 * routine, to avoid lock order reversals.
4899 		 *
4900 		 * XXX KDM what happens if the frontend list changes while
4901 		 * we're traversing it?  It's unlikely, but should be handled.
4902 		 */
4903 		mtx_unlock(&softc->ctl_lock);
4904 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4905 		mtx_lock(&softc->ctl_lock);
4906 		if (retval != 0) {
4907 			printf("%s: FETD %s port %d returned error "
4908 			       "%d for lun_disable on lun %jd\n",
4909 			       __func__, port->port_name, port->targ_port,
4910 			       retval, (intmax_t)lun->lun);
4911 		}
4912 	}
4913 
4914 	mtx_unlock(&softc->ctl_lock);
4915 	ctl_isc_announce_lun(lun);
4916 
4917 	return (0);
4918 }
4919 
4920 int
4921 ctl_start_lun(struct ctl_be_lun *be_lun)
4922 {
4923 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4924 
4925 	mtx_lock(&lun->lun_lock);
4926 	lun->flags &= ~CTL_LUN_STOPPED;
4927 	mtx_unlock(&lun->lun_lock);
4928 	return (0);
4929 }
4930 
4931 int
4932 ctl_stop_lun(struct ctl_be_lun *be_lun)
4933 {
4934 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4935 
4936 	mtx_lock(&lun->lun_lock);
4937 	lun->flags |= CTL_LUN_STOPPED;
4938 	mtx_unlock(&lun->lun_lock);
4939 	return (0);
4940 }
4941 
4942 int
4943 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4944 {
4945 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4946 
4947 	mtx_lock(&lun->lun_lock);
4948 	lun->flags |= CTL_LUN_NO_MEDIA;
4949 	mtx_unlock(&lun->lun_lock);
4950 	return (0);
4951 }
4952 
4953 int
4954 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4955 {
4956 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4957 	union ctl_ha_msg msg;
4958 
4959 	mtx_lock(&lun->lun_lock);
4960 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4961 	if (lun->flags & CTL_LUN_REMOVABLE)
4962 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4963 	mtx_unlock(&lun->lun_lock);
4964 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4965 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4966 		bzero(&msg.ua, sizeof(msg.ua));
4967 		msg.hdr.msg_type = CTL_MSG_UA;
4968 		msg.hdr.nexus.initid = -1;
4969 		msg.hdr.nexus.targ_port = -1;
4970 		msg.hdr.nexus.targ_lun = lun->lun;
4971 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4972 		msg.ua.ua_all = 1;
4973 		msg.ua.ua_set = 1;
4974 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4975 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4976 		    M_WAITOK);
4977 	}
4978 	return (0);
4979 }
4980 
4981 int
4982 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4983 {
4984 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4985 
4986 	mtx_lock(&lun->lun_lock);
4987 	lun->flags |= CTL_LUN_EJECTED;
4988 	mtx_unlock(&lun->lun_lock);
4989 	return (0);
4990 }
4991 
4992 int
4993 ctl_lun_primary(struct ctl_be_lun *be_lun)
4994 {
4995 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4996 
4997 	mtx_lock(&lun->lun_lock);
4998 	lun->flags |= CTL_LUN_PRIMARY_SC;
4999 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5000 	mtx_unlock(&lun->lun_lock);
5001 	ctl_isc_announce_lun(lun);
5002 	return (0);
5003 }
5004 
5005 int
5006 ctl_lun_secondary(struct ctl_be_lun *be_lun)
5007 {
5008 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5009 
5010 	mtx_lock(&lun->lun_lock);
5011 	lun->flags &= ~CTL_LUN_PRIMARY_SC;
5012 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5013 	mtx_unlock(&lun->lun_lock);
5014 	ctl_isc_announce_lun(lun);
5015 	return (0);
5016 }
5017 
5018 int
5019 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
5020 {
5021 	struct ctl_lun *lun;
5022 
5023 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5024 
5025 	mtx_lock(&lun->lun_lock);
5026 
5027 	/*
5028 	 * The LUN needs to be disabled before it can be marked invalid.
5029 	 */
5030 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5031 		mtx_unlock(&lun->lun_lock);
5032 		return (-1);
5033 	}
5034 	/*
5035 	 * Mark the LUN invalid.
5036 	 */
5037 	lun->flags |= CTL_LUN_INVALID;
5038 
5039 	/*
5040 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5041 	 * If we have something in the OOA queue, we'll free it when the
5042 	 * last I/O completes.
5043 	 */
5044 	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5045 		mtx_unlock(&lun->lun_lock);
5046 		ctl_free_lun(lun);
5047 	} else
5048 		mtx_unlock(&lun->lun_lock);
5049 
5050 	return (0);
5051 }
5052 
5053 void
5054 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5055 {
5056 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5057 	union ctl_ha_msg msg;
5058 
5059 	mtx_lock(&lun->lun_lock);
5060 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5061 	mtx_unlock(&lun->lun_lock);
5062 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5063 		/* Send msg to other side. */
5064 		bzero(&msg.ua, sizeof(msg.ua));
5065 		msg.hdr.msg_type = CTL_MSG_UA;
5066 		msg.hdr.nexus.initid = -1;
5067 		msg.hdr.nexus.targ_port = -1;
5068 		msg.hdr.nexus.targ_lun = lun->lun;
5069 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5070 		msg.ua.ua_all = 1;
5071 		msg.ua.ua_set = 1;
5072 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5073 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5074 		    M_WAITOK);
5075 	}
5076 }
5077 
5078 /*
5079  * Backend "memory move is complete" callback for requests that never
5080  * make it down to say RAIDCore's configuration code.
5081  */
5082 int
5083 ctl_config_move_done(union ctl_io *io)
5084 {
5085 	int retval;
5086 
5087 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5088 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5089 	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5090 
5091 	if ((io->io_hdr.port_status != 0) &&
5092 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5093 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5094 		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
5095 		    /*retry_count*/ io->io_hdr.port_status);
5096 	} else if (io->scsiio.kern_data_resid != 0 &&
5097 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
5098 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5099 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5100 		ctl_set_invalid_field_ciu(&io->scsiio);
5101 	}
5102 
5103 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5104 		ctl_data_print(io);
5105 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5106 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5107 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5108 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5109 		/*
5110 		 * XXX KDM just assuming a single pointer here, and not a
5111 		 * S/G list.  If we start using S/G lists for config data,
5112 		 * we'll need to know how to clean them up here as well.
5113 		 */
5114 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5115 			free(io->scsiio.kern_data_ptr, M_CTL);
5116 		ctl_done(io);
5117 		retval = CTL_RETVAL_COMPLETE;
5118 	} else {
5119 		/*
5120 		 * XXX KDM now we need to continue data movement.  Some
5121 		 * options:
5122 		 * - call ctl_scsiio() again?  We don't do this for data
5123 		 *   writes, because for those at least we know ahead of
5124 		 *   time where the write will go and how long it is.  For
5125 		 *   config writes, though, that information is largely
5126 		 *   contained within the write itself, thus we need to
5127 		 *   parse out the data again.
5128 		 *
5129 		 * - Call some other function once the data is in?
5130 		 */
5131 
5132 		/*
5133 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5134 		 * bits to see whether we're allocated or not.
5135 		 */
5136 		retval = ctl_scsiio(&io->scsiio);
5137 	}
5138 	return (retval);
5139 }
5140 
5141 /*
5142  * This gets called by a backend driver when it is done with a
5143  * data_submit method.
5144  */
5145 void
5146 ctl_data_submit_done(union ctl_io *io)
5147 {
5148 	/*
5149 	 * If the IO_CONT flag is set, we need to call the supplied
5150 	 * function to continue processing the I/O, instead of completing
5151 	 * the I/O just yet.
5152 	 *
5153 	 * If there is an error, though, we don't want to keep processing.
5154 	 * Instead, just send status back to the initiator.
5155 	 */
5156 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5157 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5158 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5159 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5160 		io->scsiio.io_cont(io);
5161 		return;
5162 	}
5163 	ctl_done(io);
5164 }
5165 
5166 /*
5167  * This gets called by a backend driver when it is done with a
5168  * configuration write.
5169  */
5170 void
5171 ctl_config_write_done(union ctl_io *io)
5172 {
5173 	uint8_t *buf;
5174 
5175 	/*
5176 	 * If the IO_CONT flag is set, we need to call the supplied
5177 	 * function to continue processing the I/O, instead of completing
5178 	 * the I/O just yet.
5179 	 *
5180 	 * If there is an error, though, we don't want to keep processing.
5181 	 * Instead, just send status back to the initiator.
5182 	 */
5183 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5184 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5185 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5186 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5187 		io->scsiio.io_cont(io);
5188 		return;
5189 	}
5190 	/*
5191 	 * Since a configuration write can be done for commands that actually
5192 	 * have data allocated, like write buffer, and commands that have
5193 	 * no data, like start/stop unit, we need to check here.
5194 	 */
5195 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5196 		buf = io->scsiio.kern_data_ptr;
5197 	else
5198 		buf = NULL;
5199 	ctl_done(io);
5200 	if (buf)
5201 		free(buf, M_CTL);
5202 }
5203 
5204 void
5205 ctl_config_read_done(union ctl_io *io)
5206 {
5207 	uint8_t *buf;
5208 
5209 	/*
5210 	 * If there is some error -- we are done, skip data transfer.
5211 	 */
5212 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5213 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5214 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5215 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5216 			buf = io->scsiio.kern_data_ptr;
5217 		else
5218 			buf = NULL;
5219 		ctl_done(io);
5220 		if (buf)
5221 			free(buf, M_CTL);
5222 		return;
5223 	}
5224 
5225 	/*
5226 	 * If the IO_CONT flag is set, we need to call the supplied
5227 	 * function to continue processing the I/O, instead of completing
5228 	 * the I/O just yet.
5229 	 */
5230 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5231 		io->scsiio.io_cont(io);
5232 		return;
5233 	}
5234 
5235 	ctl_datamove(io);
5236 }
5237 
5238 /*
5239  * SCSI release command.
5240  */
5241 int
5242 ctl_scsi_release(struct ctl_scsiio *ctsio)
5243 {
5244 	struct ctl_lun *lun = CTL_LUN(ctsio);
5245 	uint32_t residx;
5246 
5247 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5248 
5249 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5250 
5251 	/*
5252 	 * XXX KDM right now, we only support LUN reservation.  We don't
5253 	 * support 3rd party reservations, or extent reservations, which
5254 	 * might actually need the parameter list.  If we've gotten this
5255 	 * far, we've got a LUN reservation.  Anything else got kicked out
5256 	 * above.  So, according to SPC, ignore the length.
5257 	 */
5258 
5259 	mtx_lock(&lun->lun_lock);
5260 
5261 	/*
5262 	 * According to SPC, it is not an error for an intiator to attempt
5263 	 * to release a reservation on a LUN that isn't reserved, or that
5264 	 * is reserved by another initiator.  The reservation can only be
5265 	 * released, though, by the initiator who made it or by one of
5266 	 * several reset type events.
5267 	 */
5268 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5269 			lun->flags &= ~CTL_LUN_RESERVED;
5270 
5271 	mtx_unlock(&lun->lun_lock);
5272 
5273 	ctl_set_success(ctsio);
5274 	ctl_done((union ctl_io *)ctsio);
5275 	return (CTL_RETVAL_COMPLETE);
5276 }
5277 
5278 int
5279 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5280 {
5281 	struct ctl_lun *lun = CTL_LUN(ctsio);
5282 	uint32_t residx;
5283 
5284 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5285 
5286 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5287 
5288 	/*
5289 	 * XXX KDM right now, we only support LUN reservation.  We don't
5290 	 * support 3rd party reservations, or extent reservations, which
5291 	 * might actually need the parameter list.  If we've gotten this
5292 	 * far, we've got a LUN reservation.  Anything else got kicked out
5293 	 * above.  So, according to SPC, ignore the length.
5294 	 */
5295 
5296 	mtx_lock(&lun->lun_lock);
5297 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5298 		ctl_set_reservation_conflict(ctsio);
5299 		goto bailout;
5300 	}
5301 
5302 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5303 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5304 		ctl_set_success(ctsio);
5305 		goto bailout;
5306 	}
5307 
5308 	lun->flags |= CTL_LUN_RESERVED;
5309 	lun->res_idx = residx;
5310 	ctl_set_success(ctsio);
5311 
5312 bailout:
5313 	mtx_unlock(&lun->lun_lock);
5314 	ctl_done((union ctl_io *)ctsio);
5315 	return (CTL_RETVAL_COMPLETE);
5316 }
5317 
5318 int
5319 ctl_start_stop(struct ctl_scsiio *ctsio)
5320 {
5321 	struct ctl_lun *lun = CTL_LUN(ctsio);
5322 	struct scsi_start_stop_unit *cdb;
5323 	int retval;
5324 
5325 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5326 
5327 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5328 
5329 	if ((cdb->how & SSS_PC_MASK) == 0) {
5330 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5331 		    (cdb->how & SSS_START) == 0) {
5332 			uint32_t residx;
5333 
5334 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5335 			if (ctl_get_prkey(lun, residx) == 0 ||
5336 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5337 
5338 				ctl_set_reservation_conflict(ctsio);
5339 				ctl_done((union ctl_io *)ctsio);
5340 				return (CTL_RETVAL_COMPLETE);
5341 			}
5342 		}
5343 
5344 		if ((cdb->how & SSS_LOEJ) &&
5345 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5346 			ctl_set_invalid_field(ctsio,
5347 					      /*sks_valid*/ 1,
5348 					      /*command*/ 1,
5349 					      /*field*/ 4,
5350 					      /*bit_valid*/ 1,
5351 					      /*bit*/ 1);
5352 			ctl_done((union ctl_io *)ctsio);
5353 			return (CTL_RETVAL_COMPLETE);
5354 		}
5355 
5356 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5357 		    lun->prevent_count > 0) {
5358 			/* "Medium removal prevented" */
5359 			ctl_set_sense(ctsio, /*current_error*/ 1,
5360 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5361 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5362 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5363 			ctl_done((union ctl_io *)ctsio);
5364 			return (CTL_RETVAL_COMPLETE);
5365 		}
5366 	}
5367 
5368 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5369 	return (retval);
5370 }
5371 
5372 int
5373 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5374 {
5375 	struct ctl_lun *lun = CTL_LUN(ctsio);
5376 	struct scsi_prevent *cdb;
5377 	int retval;
5378 	uint32_t initidx;
5379 
5380 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5381 
5382 	cdb = (struct scsi_prevent *)ctsio->cdb;
5383 
5384 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5385 		ctl_set_invalid_opcode(ctsio);
5386 		ctl_done((union ctl_io *)ctsio);
5387 		return (CTL_RETVAL_COMPLETE);
5388 	}
5389 
5390 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5391 	mtx_lock(&lun->lun_lock);
5392 	if ((cdb->how & PR_PREVENT) &&
5393 	    ctl_is_set(lun->prevent, initidx) == 0) {
5394 		ctl_set_mask(lun->prevent, initidx);
5395 		lun->prevent_count++;
5396 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5397 	    ctl_is_set(lun->prevent, initidx)) {
5398 		ctl_clear_mask(lun->prevent, initidx);
5399 		lun->prevent_count--;
5400 	}
5401 	mtx_unlock(&lun->lun_lock);
5402 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5403 	return (retval);
5404 }
5405 
5406 /*
5407  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5408  * we don't really do anything with the LBA and length fields if the user
5409  * passes them in.  Instead we'll just flush out the cache for the entire
5410  * LUN.
5411  */
5412 int
5413 ctl_sync_cache(struct ctl_scsiio *ctsio)
5414 {
5415 	struct ctl_lun *lun = CTL_LUN(ctsio);
5416 	struct ctl_lba_len_flags *lbalen;
5417 	uint64_t starting_lba;
5418 	uint32_t block_count;
5419 	int retval;
5420 	uint8_t byte2;
5421 
5422 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5423 
5424 	retval = 0;
5425 
5426 	switch (ctsio->cdb[0]) {
5427 	case SYNCHRONIZE_CACHE: {
5428 		struct scsi_sync_cache *cdb;
5429 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5430 
5431 		starting_lba = scsi_4btoul(cdb->begin_lba);
5432 		block_count = scsi_2btoul(cdb->lb_count);
5433 		byte2 = cdb->byte2;
5434 		break;
5435 	}
5436 	case SYNCHRONIZE_CACHE_16: {
5437 		struct scsi_sync_cache_16 *cdb;
5438 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5439 
5440 		starting_lba = scsi_8btou64(cdb->begin_lba);
5441 		block_count = scsi_4btoul(cdb->lb_count);
5442 		byte2 = cdb->byte2;
5443 		break;
5444 	}
5445 	default:
5446 		ctl_set_invalid_opcode(ctsio);
5447 		ctl_done((union ctl_io *)ctsio);
5448 		goto bailout;
5449 		break; /* NOTREACHED */
5450 	}
5451 
5452 	/*
5453 	 * We check the LBA and length, but don't do anything with them.
5454 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5455 	 * get flushed.  This check will just help satisfy anyone who wants
5456 	 * to see an error for an out of range LBA.
5457 	 */
5458 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5459 		ctl_set_lba_out_of_range(ctsio,
5460 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5461 		ctl_done((union ctl_io *)ctsio);
5462 		goto bailout;
5463 	}
5464 
5465 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5466 	lbalen->lba = starting_lba;
5467 	lbalen->len = block_count;
5468 	lbalen->flags = byte2;
5469 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5470 
5471 bailout:
5472 	return (retval);
5473 }
5474 
5475 int
5476 ctl_format(struct ctl_scsiio *ctsio)
5477 {
5478 	struct scsi_format *cdb;
5479 	int length, defect_list_len;
5480 
5481 	CTL_DEBUG_PRINT(("ctl_format\n"));
5482 
5483 	cdb = (struct scsi_format *)ctsio->cdb;
5484 
5485 	length = 0;
5486 	if (cdb->byte2 & SF_FMTDATA) {
5487 		if (cdb->byte2 & SF_LONGLIST)
5488 			length = sizeof(struct scsi_format_header_long);
5489 		else
5490 			length = sizeof(struct scsi_format_header_short);
5491 	}
5492 
5493 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5494 	 && (length > 0)) {
5495 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5496 		ctsio->kern_data_len = length;
5497 		ctsio->kern_total_len = length;
5498 		ctsio->kern_rel_offset = 0;
5499 		ctsio->kern_sg_entries = 0;
5500 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5501 		ctsio->be_move_done = ctl_config_move_done;
5502 		ctl_datamove((union ctl_io *)ctsio);
5503 
5504 		return (CTL_RETVAL_COMPLETE);
5505 	}
5506 
5507 	defect_list_len = 0;
5508 
5509 	if (cdb->byte2 & SF_FMTDATA) {
5510 		if (cdb->byte2 & SF_LONGLIST) {
5511 			struct scsi_format_header_long *header;
5512 
5513 			header = (struct scsi_format_header_long *)
5514 				ctsio->kern_data_ptr;
5515 
5516 			defect_list_len = scsi_4btoul(header->defect_list_len);
5517 			if (defect_list_len != 0) {
5518 				ctl_set_invalid_field(ctsio,
5519 						      /*sks_valid*/ 1,
5520 						      /*command*/ 0,
5521 						      /*field*/ 2,
5522 						      /*bit_valid*/ 0,
5523 						      /*bit*/ 0);
5524 				goto bailout;
5525 			}
5526 		} else {
5527 			struct scsi_format_header_short *header;
5528 
5529 			header = (struct scsi_format_header_short *)
5530 				ctsio->kern_data_ptr;
5531 
5532 			defect_list_len = scsi_2btoul(header->defect_list_len);
5533 			if (defect_list_len != 0) {
5534 				ctl_set_invalid_field(ctsio,
5535 						      /*sks_valid*/ 1,
5536 						      /*command*/ 0,
5537 						      /*field*/ 2,
5538 						      /*bit_valid*/ 0,
5539 						      /*bit*/ 0);
5540 				goto bailout;
5541 			}
5542 		}
5543 	}
5544 
5545 	ctl_set_success(ctsio);
5546 bailout:
5547 
5548 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5549 		free(ctsio->kern_data_ptr, M_CTL);
5550 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5551 	}
5552 
5553 	ctl_done((union ctl_io *)ctsio);
5554 	return (CTL_RETVAL_COMPLETE);
5555 }
5556 
5557 int
5558 ctl_read_buffer(struct ctl_scsiio *ctsio)
5559 {
5560 	struct ctl_lun *lun = CTL_LUN(ctsio);
5561 	uint64_t buffer_offset;
5562 	uint32_t len;
5563 	uint8_t byte2;
5564 	static uint8_t descr[4];
5565 	static uint8_t echo_descr[4] = { 0 };
5566 
5567 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5568 
5569 	switch (ctsio->cdb[0]) {
5570 	case READ_BUFFER: {
5571 		struct scsi_read_buffer *cdb;
5572 
5573 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5574 		buffer_offset = scsi_3btoul(cdb->offset);
5575 		len = scsi_3btoul(cdb->length);
5576 		byte2 = cdb->byte2;
5577 		break;
5578 	}
5579 	case READ_BUFFER_16: {
5580 		struct scsi_read_buffer_16 *cdb;
5581 
5582 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5583 		buffer_offset = scsi_8btou64(cdb->offset);
5584 		len = scsi_4btoul(cdb->length);
5585 		byte2 = cdb->byte2;
5586 		break;
5587 	}
5588 	default: /* This shouldn't happen. */
5589 		ctl_set_invalid_opcode(ctsio);
5590 		ctl_done((union ctl_io *)ctsio);
5591 		return (CTL_RETVAL_COMPLETE);
5592 	}
5593 
5594 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5595 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5596 		ctl_set_invalid_field(ctsio,
5597 				      /*sks_valid*/ 1,
5598 				      /*command*/ 1,
5599 				      /*field*/ 6,
5600 				      /*bit_valid*/ 0,
5601 				      /*bit*/ 0);
5602 		ctl_done((union ctl_io *)ctsio);
5603 		return (CTL_RETVAL_COMPLETE);
5604 	}
5605 
5606 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5607 		descr[0] = 0;
5608 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5609 		ctsio->kern_data_ptr = descr;
5610 		len = min(len, sizeof(descr));
5611 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5612 		ctsio->kern_data_ptr = echo_descr;
5613 		len = min(len, sizeof(echo_descr));
5614 	} else {
5615 		if (lun->write_buffer == NULL) {
5616 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5617 			    M_CTL, M_WAITOK);
5618 		}
5619 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5620 	}
5621 	ctsio->kern_data_len = len;
5622 	ctsio->kern_total_len = len;
5623 	ctsio->kern_rel_offset = 0;
5624 	ctsio->kern_sg_entries = 0;
5625 	ctl_set_success(ctsio);
5626 	ctsio->be_move_done = ctl_config_move_done;
5627 	ctl_datamove((union ctl_io *)ctsio);
5628 	return (CTL_RETVAL_COMPLETE);
5629 }
5630 
5631 int
5632 ctl_write_buffer(struct ctl_scsiio *ctsio)
5633 {
5634 	struct ctl_lun *lun = CTL_LUN(ctsio);
5635 	struct scsi_write_buffer *cdb;
5636 	int buffer_offset, len;
5637 
5638 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5639 
5640 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5641 
5642 	len = scsi_3btoul(cdb->length);
5643 	buffer_offset = scsi_3btoul(cdb->offset);
5644 
5645 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5646 		ctl_set_invalid_field(ctsio,
5647 				      /*sks_valid*/ 1,
5648 				      /*command*/ 1,
5649 				      /*field*/ 6,
5650 				      /*bit_valid*/ 0,
5651 				      /*bit*/ 0);
5652 		ctl_done((union ctl_io *)ctsio);
5653 		return (CTL_RETVAL_COMPLETE);
5654 	}
5655 
5656 	/*
5657 	 * If we've got a kernel request that hasn't been malloced yet,
5658 	 * malloc it and tell the caller the data buffer is here.
5659 	 */
5660 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5661 		if (lun->write_buffer == NULL) {
5662 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5663 			    M_CTL, M_WAITOK);
5664 		}
5665 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5666 		ctsio->kern_data_len = len;
5667 		ctsio->kern_total_len = len;
5668 		ctsio->kern_rel_offset = 0;
5669 		ctsio->kern_sg_entries = 0;
5670 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5671 		ctsio->be_move_done = ctl_config_move_done;
5672 		ctl_datamove((union ctl_io *)ctsio);
5673 
5674 		return (CTL_RETVAL_COMPLETE);
5675 	}
5676 
5677 	ctl_set_success(ctsio);
5678 	ctl_done((union ctl_io *)ctsio);
5679 	return (CTL_RETVAL_COMPLETE);
5680 }
5681 
5682 int
5683 ctl_write_same(struct ctl_scsiio *ctsio)
5684 {
5685 	struct ctl_lun *lun = CTL_LUN(ctsio);
5686 	struct ctl_lba_len_flags *lbalen;
5687 	uint64_t lba;
5688 	uint32_t num_blocks;
5689 	int len, retval;
5690 	uint8_t byte2;
5691 
5692 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5693 
5694 	switch (ctsio->cdb[0]) {
5695 	case WRITE_SAME_10: {
5696 		struct scsi_write_same_10 *cdb;
5697 
5698 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5699 
5700 		lba = scsi_4btoul(cdb->addr);
5701 		num_blocks = scsi_2btoul(cdb->length);
5702 		byte2 = cdb->byte2;
5703 		break;
5704 	}
5705 	case WRITE_SAME_16: {
5706 		struct scsi_write_same_16 *cdb;
5707 
5708 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5709 
5710 		lba = scsi_8btou64(cdb->addr);
5711 		num_blocks = scsi_4btoul(cdb->length);
5712 		byte2 = cdb->byte2;
5713 		break;
5714 	}
5715 	default:
5716 		/*
5717 		 * We got a command we don't support.  This shouldn't
5718 		 * happen, commands should be filtered out above us.
5719 		 */
5720 		ctl_set_invalid_opcode(ctsio);
5721 		ctl_done((union ctl_io *)ctsio);
5722 
5723 		return (CTL_RETVAL_COMPLETE);
5724 		break; /* NOTREACHED */
5725 	}
5726 
5727 	/* ANCHOR flag can be used only together with UNMAP */
5728 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5729 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5730 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5731 		ctl_done((union ctl_io *)ctsio);
5732 		return (CTL_RETVAL_COMPLETE);
5733 	}
5734 
5735 	/*
5736 	 * The first check is to make sure we're in bounds, the second
5737 	 * check is to catch wrap-around problems.  If the lba + num blocks
5738 	 * is less than the lba, then we've wrapped around and the block
5739 	 * range is invalid anyway.
5740 	 */
5741 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5742 	 || ((lba + num_blocks) < lba)) {
5743 		ctl_set_lba_out_of_range(ctsio,
5744 		    MAX(lba, lun->be_lun->maxlba + 1));
5745 		ctl_done((union ctl_io *)ctsio);
5746 		return (CTL_RETVAL_COMPLETE);
5747 	}
5748 
5749 	/* Zero number of blocks means "to the last logical block" */
5750 	if (num_blocks == 0) {
5751 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5752 			ctl_set_invalid_field(ctsio,
5753 					      /*sks_valid*/ 0,
5754 					      /*command*/ 1,
5755 					      /*field*/ 0,
5756 					      /*bit_valid*/ 0,
5757 					      /*bit*/ 0);
5758 			ctl_done((union ctl_io *)ctsio);
5759 			return (CTL_RETVAL_COMPLETE);
5760 		}
5761 		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5762 	}
5763 
5764 	len = lun->be_lun->blocksize;
5765 
5766 	/*
5767 	 * If we've got a kernel request that hasn't been malloced yet,
5768 	 * malloc it and tell the caller the data buffer is here.
5769 	 */
5770 	if ((byte2 & SWS_NDOB) == 0 &&
5771 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5772 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5773 		ctsio->kern_data_len = len;
5774 		ctsio->kern_total_len = len;
5775 		ctsio->kern_rel_offset = 0;
5776 		ctsio->kern_sg_entries = 0;
5777 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5778 		ctsio->be_move_done = ctl_config_move_done;
5779 		ctl_datamove((union ctl_io *)ctsio);
5780 
5781 		return (CTL_RETVAL_COMPLETE);
5782 	}
5783 
5784 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5785 	lbalen->lba = lba;
5786 	lbalen->len = num_blocks;
5787 	lbalen->flags = byte2;
5788 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5789 
5790 	return (retval);
5791 }
5792 
5793 int
5794 ctl_unmap(struct ctl_scsiio *ctsio)
5795 {
5796 	struct ctl_lun *lun = CTL_LUN(ctsio);
5797 	struct scsi_unmap *cdb;
5798 	struct ctl_ptr_len_flags *ptrlen;
5799 	struct scsi_unmap_header *hdr;
5800 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5801 	uint64_t lba;
5802 	uint32_t num_blocks;
5803 	int len, retval;
5804 	uint8_t byte2;
5805 
5806 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5807 
5808 	cdb = (struct scsi_unmap *)ctsio->cdb;
5809 	len = scsi_2btoul(cdb->length);
5810 	byte2 = cdb->byte2;
5811 
5812 	/*
5813 	 * If we've got a kernel request that hasn't been malloced yet,
5814 	 * malloc it and tell the caller the data buffer is here.
5815 	 */
5816 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5817 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5818 		ctsio->kern_data_len = len;
5819 		ctsio->kern_total_len = len;
5820 		ctsio->kern_rel_offset = 0;
5821 		ctsio->kern_sg_entries = 0;
5822 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5823 		ctsio->be_move_done = ctl_config_move_done;
5824 		ctl_datamove((union ctl_io *)ctsio);
5825 
5826 		return (CTL_RETVAL_COMPLETE);
5827 	}
5828 
5829 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5830 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5831 	if (len < sizeof (*hdr) ||
5832 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5833 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5834 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5835 		ctl_set_invalid_field(ctsio,
5836 				      /*sks_valid*/ 0,
5837 				      /*command*/ 0,
5838 				      /*field*/ 0,
5839 				      /*bit_valid*/ 0,
5840 				      /*bit*/ 0);
5841 		goto done;
5842 	}
5843 	len = scsi_2btoul(hdr->desc_length);
5844 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5845 	end = buf + len / sizeof(*buf);
5846 
5847 	endnz = buf;
5848 	for (range = buf; range < end; range++) {
5849 		lba = scsi_8btou64(range->lba);
5850 		num_blocks = scsi_4btoul(range->length);
5851 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5852 		 || ((lba + num_blocks) < lba)) {
5853 			ctl_set_lba_out_of_range(ctsio,
5854 			    MAX(lba, lun->be_lun->maxlba + 1));
5855 			ctl_done((union ctl_io *)ctsio);
5856 			return (CTL_RETVAL_COMPLETE);
5857 		}
5858 		if (num_blocks != 0)
5859 			endnz = range + 1;
5860 	}
5861 
5862 	/*
5863 	 * Block backend can not handle zero last range.
5864 	 * Filter it out and return if there is nothing left.
5865 	 */
5866 	len = (uint8_t *)endnz - (uint8_t *)buf;
5867 	if (len == 0) {
5868 		ctl_set_success(ctsio);
5869 		goto done;
5870 	}
5871 
5872 	mtx_lock(&lun->lun_lock);
5873 	ptrlen = (struct ctl_ptr_len_flags *)
5874 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5875 	ptrlen->ptr = (void *)buf;
5876 	ptrlen->len = len;
5877 	ptrlen->flags = byte2;
5878 	ctl_try_unblock_others(lun, (union ctl_io *)ctsio, FALSE);
5879 	mtx_unlock(&lun->lun_lock);
5880 
5881 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5882 	return (retval);
5883 
5884 done:
5885 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5886 		free(ctsio->kern_data_ptr, M_CTL);
5887 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5888 	}
5889 	ctl_done((union ctl_io *)ctsio);
5890 	return (CTL_RETVAL_COMPLETE);
5891 }
5892 
5893 int
5894 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5895 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5896 {
5897 	struct ctl_lun *lun = CTL_LUN(ctsio);
5898 	uint8_t *current_cp;
5899 	int set_ua;
5900 	uint32_t initidx;
5901 
5902 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5903 	set_ua = 0;
5904 
5905 	current_cp = (page_index->page_data + (page_index->page_len *
5906 	    CTL_PAGE_CURRENT));
5907 
5908 	mtx_lock(&lun->lun_lock);
5909 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5910 		memcpy(current_cp, page_ptr, page_index->page_len);
5911 		set_ua = 1;
5912 	}
5913 	if (set_ua != 0)
5914 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5915 	mtx_unlock(&lun->lun_lock);
5916 	if (set_ua) {
5917 		ctl_isc_announce_mode(lun,
5918 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5919 		    page_index->page_code, page_index->subpage);
5920 	}
5921 	return (CTL_RETVAL_COMPLETE);
5922 }
5923 
5924 static void
5925 ctl_ie_timer(void *arg)
5926 {
5927 	struct ctl_lun *lun = arg;
5928 	uint64_t t;
5929 
5930 	if (lun->ie_asc == 0)
5931 		return;
5932 
5933 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5934 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5935 	else
5936 		lun->ie_reported = 0;
5937 
5938 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5939 		lun->ie_reportcnt++;
5940 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5941 		if (t == 0 || t == UINT32_MAX)
5942 			t = 3000;  /* 5 min */
5943 		callout_schedule(&lun->ie_callout, t * hz / 10);
5944 	}
5945 }
5946 
5947 int
5948 ctl_ie_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 	struct scsi_info_exceptions_page *pg;
5953 	uint64_t t;
5954 
5955 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5956 
5957 	pg = (struct scsi_info_exceptions_page *)page_ptr;
5958 	mtx_lock(&lun->lun_lock);
5959 	if (pg->info_flags & SIEP_FLAGS_TEST) {
5960 		lun->ie_asc = 0x5d;
5961 		lun->ie_ascq = 0xff;
5962 		if (pg->mrie == SIEP_MRIE_UA) {
5963 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5964 			lun->ie_reported = 1;
5965 		} else {
5966 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5967 			lun->ie_reported = -1;
5968 		}
5969 		lun->ie_reportcnt = 1;
5970 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5971 			lun->ie_reportcnt++;
5972 			t = scsi_4btoul(pg->interval_timer);
5973 			if (t == 0 || t == UINT32_MAX)
5974 				t = 3000;  /* 5 min */
5975 			callout_reset(&lun->ie_callout, t * hz / 10,
5976 			    ctl_ie_timer, lun);
5977 		}
5978 	} else {
5979 		lun->ie_asc = 0;
5980 		lun->ie_ascq = 0;
5981 		lun->ie_reported = 1;
5982 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5983 		lun->ie_reportcnt = UINT32_MAX;
5984 		callout_stop(&lun->ie_callout);
5985 	}
5986 	mtx_unlock(&lun->lun_lock);
5987 	return (CTL_RETVAL_COMPLETE);
5988 }
5989 
5990 static int
5991 ctl_do_mode_select(union ctl_io *io)
5992 {
5993 	struct ctl_lun *lun = CTL_LUN(io);
5994 	struct scsi_mode_page_header *page_header;
5995 	struct ctl_page_index *page_index;
5996 	struct ctl_scsiio *ctsio;
5997 	int page_len, page_len_offset, page_len_size;
5998 	union ctl_modepage_info *modepage_info;
5999 	uint16_t *len_left, *len_used;
6000 	int retval, i;
6001 
6002 	ctsio = &io->scsiio;
6003 	page_index = NULL;
6004 	page_len = 0;
6005 
6006 	modepage_info = (union ctl_modepage_info *)
6007 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6008 	len_left = &modepage_info->header.len_left;
6009 	len_used = &modepage_info->header.len_used;
6010 
6011 do_next_page:
6012 
6013 	page_header = (struct scsi_mode_page_header *)
6014 		(ctsio->kern_data_ptr + *len_used);
6015 
6016 	if (*len_left == 0) {
6017 		free(ctsio->kern_data_ptr, M_CTL);
6018 		ctl_set_success(ctsio);
6019 		ctl_done((union ctl_io *)ctsio);
6020 		return (CTL_RETVAL_COMPLETE);
6021 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6022 
6023 		free(ctsio->kern_data_ptr, M_CTL);
6024 		ctl_set_param_len_error(ctsio);
6025 		ctl_done((union ctl_io *)ctsio);
6026 		return (CTL_RETVAL_COMPLETE);
6027 
6028 	} else if ((page_header->page_code & SMPH_SPF)
6029 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6030 
6031 		free(ctsio->kern_data_ptr, M_CTL);
6032 		ctl_set_param_len_error(ctsio);
6033 		ctl_done((union ctl_io *)ctsio);
6034 		return (CTL_RETVAL_COMPLETE);
6035 	}
6036 
6037 
6038 	/*
6039 	 * XXX KDM should we do something with the block descriptor?
6040 	 */
6041 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6042 		page_index = &lun->mode_pages.index[i];
6043 		if (lun->be_lun->lun_type == T_DIRECT &&
6044 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6045 			continue;
6046 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6047 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6048 			continue;
6049 		if (lun->be_lun->lun_type == T_CDROM &&
6050 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6051 			continue;
6052 
6053 		if ((page_index->page_code & SMPH_PC_MASK) !=
6054 		    (page_header->page_code & SMPH_PC_MASK))
6055 			continue;
6056 
6057 		/*
6058 		 * If neither page has a subpage code, then we've got a
6059 		 * match.
6060 		 */
6061 		if (((page_index->page_code & SMPH_SPF) == 0)
6062 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6063 			page_len = page_header->page_length;
6064 			break;
6065 		}
6066 
6067 		/*
6068 		 * If both pages have subpages, then the subpage numbers
6069 		 * have to match.
6070 		 */
6071 		if ((page_index->page_code & SMPH_SPF)
6072 		  && (page_header->page_code & SMPH_SPF)) {
6073 			struct scsi_mode_page_header_sp *sph;
6074 
6075 			sph = (struct scsi_mode_page_header_sp *)page_header;
6076 			if (page_index->subpage == sph->subpage) {
6077 				page_len = scsi_2btoul(sph->page_length);
6078 				break;
6079 			}
6080 		}
6081 	}
6082 
6083 	/*
6084 	 * If we couldn't find the page, or if we don't have a mode select
6085 	 * handler for it, send back an error to the user.
6086 	 */
6087 	if ((i >= CTL_NUM_MODE_PAGES)
6088 	 || (page_index->select_handler == NULL)) {
6089 		ctl_set_invalid_field(ctsio,
6090 				      /*sks_valid*/ 1,
6091 				      /*command*/ 0,
6092 				      /*field*/ *len_used,
6093 				      /*bit_valid*/ 0,
6094 				      /*bit*/ 0);
6095 		free(ctsio->kern_data_ptr, M_CTL);
6096 		ctl_done((union ctl_io *)ctsio);
6097 		return (CTL_RETVAL_COMPLETE);
6098 	}
6099 
6100 	if (page_index->page_code & SMPH_SPF) {
6101 		page_len_offset = 2;
6102 		page_len_size = 2;
6103 	} else {
6104 		page_len_size = 1;
6105 		page_len_offset = 1;
6106 	}
6107 
6108 	/*
6109 	 * If the length the initiator gives us isn't the one we specify in
6110 	 * the mode page header, or if they didn't specify enough data in
6111 	 * the CDB to avoid truncating this page, kick out the request.
6112 	 */
6113 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6114 		ctl_set_invalid_field(ctsio,
6115 				      /*sks_valid*/ 1,
6116 				      /*command*/ 0,
6117 				      /*field*/ *len_used + page_len_offset,
6118 				      /*bit_valid*/ 0,
6119 				      /*bit*/ 0);
6120 		free(ctsio->kern_data_ptr, M_CTL);
6121 		ctl_done((union ctl_io *)ctsio);
6122 		return (CTL_RETVAL_COMPLETE);
6123 	}
6124 	if (*len_left < page_index->page_len) {
6125 		free(ctsio->kern_data_ptr, M_CTL);
6126 		ctl_set_param_len_error(ctsio);
6127 		ctl_done((union ctl_io *)ctsio);
6128 		return (CTL_RETVAL_COMPLETE);
6129 	}
6130 
6131 	/*
6132 	 * Run through the mode page, checking to make sure that the bits
6133 	 * the user changed are actually legal for him to change.
6134 	 */
6135 	for (i = 0; i < page_index->page_len; i++) {
6136 		uint8_t *user_byte, *change_mask, *current_byte;
6137 		int bad_bit;
6138 		int j;
6139 
6140 		user_byte = (uint8_t *)page_header + i;
6141 		change_mask = page_index->page_data +
6142 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6143 		current_byte = page_index->page_data +
6144 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6145 
6146 		/*
6147 		 * Check to see whether the user set any bits in this byte
6148 		 * that he is not allowed to set.
6149 		 */
6150 		if ((*user_byte & ~(*change_mask)) ==
6151 		    (*current_byte & ~(*change_mask)))
6152 			continue;
6153 
6154 		/*
6155 		 * Go through bit by bit to determine which one is illegal.
6156 		 */
6157 		bad_bit = 0;
6158 		for (j = 7; j >= 0; j--) {
6159 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6160 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6161 				bad_bit = i;
6162 				break;
6163 			}
6164 		}
6165 		ctl_set_invalid_field(ctsio,
6166 				      /*sks_valid*/ 1,
6167 				      /*command*/ 0,
6168 				      /*field*/ *len_used + i,
6169 				      /*bit_valid*/ 1,
6170 				      /*bit*/ bad_bit);
6171 		free(ctsio->kern_data_ptr, M_CTL);
6172 		ctl_done((union ctl_io *)ctsio);
6173 		return (CTL_RETVAL_COMPLETE);
6174 	}
6175 
6176 	/*
6177 	 * Decrement these before we call the page handler, since we may
6178 	 * end up getting called back one way or another before the handler
6179 	 * returns to this context.
6180 	 */
6181 	*len_left -= page_index->page_len;
6182 	*len_used += page_index->page_len;
6183 
6184 	retval = page_index->select_handler(ctsio, page_index,
6185 					    (uint8_t *)page_header);
6186 
6187 	/*
6188 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6189 	 * wait until this queued command completes to finish processing
6190 	 * the mode page.  If it returns anything other than
6191 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6192 	 * already set the sense information, freed the data pointer, and
6193 	 * completed the io for us.
6194 	 */
6195 	if (retval != CTL_RETVAL_COMPLETE)
6196 		goto bailout_no_done;
6197 
6198 	/*
6199 	 * If the initiator sent us more than one page, parse the next one.
6200 	 */
6201 	if (*len_left > 0)
6202 		goto do_next_page;
6203 
6204 	ctl_set_success(ctsio);
6205 	free(ctsio->kern_data_ptr, M_CTL);
6206 	ctl_done((union ctl_io *)ctsio);
6207 
6208 bailout_no_done:
6209 
6210 	return (CTL_RETVAL_COMPLETE);
6211 
6212 }
6213 
6214 int
6215 ctl_mode_select(struct ctl_scsiio *ctsio)
6216 {
6217 	struct ctl_lun *lun = CTL_LUN(ctsio);
6218 	union ctl_modepage_info *modepage_info;
6219 	int bd_len, i, header_size, param_len, rtd;
6220 	uint32_t initidx;
6221 
6222 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6223 	switch (ctsio->cdb[0]) {
6224 	case MODE_SELECT_6: {
6225 		struct scsi_mode_select_6 *cdb;
6226 
6227 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6228 
6229 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6230 		param_len = cdb->length;
6231 		header_size = sizeof(struct scsi_mode_header_6);
6232 		break;
6233 	}
6234 	case MODE_SELECT_10: {
6235 		struct scsi_mode_select_10 *cdb;
6236 
6237 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6238 
6239 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6240 		param_len = scsi_2btoul(cdb->length);
6241 		header_size = sizeof(struct scsi_mode_header_10);
6242 		break;
6243 	}
6244 	default:
6245 		ctl_set_invalid_opcode(ctsio);
6246 		ctl_done((union ctl_io *)ctsio);
6247 		return (CTL_RETVAL_COMPLETE);
6248 	}
6249 
6250 	if (rtd) {
6251 		if (param_len != 0) {
6252 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6253 			    /*command*/ 1, /*field*/ 0,
6254 			    /*bit_valid*/ 0, /*bit*/ 0);
6255 			ctl_done((union ctl_io *)ctsio);
6256 			return (CTL_RETVAL_COMPLETE);
6257 		}
6258 
6259 		/* Revert to defaults. */
6260 		ctl_init_page_index(lun);
6261 		mtx_lock(&lun->lun_lock);
6262 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6263 		mtx_unlock(&lun->lun_lock);
6264 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6265 			ctl_isc_announce_mode(lun, -1,
6266 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6267 			    lun->mode_pages.index[i].subpage);
6268 		}
6269 		ctl_set_success(ctsio);
6270 		ctl_done((union ctl_io *)ctsio);
6271 		return (CTL_RETVAL_COMPLETE);
6272 	}
6273 
6274 	/*
6275 	 * From SPC-3:
6276 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6277 	 * shall be empty. This condition shall not be considered as an error."
6278 	 */
6279 	if (param_len == 0) {
6280 		ctl_set_success(ctsio);
6281 		ctl_done((union ctl_io *)ctsio);
6282 		return (CTL_RETVAL_COMPLETE);
6283 	}
6284 
6285 	/*
6286 	 * Since we'll hit this the first time through, prior to
6287 	 * allocation, we don't need to free a data buffer here.
6288 	 */
6289 	if (param_len < header_size) {
6290 		ctl_set_param_len_error(ctsio);
6291 		ctl_done((union ctl_io *)ctsio);
6292 		return (CTL_RETVAL_COMPLETE);
6293 	}
6294 
6295 	/*
6296 	 * Allocate the data buffer and grab the user's data.  In theory,
6297 	 * we shouldn't have to sanity check the parameter list length here
6298 	 * because the maximum size is 64K.  We should be able to malloc
6299 	 * that much without too many problems.
6300 	 */
6301 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6302 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6303 		ctsio->kern_data_len = param_len;
6304 		ctsio->kern_total_len = param_len;
6305 		ctsio->kern_rel_offset = 0;
6306 		ctsio->kern_sg_entries = 0;
6307 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6308 		ctsio->be_move_done = ctl_config_move_done;
6309 		ctl_datamove((union ctl_io *)ctsio);
6310 
6311 		return (CTL_RETVAL_COMPLETE);
6312 	}
6313 
6314 	switch (ctsio->cdb[0]) {
6315 	case MODE_SELECT_6: {
6316 		struct scsi_mode_header_6 *mh6;
6317 
6318 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6319 		bd_len = mh6->blk_desc_len;
6320 		break;
6321 	}
6322 	case MODE_SELECT_10: {
6323 		struct scsi_mode_header_10 *mh10;
6324 
6325 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6326 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6327 		break;
6328 	}
6329 	default:
6330 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6331 	}
6332 
6333 	if (param_len < (header_size + bd_len)) {
6334 		free(ctsio->kern_data_ptr, M_CTL);
6335 		ctl_set_param_len_error(ctsio);
6336 		ctl_done((union ctl_io *)ctsio);
6337 		return (CTL_RETVAL_COMPLETE);
6338 	}
6339 
6340 	/*
6341 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6342 	 * ctl_config_write_done(), it'll get passed back to
6343 	 * ctl_do_mode_select() for further processing, or completion if
6344 	 * we're all done.
6345 	 */
6346 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6347 	ctsio->io_cont = ctl_do_mode_select;
6348 
6349 	modepage_info = (union ctl_modepage_info *)
6350 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6351 	memset(modepage_info, 0, sizeof(*modepage_info));
6352 	modepage_info->header.len_left = param_len - header_size - bd_len;
6353 	modepage_info->header.len_used = header_size + bd_len;
6354 
6355 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6356 }
6357 
6358 int
6359 ctl_mode_sense(struct ctl_scsiio *ctsio)
6360 {
6361 	struct ctl_lun *lun = CTL_LUN(ctsio);
6362 	int pc, page_code, dbd, subpage;
6363 	int alloc_len, page_len, header_len, total_len;
6364 	struct scsi_mode_block_descr *block_desc;
6365 	struct ctl_page_index *page_index;
6366 
6367 	dbd = 0;
6368 	block_desc = NULL;
6369 
6370 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6371 
6372 	switch (ctsio->cdb[0]) {
6373 	case MODE_SENSE_6: {
6374 		struct scsi_mode_sense_6 *cdb;
6375 
6376 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6377 
6378 		header_len = sizeof(struct scsi_mode_hdr_6);
6379 		if (cdb->byte2 & SMS_DBD)
6380 			dbd = 1;
6381 		else
6382 			header_len += sizeof(struct scsi_mode_block_descr);
6383 
6384 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6385 		page_code = cdb->page & SMS_PAGE_CODE;
6386 		subpage = cdb->subpage;
6387 		alloc_len = cdb->length;
6388 		break;
6389 	}
6390 	case MODE_SENSE_10: {
6391 		struct scsi_mode_sense_10 *cdb;
6392 
6393 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6394 
6395 		header_len = sizeof(struct scsi_mode_hdr_10);
6396 
6397 		if (cdb->byte2 & SMS_DBD)
6398 			dbd = 1;
6399 		else
6400 			header_len += sizeof(struct scsi_mode_block_descr);
6401 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6402 		page_code = cdb->page & SMS_PAGE_CODE;
6403 		subpage = cdb->subpage;
6404 		alloc_len = scsi_2btoul(cdb->length);
6405 		break;
6406 	}
6407 	default:
6408 		ctl_set_invalid_opcode(ctsio);
6409 		ctl_done((union ctl_io *)ctsio);
6410 		return (CTL_RETVAL_COMPLETE);
6411 		break; /* NOTREACHED */
6412 	}
6413 
6414 	/*
6415 	 * We have to make a first pass through to calculate the size of
6416 	 * the pages that match the user's query.  Then we allocate enough
6417 	 * memory to hold it, and actually copy the data into the buffer.
6418 	 */
6419 	switch (page_code) {
6420 	case SMS_ALL_PAGES_PAGE: {
6421 		u_int i;
6422 
6423 		page_len = 0;
6424 
6425 		/*
6426 		 * At the moment, values other than 0 and 0xff here are
6427 		 * reserved according to SPC-3.
6428 		 */
6429 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6430 		 && (subpage != SMS_SUBPAGE_ALL)) {
6431 			ctl_set_invalid_field(ctsio,
6432 					      /*sks_valid*/ 1,
6433 					      /*command*/ 1,
6434 					      /*field*/ 3,
6435 					      /*bit_valid*/ 0,
6436 					      /*bit*/ 0);
6437 			ctl_done((union ctl_io *)ctsio);
6438 			return (CTL_RETVAL_COMPLETE);
6439 		}
6440 
6441 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6442 			page_index = &lun->mode_pages.index[i];
6443 
6444 			/* Make sure the page is supported for this dev type */
6445 			if (lun->be_lun->lun_type == T_DIRECT &&
6446 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6447 				continue;
6448 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6449 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6450 				continue;
6451 			if (lun->be_lun->lun_type == T_CDROM &&
6452 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6453 				continue;
6454 
6455 			/*
6456 			 * We don't use this subpage if the user didn't
6457 			 * request all subpages.
6458 			 */
6459 			if ((page_index->subpage != 0)
6460 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6461 				continue;
6462 
6463 			page_len += page_index->page_len;
6464 		}
6465 		break;
6466 	}
6467 	default: {
6468 		u_int i;
6469 
6470 		page_len = 0;
6471 
6472 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6473 			page_index = &lun->mode_pages.index[i];
6474 
6475 			/* Make sure the page is supported for this dev type */
6476 			if (lun->be_lun->lun_type == T_DIRECT &&
6477 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6478 				continue;
6479 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6480 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6481 				continue;
6482 			if (lun->be_lun->lun_type == T_CDROM &&
6483 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6484 				continue;
6485 
6486 			/* Look for the right page code */
6487 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6488 				continue;
6489 
6490 			/* Look for the right subpage or the subpage wildcard*/
6491 			if ((page_index->subpage != subpage)
6492 			 && (subpage != SMS_SUBPAGE_ALL))
6493 				continue;
6494 
6495 			page_len += page_index->page_len;
6496 		}
6497 
6498 		if (page_len == 0) {
6499 			ctl_set_invalid_field(ctsio,
6500 					      /*sks_valid*/ 1,
6501 					      /*command*/ 1,
6502 					      /*field*/ 2,
6503 					      /*bit_valid*/ 1,
6504 					      /*bit*/ 5);
6505 			ctl_done((union ctl_io *)ctsio);
6506 			return (CTL_RETVAL_COMPLETE);
6507 		}
6508 		break;
6509 	}
6510 	}
6511 
6512 	total_len = header_len + page_len;
6513 
6514 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6515 	ctsio->kern_sg_entries = 0;
6516 	ctsio->kern_rel_offset = 0;
6517 	ctsio->kern_data_len = min(total_len, alloc_len);
6518 	ctsio->kern_total_len = ctsio->kern_data_len;
6519 
6520 	switch (ctsio->cdb[0]) {
6521 	case MODE_SENSE_6: {
6522 		struct scsi_mode_hdr_6 *header;
6523 
6524 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6525 
6526 		header->datalen = MIN(total_len - 1, 254);
6527 		if (lun->be_lun->lun_type == T_DIRECT) {
6528 			header->dev_specific = 0x10; /* DPOFUA */
6529 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6530 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6531 				header->dev_specific |= 0x80; /* WP */
6532 		}
6533 		if (dbd)
6534 			header->block_descr_len = 0;
6535 		else
6536 			header->block_descr_len =
6537 				sizeof(struct scsi_mode_block_descr);
6538 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6539 		break;
6540 	}
6541 	case MODE_SENSE_10: {
6542 		struct scsi_mode_hdr_10 *header;
6543 		int datalen;
6544 
6545 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6546 
6547 		datalen = MIN(total_len - 2, 65533);
6548 		scsi_ulto2b(datalen, header->datalen);
6549 		if (lun->be_lun->lun_type == T_DIRECT) {
6550 			header->dev_specific = 0x10; /* DPOFUA */
6551 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6552 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6553 				header->dev_specific |= 0x80; /* WP */
6554 		}
6555 		if (dbd)
6556 			scsi_ulto2b(0, header->block_descr_len);
6557 		else
6558 			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6559 				    header->block_descr_len);
6560 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6561 		break;
6562 	}
6563 	default:
6564 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6565 	}
6566 
6567 	/*
6568 	 * If we've got a disk, use its blocksize in the block
6569 	 * descriptor.  Otherwise, just set it to 0.
6570 	 */
6571 	if (dbd == 0) {
6572 		if (lun->be_lun->lun_type == T_DIRECT)
6573 			scsi_ulto3b(lun->be_lun->blocksize,
6574 				    block_desc->block_len);
6575 		else
6576 			scsi_ulto3b(0, block_desc->block_len);
6577 	}
6578 
6579 	switch (page_code) {
6580 	case SMS_ALL_PAGES_PAGE: {
6581 		int i, data_used;
6582 
6583 		data_used = header_len;
6584 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6585 			struct ctl_page_index *page_index;
6586 
6587 			page_index = &lun->mode_pages.index[i];
6588 			if (lun->be_lun->lun_type == T_DIRECT &&
6589 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6590 				continue;
6591 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6592 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6593 				continue;
6594 			if (lun->be_lun->lun_type == T_CDROM &&
6595 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6596 				continue;
6597 
6598 			/*
6599 			 * We don't use this subpage if the user didn't
6600 			 * request all subpages.  We already checked (above)
6601 			 * to make sure the user only specified a subpage
6602 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6603 			 */
6604 			if ((page_index->subpage != 0)
6605 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6606 				continue;
6607 
6608 			/*
6609 			 * Call the handler, if it exists, to update the
6610 			 * page to the latest values.
6611 			 */
6612 			if (page_index->sense_handler != NULL)
6613 				page_index->sense_handler(ctsio, page_index,pc);
6614 
6615 			memcpy(ctsio->kern_data_ptr + data_used,
6616 			       page_index->page_data +
6617 			       (page_index->page_len * pc),
6618 			       page_index->page_len);
6619 			data_used += page_index->page_len;
6620 		}
6621 		break;
6622 	}
6623 	default: {
6624 		int i, data_used;
6625 
6626 		data_used = header_len;
6627 
6628 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6629 			struct ctl_page_index *page_index;
6630 
6631 			page_index = &lun->mode_pages.index[i];
6632 
6633 			/* Look for the right page code */
6634 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6635 				continue;
6636 
6637 			/* Look for the right subpage or the subpage wildcard*/
6638 			if ((page_index->subpage != subpage)
6639 			 && (subpage != SMS_SUBPAGE_ALL))
6640 				continue;
6641 
6642 			/* Make sure the page is supported for this dev type */
6643 			if (lun->be_lun->lun_type == T_DIRECT &&
6644 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6645 				continue;
6646 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6647 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6648 				continue;
6649 			if (lun->be_lun->lun_type == T_CDROM &&
6650 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6651 				continue;
6652 
6653 			/*
6654 			 * Call the handler, if it exists, to update the
6655 			 * page to the latest values.
6656 			 */
6657 			if (page_index->sense_handler != NULL)
6658 				page_index->sense_handler(ctsio, page_index,pc);
6659 
6660 			memcpy(ctsio->kern_data_ptr + data_used,
6661 			       page_index->page_data +
6662 			       (page_index->page_len * pc),
6663 			       page_index->page_len);
6664 			data_used += page_index->page_len;
6665 		}
6666 		break;
6667 	}
6668 	}
6669 
6670 	ctl_set_success(ctsio);
6671 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6672 	ctsio->be_move_done = ctl_config_move_done;
6673 	ctl_datamove((union ctl_io *)ctsio);
6674 	return (CTL_RETVAL_COMPLETE);
6675 }
6676 
6677 int
6678 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6679 			       struct ctl_page_index *page_index,
6680 			       int pc)
6681 {
6682 	struct ctl_lun *lun = CTL_LUN(ctsio);
6683 	struct scsi_log_param_header *phdr;
6684 	uint8_t *data;
6685 	uint64_t val;
6686 
6687 	data = page_index->page_data;
6688 
6689 	if (lun->backend->lun_attr != NULL &&
6690 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6691 	     != UINT64_MAX) {
6692 		phdr = (struct scsi_log_param_header *)data;
6693 		scsi_ulto2b(0x0001, phdr->param_code);
6694 		phdr->param_control = SLP_LBIN | SLP_LP;
6695 		phdr->param_len = 8;
6696 		data = (uint8_t *)(phdr + 1);
6697 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6698 		data[4] = 0x02; /* per-pool */
6699 		data += phdr->param_len;
6700 	}
6701 
6702 	if (lun->backend->lun_attr != NULL &&
6703 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6704 	     != UINT64_MAX) {
6705 		phdr = (struct scsi_log_param_header *)data;
6706 		scsi_ulto2b(0x0002, phdr->param_code);
6707 		phdr->param_control = SLP_LBIN | SLP_LP;
6708 		phdr->param_len = 8;
6709 		data = (uint8_t *)(phdr + 1);
6710 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6711 		data[4] = 0x01; /* per-LUN */
6712 		data += phdr->param_len;
6713 	}
6714 
6715 	if (lun->backend->lun_attr != NULL &&
6716 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6717 	     != UINT64_MAX) {
6718 		phdr = (struct scsi_log_param_header *)data;
6719 		scsi_ulto2b(0x00f1, phdr->param_code);
6720 		phdr->param_control = SLP_LBIN | SLP_LP;
6721 		phdr->param_len = 8;
6722 		data = (uint8_t *)(phdr + 1);
6723 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6724 		data[4] = 0x02; /* per-pool */
6725 		data += phdr->param_len;
6726 	}
6727 
6728 	if (lun->backend->lun_attr != NULL &&
6729 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6730 	     != UINT64_MAX) {
6731 		phdr = (struct scsi_log_param_header *)data;
6732 		scsi_ulto2b(0x00f2, phdr->param_code);
6733 		phdr->param_control = SLP_LBIN | SLP_LP;
6734 		phdr->param_len = 8;
6735 		data = (uint8_t *)(phdr + 1);
6736 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6737 		data[4] = 0x02; /* per-pool */
6738 		data += phdr->param_len;
6739 	}
6740 
6741 	page_index->page_len = data - page_index->page_data;
6742 	return (0);
6743 }
6744 
6745 int
6746 ctl_sap_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 stat_page *data;
6752 	struct bintime *t;
6753 
6754 	data = (struct stat_page *)page_index->page_data;
6755 
6756 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6757 	data->sap.hdr.param_control = SLP_LBIN;
6758 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6759 	    sizeof(struct scsi_log_param_header);
6760 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6761 	    data->sap.read_num);
6762 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6763 	    data->sap.write_num);
6764 	if (lun->be_lun->blocksize > 0) {
6765 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6766 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6767 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6768 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6769 	}
6770 	t = &lun->stats.time[CTL_STATS_READ];
6771 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6772 	    data->sap.read_int);
6773 	t = &lun->stats.time[CTL_STATS_WRITE];
6774 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6775 	    data->sap.write_int);
6776 	scsi_u64to8b(0, data->sap.weighted_num);
6777 	scsi_u64to8b(0, data->sap.weighted_int);
6778 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6779 	data->it.hdr.param_control = SLP_LBIN;
6780 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6781 	    sizeof(struct scsi_log_param_header);
6782 #ifdef CTL_TIME_IO
6783 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6784 #endif
6785 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6786 	data->it.hdr.param_control = SLP_LBIN;
6787 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6788 	    sizeof(struct scsi_log_param_header);
6789 	scsi_ulto4b(3, data->ti.exponent);
6790 	scsi_ulto4b(1, data->ti.integer);
6791 	return (0);
6792 }
6793 
6794 int
6795 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6796 			       struct ctl_page_index *page_index,
6797 			       int pc)
6798 {
6799 	struct ctl_lun *lun = CTL_LUN(ctsio);
6800 	struct scsi_log_informational_exceptions *data;
6801 
6802 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6803 
6804 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6805 	data->hdr.param_control = SLP_LBIN;
6806 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6807 	    sizeof(struct scsi_log_param_header);
6808 	data->ie_asc = lun->ie_asc;
6809 	data->ie_ascq = lun->ie_ascq;
6810 	data->temperature = 0xff;
6811 	return (0);
6812 }
6813 
6814 int
6815 ctl_log_sense(struct ctl_scsiio *ctsio)
6816 {
6817 	struct ctl_lun *lun = CTL_LUN(ctsio);
6818 	int i, pc, page_code, subpage;
6819 	int alloc_len, total_len;
6820 	struct ctl_page_index *page_index;
6821 	struct scsi_log_sense *cdb;
6822 	struct scsi_log_header *header;
6823 
6824 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6825 
6826 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6827 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6828 	page_code = cdb->page & SLS_PAGE_CODE;
6829 	subpage = cdb->subpage;
6830 	alloc_len = scsi_2btoul(cdb->length);
6831 
6832 	page_index = NULL;
6833 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6834 		page_index = &lun->log_pages.index[i];
6835 
6836 		/* Look for the right page code */
6837 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6838 			continue;
6839 
6840 		/* Look for the right subpage or the subpage wildcard*/
6841 		if (page_index->subpage != subpage)
6842 			continue;
6843 
6844 		break;
6845 	}
6846 	if (i >= CTL_NUM_LOG_PAGES) {
6847 		ctl_set_invalid_field(ctsio,
6848 				      /*sks_valid*/ 1,
6849 				      /*command*/ 1,
6850 				      /*field*/ 2,
6851 				      /*bit_valid*/ 0,
6852 				      /*bit*/ 0);
6853 		ctl_done((union ctl_io *)ctsio);
6854 		return (CTL_RETVAL_COMPLETE);
6855 	}
6856 
6857 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6858 
6859 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6860 	ctsio->kern_sg_entries = 0;
6861 	ctsio->kern_rel_offset = 0;
6862 	ctsio->kern_data_len = min(total_len, alloc_len);
6863 	ctsio->kern_total_len = ctsio->kern_data_len;
6864 
6865 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6866 	header->page = page_index->page_code;
6867 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6868 		header->page |= SL_DS;
6869 	if (page_index->subpage) {
6870 		header->page |= SL_SPF;
6871 		header->subpage = page_index->subpage;
6872 	}
6873 	scsi_ulto2b(page_index->page_len, header->datalen);
6874 
6875 	/*
6876 	 * Call the handler, if it exists, to update the
6877 	 * page to the latest values.
6878 	 */
6879 	if (page_index->sense_handler != NULL)
6880 		page_index->sense_handler(ctsio, page_index, pc);
6881 
6882 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6883 
6884 	ctl_set_success(ctsio);
6885 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6886 	ctsio->be_move_done = ctl_config_move_done;
6887 	ctl_datamove((union ctl_io *)ctsio);
6888 	return (CTL_RETVAL_COMPLETE);
6889 }
6890 
6891 int
6892 ctl_read_capacity(struct ctl_scsiio *ctsio)
6893 {
6894 	struct ctl_lun *lun = CTL_LUN(ctsio);
6895 	struct scsi_read_capacity *cdb;
6896 	struct scsi_read_capacity_data *data;
6897 	uint32_t lba;
6898 
6899 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6900 
6901 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6902 
6903 	lba = scsi_4btoul(cdb->addr);
6904 	if (((cdb->pmi & SRC_PMI) == 0)
6905 	 && (lba != 0)) {
6906 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6907 				      /*sks_valid*/ 1,
6908 				      /*command*/ 1,
6909 				      /*field*/ 2,
6910 				      /*bit_valid*/ 0,
6911 				      /*bit*/ 0);
6912 		ctl_done((union ctl_io *)ctsio);
6913 		return (CTL_RETVAL_COMPLETE);
6914 	}
6915 
6916 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6917 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6918 	ctsio->kern_data_len = sizeof(*data);
6919 	ctsio->kern_total_len = sizeof(*data);
6920 	ctsio->kern_rel_offset = 0;
6921 	ctsio->kern_sg_entries = 0;
6922 
6923 	/*
6924 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6925 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6926 	 * serivce action set.
6927 	 */
6928 	if (lun->be_lun->maxlba > 0xfffffffe)
6929 		scsi_ulto4b(0xffffffff, data->addr);
6930 	else
6931 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6932 
6933 	/*
6934 	 * XXX KDM this may not be 512 bytes...
6935 	 */
6936 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6937 
6938 	ctl_set_success(ctsio);
6939 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6940 	ctsio->be_move_done = ctl_config_move_done;
6941 	ctl_datamove((union ctl_io *)ctsio);
6942 	return (CTL_RETVAL_COMPLETE);
6943 }
6944 
6945 int
6946 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6947 {
6948 	struct ctl_lun *lun = CTL_LUN(ctsio);
6949 	struct scsi_read_capacity_16 *cdb;
6950 	struct scsi_read_capacity_data_long *data;
6951 	uint64_t lba;
6952 	uint32_t alloc_len;
6953 
6954 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6955 
6956 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6957 
6958 	alloc_len = scsi_4btoul(cdb->alloc_len);
6959 	lba = scsi_8btou64(cdb->addr);
6960 
6961 	if ((cdb->reladr & SRC16_PMI)
6962 	 && (lba != 0)) {
6963 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6964 				      /*sks_valid*/ 1,
6965 				      /*command*/ 1,
6966 				      /*field*/ 2,
6967 				      /*bit_valid*/ 0,
6968 				      /*bit*/ 0);
6969 		ctl_done((union ctl_io *)ctsio);
6970 		return (CTL_RETVAL_COMPLETE);
6971 	}
6972 
6973 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6974 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6975 	ctsio->kern_rel_offset = 0;
6976 	ctsio->kern_sg_entries = 0;
6977 	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
6978 	ctsio->kern_total_len = ctsio->kern_data_len;
6979 
6980 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6981 	/* XXX KDM this may not be 512 bytes... */
6982 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6983 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6984 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6985 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6986 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6987 
6988 	ctl_set_success(ctsio);
6989 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6990 	ctsio->be_move_done = ctl_config_move_done;
6991 	ctl_datamove((union ctl_io *)ctsio);
6992 	return (CTL_RETVAL_COMPLETE);
6993 }
6994 
6995 int
6996 ctl_get_lba_status(struct ctl_scsiio *ctsio)
6997 {
6998 	struct ctl_lun *lun = CTL_LUN(ctsio);
6999 	struct scsi_get_lba_status *cdb;
7000 	struct scsi_get_lba_status_data *data;
7001 	struct ctl_lba_len_flags *lbalen;
7002 	uint64_t lba;
7003 	uint32_t alloc_len, total_len;
7004 	int retval;
7005 
7006 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7007 
7008 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7009 	lba = scsi_8btou64(cdb->addr);
7010 	alloc_len = scsi_4btoul(cdb->alloc_len);
7011 
7012 	if (lba > lun->be_lun->maxlba) {
7013 		ctl_set_lba_out_of_range(ctsio, lba);
7014 		ctl_done((union ctl_io *)ctsio);
7015 		return (CTL_RETVAL_COMPLETE);
7016 	}
7017 
7018 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7019 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7020 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7021 	ctsio->kern_rel_offset = 0;
7022 	ctsio->kern_sg_entries = 0;
7023 	ctsio->kern_data_len = min(total_len, alloc_len);
7024 	ctsio->kern_total_len = ctsio->kern_data_len;
7025 
7026 	/* Fill dummy data in case backend can't tell anything. */
7027 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7028 	scsi_u64to8b(lba, data->descr[0].addr);
7029 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7030 	    data->descr[0].length);
7031 	data->descr[0].status = 0; /* Mapped or unknown. */
7032 
7033 	ctl_set_success(ctsio);
7034 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7035 	ctsio->be_move_done = ctl_config_move_done;
7036 
7037 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7038 	lbalen->lba = lba;
7039 	lbalen->len = total_len;
7040 	lbalen->flags = 0;
7041 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7042 	return (retval);
7043 }
7044 
7045 int
7046 ctl_read_defect(struct ctl_scsiio *ctsio)
7047 {
7048 	struct scsi_read_defect_data_10 *ccb10;
7049 	struct scsi_read_defect_data_12 *ccb12;
7050 	struct scsi_read_defect_data_hdr_10 *data10;
7051 	struct scsi_read_defect_data_hdr_12 *data12;
7052 	uint32_t alloc_len, data_len;
7053 	uint8_t format;
7054 
7055 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7056 
7057 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7058 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7059 		format = ccb10->format;
7060 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7061 		data_len = sizeof(*data10);
7062 	} else {
7063 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7064 		format = ccb12->format;
7065 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7066 		data_len = sizeof(*data12);
7067 	}
7068 	if (alloc_len == 0) {
7069 		ctl_set_success(ctsio);
7070 		ctl_done((union ctl_io *)ctsio);
7071 		return (CTL_RETVAL_COMPLETE);
7072 	}
7073 
7074 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7075 	ctsio->kern_rel_offset = 0;
7076 	ctsio->kern_sg_entries = 0;
7077 	ctsio->kern_data_len = min(data_len, alloc_len);
7078 	ctsio->kern_total_len = ctsio->kern_data_len;
7079 
7080 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7081 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7082 		    ctsio->kern_data_ptr;
7083 		data10->format = format;
7084 		scsi_ulto2b(0, data10->length);
7085 	} else {
7086 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7087 		    ctsio->kern_data_ptr;
7088 		data12->format = format;
7089 		scsi_ulto2b(0, data12->generation);
7090 		scsi_ulto4b(0, data12->length);
7091 	}
7092 
7093 	ctl_set_success(ctsio);
7094 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7095 	ctsio->be_move_done = ctl_config_move_done;
7096 	ctl_datamove((union ctl_io *)ctsio);
7097 	return (CTL_RETVAL_COMPLETE);
7098 }
7099 
7100 int
7101 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7102 {
7103 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7104 	struct ctl_lun *lun = CTL_LUN(ctsio);
7105 	struct scsi_maintenance_in *cdb;
7106 	int retval;
7107 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7108 	int num_ha_groups, num_target_ports, shared_group;
7109 	struct ctl_port *port;
7110 	struct scsi_target_group_data *rtg_ptr;
7111 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7112 	struct scsi_target_port_group_descriptor *tpg_desc;
7113 
7114 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7115 
7116 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7117 	retval = CTL_RETVAL_COMPLETE;
7118 
7119 	switch (cdb->byte2 & STG_PDF_MASK) {
7120 	case STG_PDF_LENGTH:
7121 		ext = 0;
7122 		break;
7123 	case STG_PDF_EXTENDED:
7124 		ext = 1;
7125 		break;
7126 	default:
7127 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7128 				      /*sks_valid*/ 1,
7129 				      /*command*/ 1,
7130 				      /*field*/ 2,
7131 				      /*bit_valid*/ 1,
7132 				      /*bit*/ 5);
7133 		ctl_done((union ctl_io *)ctsio);
7134 		return(retval);
7135 	}
7136 
7137 	num_target_ports = 0;
7138 	shared_group = (softc->is_single != 0);
7139 	mtx_lock(&softc->ctl_lock);
7140 	STAILQ_FOREACH(port, &softc->port_list, links) {
7141 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7142 			continue;
7143 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7144 			continue;
7145 		num_target_ports++;
7146 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7147 			shared_group = 1;
7148 	}
7149 	mtx_unlock(&softc->ctl_lock);
7150 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7151 
7152 	if (ext)
7153 		total_len = sizeof(struct scsi_target_group_data_extended);
7154 	else
7155 		total_len = sizeof(struct scsi_target_group_data);
7156 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7157 		(shared_group + num_ha_groups) +
7158 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7159 
7160 	alloc_len = scsi_4btoul(cdb->length);
7161 
7162 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7163 	ctsio->kern_sg_entries = 0;
7164 	ctsio->kern_rel_offset = 0;
7165 	ctsio->kern_data_len = min(total_len, alloc_len);
7166 	ctsio->kern_total_len = ctsio->kern_data_len;
7167 
7168 	if (ext) {
7169 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7170 		    ctsio->kern_data_ptr;
7171 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7172 		rtg_ext_ptr->format_type = 0x10;
7173 		rtg_ext_ptr->implicit_transition_time = 0;
7174 		tpg_desc = &rtg_ext_ptr->groups[0];
7175 	} else {
7176 		rtg_ptr = (struct scsi_target_group_data *)
7177 		    ctsio->kern_data_ptr;
7178 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7179 		tpg_desc = &rtg_ptr->groups[0];
7180 	}
7181 
7182 	mtx_lock(&softc->ctl_lock);
7183 	pg = softc->port_min / softc->port_cnt;
7184 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7185 		/* Some shelf is known to be primary. */
7186 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7187 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7188 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7189 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7190 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7191 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7192 		else
7193 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7194 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7195 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7196 		} else {
7197 			ts = os;
7198 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7199 		}
7200 	} else {
7201 		/* No known primary shelf. */
7202 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7203 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7204 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7205 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7206 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7207 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7208 		} else {
7209 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7210 		}
7211 	}
7212 	if (shared_group) {
7213 		tpg_desc->pref_state = ts;
7214 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7215 		    TPG_U_SUP | TPG_T_SUP;
7216 		scsi_ulto2b(1, tpg_desc->target_port_group);
7217 		tpg_desc->status = TPG_IMPLICIT;
7218 		pc = 0;
7219 		STAILQ_FOREACH(port, &softc->port_list, links) {
7220 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7221 				continue;
7222 			if (!softc->is_single &&
7223 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7224 				continue;
7225 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7226 				continue;
7227 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7228 			    relative_target_port_identifier);
7229 			pc++;
7230 		}
7231 		tpg_desc->target_port_count = pc;
7232 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7233 		    &tpg_desc->descriptors[pc];
7234 	}
7235 	for (g = 0; g < num_ha_groups; g++) {
7236 		tpg_desc->pref_state = (g == pg) ? ts : os;
7237 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7238 		    TPG_U_SUP | TPG_T_SUP;
7239 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7240 		tpg_desc->status = TPG_IMPLICIT;
7241 		pc = 0;
7242 		STAILQ_FOREACH(port, &softc->port_list, links) {
7243 			if (port->targ_port < g * softc->port_cnt ||
7244 			    port->targ_port >= (g + 1) * softc->port_cnt)
7245 				continue;
7246 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7247 				continue;
7248 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7249 				continue;
7250 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7251 				continue;
7252 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7253 			    relative_target_port_identifier);
7254 			pc++;
7255 		}
7256 		tpg_desc->target_port_count = pc;
7257 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7258 		    &tpg_desc->descriptors[pc];
7259 	}
7260 	mtx_unlock(&softc->ctl_lock);
7261 
7262 	ctl_set_success(ctsio);
7263 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7264 	ctsio->be_move_done = ctl_config_move_done;
7265 	ctl_datamove((union ctl_io *)ctsio);
7266 	return(retval);
7267 }
7268 
7269 int
7270 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7271 {
7272 	struct ctl_lun *lun = CTL_LUN(ctsio);
7273 	struct scsi_report_supported_opcodes *cdb;
7274 	const struct ctl_cmd_entry *entry, *sentry;
7275 	struct scsi_report_supported_opcodes_all *all;
7276 	struct scsi_report_supported_opcodes_descr *descr;
7277 	struct scsi_report_supported_opcodes_one *one;
7278 	int retval;
7279 	int alloc_len, total_len;
7280 	int opcode, service_action, i, j, num;
7281 
7282 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7283 
7284 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7285 	retval = CTL_RETVAL_COMPLETE;
7286 
7287 	opcode = cdb->requested_opcode;
7288 	service_action = scsi_2btoul(cdb->requested_service_action);
7289 	switch (cdb->options & RSO_OPTIONS_MASK) {
7290 	case RSO_OPTIONS_ALL:
7291 		num = 0;
7292 		for (i = 0; i < 256; i++) {
7293 			entry = &ctl_cmd_table[i];
7294 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7295 				for (j = 0; j < 32; j++) {
7296 					sentry = &((const struct ctl_cmd_entry *)
7297 					    entry->execute)[j];
7298 					if (ctl_cmd_applicable(
7299 					    lun->be_lun->lun_type, sentry))
7300 						num++;
7301 				}
7302 			} else {
7303 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7304 				    entry))
7305 					num++;
7306 			}
7307 		}
7308 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7309 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7310 		break;
7311 	case RSO_OPTIONS_OC:
7312 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7313 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7314 					      /*sks_valid*/ 1,
7315 					      /*command*/ 1,
7316 					      /*field*/ 2,
7317 					      /*bit_valid*/ 1,
7318 					      /*bit*/ 2);
7319 			ctl_done((union ctl_io *)ctsio);
7320 			return (CTL_RETVAL_COMPLETE);
7321 		}
7322 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7323 		break;
7324 	case RSO_OPTIONS_OC_SA:
7325 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7326 		    service_action >= 32) {
7327 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7328 					      /*sks_valid*/ 1,
7329 					      /*command*/ 1,
7330 					      /*field*/ 2,
7331 					      /*bit_valid*/ 1,
7332 					      /*bit*/ 2);
7333 			ctl_done((union ctl_io *)ctsio);
7334 			return (CTL_RETVAL_COMPLETE);
7335 		}
7336 		/* FALLTHROUGH */
7337 	case RSO_OPTIONS_OC_ASA:
7338 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7339 		break;
7340 	default:
7341 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7342 				      /*sks_valid*/ 1,
7343 				      /*command*/ 1,
7344 				      /*field*/ 2,
7345 				      /*bit_valid*/ 1,
7346 				      /*bit*/ 2);
7347 		ctl_done((union ctl_io *)ctsio);
7348 		return (CTL_RETVAL_COMPLETE);
7349 	}
7350 
7351 	alloc_len = scsi_4btoul(cdb->length);
7352 
7353 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7354 	ctsio->kern_sg_entries = 0;
7355 	ctsio->kern_rel_offset = 0;
7356 	ctsio->kern_data_len = min(total_len, alloc_len);
7357 	ctsio->kern_total_len = ctsio->kern_data_len;
7358 
7359 	switch (cdb->options & RSO_OPTIONS_MASK) {
7360 	case RSO_OPTIONS_ALL:
7361 		all = (struct scsi_report_supported_opcodes_all *)
7362 		    ctsio->kern_data_ptr;
7363 		num = 0;
7364 		for (i = 0; i < 256; i++) {
7365 			entry = &ctl_cmd_table[i];
7366 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7367 				for (j = 0; j < 32; j++) {
7368 					sentry = &((const struct ctl_cmd_entry *)
7369 					    entry->execute)[j];
7370 					if (!ctl_cmd_applicable(
7371 					    lun->be_lun->lun_type, sentry))
7372 						continue;
7373 					descr = &all->descr[num++];
7374 					descr->opcode = i;
7375 					scsi_ulto2b(j, descr->service_action);
7376 					descr->flags = RSO_SERVACTV;
7377 					scsi_ulto2b(sentry->length,
7378 					    descr->cdb_length);
7379 				}
7380 			} else {
7381 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7382 				    entry))
7383 					continue;
7384 				descr = &all->descr[num++];
7385 				descr->opcode = i;
7386 				scsi_ulto2b(0, descr->service_action);
7387 				descr->flags = 0;
7388 				scsi_ulto2b(entry->length, descr->cdb_length);
7389 			}
7390 		}
7391 		scsi_ulto4b(
7392 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7393 		    all->length);
7394 		break;
7395 	case RSO_OPTIONS_OC:
7396 		one = (struct scsi_report_supported_opcodes_one *)
7397 		    ctsio->kern_data_ptr;
7398 		entry = &ctl_cmd_table[opcode];
7399 		goto fill_one;
7400 	case RSO_OPTIONS_OC_SA:
7401 		one = (struct scsi_report_supported_opcodes_one *)
7402 		    ctsio->kern_data_ptr;
7403 		entry = &ctl_cmd_table[opcode];
7404 		entry = &((const struct ctl_cmd_entry *)
7405 		    entry->execute)[service_action];
7406 fill_one:
7407 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7408 			one->support = 3;
7409 			scsi_ulto2b(entry->length, one->cdb_length);
7410 			one->cdb_usage[0] = opcode;
7411 			memcpy(&one->cdb_usage[1], entry->usage,
7412 			    entry->length - 1);
7413 		} else
7414 			one->support = 1;
7415 		break;
7416 	case RSO_OPTIONS_OC_ASA:
7417 		one = (struct scsi_report_supported_opcodes_one *)
7418 		    ctsio->kern_data_ptr;
7419 		entry = &ctl_cmd_table[opcode];
7420 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7421 			entry = &((const struct ctl_cmd_entry *)
7422 			    entry->execute)[service_action];
7423 		} else if (service_action != 0) {
7424 			one->support = 1;
7425 			break;
7426 		}
7427 		goto fill_one;
7428 	}
7429 
7430 	ctl_set_success(ctsio);
7431 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7432 	ctsio->be_move_done = ctl_config_move_done;
7433 	ctl_datamove((union ctl_io *)ctsio);
7434 	return(retval);
7435 }
7436 
7437 int
7438 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7439 {
7440 	struct scsi_report_supported_tmf *cdb;
7441 	struct scsi_report_supported_tmf_ext_data *data;
7442 	int retval;
7443 	int alloc_len, total_len;
7444 
7445 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7446 
7447 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7448 
7449 	retval = CTL_RETVAL_COMPLETE;
7450 
7451 	if (cdb->options & RST_REPD)
7452 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7453 	else
7454 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7455 	alloc_len = scsi_4btoul(cdb->length);
7456 
7457 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7458 	ctsio->kern_sg_entries = 0;
7459 	ctsio->kern_rel_offset = 0;
7460 	ctsio->kern_data_len = min(total_len, alloc_len);
7461 	ctsio->kern_total_len = ctsio->kern_data_len;
7462 
7463 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7464 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7465 	    RST_TRS;
7466 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7467 	data->length = total_len - 4;
7468 
7469 	ctl_set_success(ctsio);
7470 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7471 	ctsio->be_move_done = ctl_config_move_done;
7472 	ctl_datamove((union ctl_io *)ctsio);
7473 	return (retval);
7474 }
7475 
7476 int
7477 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7478 {
7479 	struct scsi_report_timestamp *cdb;
7480 	struct scsi_report_timestamp_data *data;
7481 	struct timeval tv;
7482 	int64_t timestamp;
7483 	int retval;
7484 	int alloc_len, total_len;
7485 
7486 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7487 
7488 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7489 
7490 	retval = CTL_RETVAL_COMPLETE;
7491 
7492 	total_len = sizeof(struct scsi_report_timestamp_data);
7493 	alloc_len = scsi_4btoul(cdb->length);
7494 
7495 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7496 	ctsio->kern_sg_entries = 0;
7497 	ctsio->kern_rel_offset = 0;
7498 	ctsio->kern_data_len = min(total_len, alloc_len);
7499 	ctsio->kern_total_len = ctsio->kern_data_len;
7500 
7501 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7502 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7503 	data->origin = RTS_ORIG_OUTSIDE;
7504 	getmicrotime(&tv);
7505 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7506 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7507 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7508 
7509 	ctl_set_success(ctsio);
7510 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7511 	ctsio->be_move_done = ctl_config_move_done;
7512 	ctl_datamove((union ctl_io *)ctsio);
7513 	return (retval);
7514 }
7515 
7516 int
7517 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7518 {
7519 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7520 	struct ctl_lun *lun = CTL_LUN(ctsio);
7521 	struct scsi_per_res_in *cdb;
7522 	int alloc_len, total_len = 0;
7523 	/* struct scsi_per_res_in_rsrv in_data; */
7524 	uint64_t key;
7525 
7526 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7527 
7528 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7529 
7530 	alloc_len = scsi_2btoul(cdb->length);
7531 
7532 retry:
7533 	mtx_lock(&lun->lun_lock);
7534 	switch (cdb->action) {
7535 	case SPRI_RK: /* read keys */
7536 		total_len = sizeof(struct scsi_per_res_in_keys) +
7537 			lun->pr_key_count *
7538 			sizeof(struct scsi_per_res_key);
7539 		break;
7540 	case SPRI_RR: /* read reservation */
7541 		if (lun->flags & CTL_LUN_PR_RESERVED)
7542 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7543 		else
7544 			total_len = sizeof(struct scsi_per_res_in_header);
7545 		break;
7546 	case SPRI_RC: /* report capabilities */
7547 		total_len = sizeof(struct scsi_per_res_cap);
7548 		break;
7549 	case SPRI_RS: /* read full status */
7550 		total_len = sizeof(struct scsi_per_res_in_header) +
7551 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7552 		    lun->pr_key_count;
7553 		break;
7554 	default:
7555 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7556 	}
7557 	mtx_unlock(&lun->lun_lock);
7558 
7559 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7560 	ctsio->kern_rel_offset = 0;
7561 	ctsio->kern_sg_entries = 0;
7562 	ctsio->kern_data_len = min(total_len, alloc_len);
7563 	ctsio->kern_total_len = ctsio->kern_data_len;
7564 
7565 	mtx_lock(&lun->lun_lock);
7566 	switch (cdb->action) {
7567 	case SPRI_RK: { // read keys
7568         struct scsi_per_res_in_keys *res_keys;
7569 		int i, key_count;
7570 
7571 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7572 
7573 		/*
7574 		 * We had to drop the lock to allocate our buffer, which
7575 		 * leaves time for someone to come in with another
7576 		 * persistent reservation.  (That is unlikely, though,
7577 		 * since this should be the only persistent reservation
7578 		 * command active right now.)
7579 		 */
7580 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7581 		    (lun->pr_key_count *
7582 		     sizeof(struct scsi_per_res_key)))){
7583 			mtx_unlock(&lun->lun_lock);
7584 			free(ctsio->kern_data_ptr, M_CTL);
7585 			printf("%s: reservation length changed, retrying\n",
7586 			       __func__);
7587 			goto retry;
7588 		}
7589 
7590 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7591 
7592 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7593 			     lun->pr_key_count, res_keys->header.length);
7594 
7595 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7596 			if ((key = ctl_get_prkey(lun, i)) == 0)
7597 				continue;
7598 
7599 			/*
7600 			 * We used lun->pr_key_count to calculate the
7601 			 * size to allocate.  If it turns out the number of
7602 			 * initiators with the registered flag set is
7603 			 * larger than that (i.e. they haven't been kept in
7604 			 * sync), we've got a problem.
7605 			 */
7606 			if (key_count >= lun->pr_key_count) {
7607 				key_count++;
7608 				continue;
7609 			}
7610 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7611 			key_count++;
7612 		}
7613 		break;
7614 	}
7615 	case SPRI_RR: { // read reservation
7616 		struct scsi_per_res_in_rsrv *res;
7617 		int tmp_len, header_only;
7618 
7619 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7620 
7621 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7622 
7623 		if (lun->flags & CTL_LUN_PR_RESERVED)
7624 		{
7625 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7626 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7627 				    res->header.length);
7628 			header_only = 0;
7629 		} else {
7630 			tmp_len = sizeof(struct scsi_per_res_in_header);
7631 			scsi_ulto4b(0, res->header.length);
7632 			header_only = 1;
7633 		}
7634 
7635 		/*
7636 		 * We had to drop the lock to allocate our buffer, which
7637 		 * leaves time for someone to come in with another
7638 		 * persistent reservation.  (That is unlikely, though,
7639 		 * since this should be the only persistent reservation
7640 		 * command active right now.)
7641 		 */
7642 		if (tmp_len != total_len) {
7643 			mtx_unlock(&lun->lun_lock);
7644 			free(ctsio->kern_data_ptr, M_CTL);
7645 			printf("%s: reservation status changed, retrying\n",
7646 			       __func__);
7647 			goto retry;
7648 		}
7649 
7650 		/*
7651 		 * No reservation held, so we're done.
7652 		 */
7653 		if (header_only != 0)
7654 			break;
7655 
7656 		/*
7657 		 * If the registration is an All Registrants type, the key
7658 		 * is 0, since it doesn't really matter.
7659 		 */
7660 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7661 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7662 			    res->data.reservation);
7663 		}
7664 		res->data.scopetype = lun->pr_res_type;
7665 		break;
7666 	}
7667 	case SPRI_RC:     //report capabilities
7668 	{
7669 		struct scsi_per_res_cap *res_cap;
7670 		uint16_t type_mask;
7671 
7672 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7673 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7674 		res_cap->flags1 = SPRI_CRH;
7675 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7676 		type_mask = SPRI_TM_WR_EX_AR |
7677 			    SPRI_TM_EX_AC_RO |
7678 			    SPRI_TM_WR_EX_RO |
7679 			    SPRI_TM_EX_AC |
7680 			    SPRI_TM_WR_EX |
7681 			    SPRI_TM_EX_AC_AR;
7682 		scsi_ulto2b(type_mask, res_cap->type_mask);
7683 		break;
7684 	}
7685 	case SPRI_RS: { // read full status
7686 		struct scsi_per_res_in_full *res_status;
7687 		struct scsi_per_res_in_full_desc *res_desc;
7688 		struct ctl_port *port;
7689 		int i, len;
7690 
7691 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7692 
7693 		/*
7694 		 * We had to drop the lock to allocate our buffer, which
7695 		 * leaves time for someone to come in with another
7696 		 * persistent reservation.  (That is unlikely, though,
7697 		 * since this should be the only persistent reservation
7698 		 * command active right now.)
7699 		 */
7700 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7701 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7702 		     lun->pr_key_count)){
7703 			mtx_unlock(&lun->lun_lock);
7704 			free(ctsio->kern_data_ptr, M_CTL);
7705 			printf("%s: reservation length changed, retrying\n",
7706 			       __func__);
7707 			goto retry;
7708 		}
7709 
7710 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7711 
7712 		res_desc = &res_status->desc[0];
7713 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7714 			if ((key = ctl_get_prkey(lun, i)) == 0)
7715 				continue;
7716 
7717 			scsi_u64to8b(key, res_desc->res_key.key);
7718 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7719 			    (lun->pr_res_idx == i ||
7720 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7721 				res_desc->flags = SPRI_FULL_R_HOLDER;
7722 				res_desc->scopetype = lun->pr_res_type;
7723 			}
7724 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7725 			    res_desc->rel_trgt_port_id);
7726 			len = 0;
7727 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7728 			if (port != NULL)
7729 				len = ctl_create_iid(port,
7730 				    i % CTL_MAX_INIT_PER_PORT,
7731 				    res_desc->transport_id);
7732 			scsi_ulto4b(len, res_desc->additional_length);
7733 			res_desc = (struct scsi_per_res_in_full_desc *)
7734 			    &res_desc->transport_id[len];
7735 		}
7736 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7737 		    res_status->header.length);
7738 		break;
7739 	}
7740 	default:
7741 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7742 	}
7743 	mtx_unlock(&lun->lun_lock);
7744 
7745 	ctl_set_success(ctsio);
7746 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7747 	ctsio->be_move_done = ctl_config_move_done;
7748 	ctl_datamove((union ctl_io *)ctsio);
7749 	return (CTL_RETVAL_COMPLETE);
7750 }
7751 
7752 /*
7753  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7754  * it should return.
7755  */
7756 static int
7757 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7758 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7759 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7760 		struct scsi_per_res_out_parms* param)
7761 {
7762 	union ctl_ha_msg persis_io;
7763 	int i;
7764 
7765 	mtx_lock(&lun->lun_lock);
7766 	if (sa_res_key == 0) {
7767 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7768 			/* validate scope and type */
7769 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7770 			     SPR_LU_SCOPE) {
7771 				mtx_unlock(&lun->lun_lock);
7772 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7773 						      /*sks_valid*/ 1,
7774 						      /*command*/ 1,
7775 						      /*field*/ 2,
7776 						      /*bit_valid*/ 1,
7777 						      /*bit*/ 4);
7778 				ctl_done((union ctl_io *)ctsio);
7779 				return (1);
7780 			}
7781 
7782 		        if (type>8 || type==2 || type==4 || type==0) {
7783 				mtx_unlock(&lun->lun_lock);
7784 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7785        	           				      /*sks_valid*/ 1,
7786 						      /*command*/ 1,
7787 						      /*field*/ 2,
7788 						      /*bit_valid*/ 1,
7789 						      /*bit*/ 0);
7790 				ctl_done((union ctl_io *)ctsio);
7791 				return (1);
7792 		        }
7793 
7794 			/*
7795 			 * Unregister everybody else and build UA for
7796 			 * them
7797 			 */
7798 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7799 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7800 					continue;
7801 
7802 				ctl_clr_prkey(lun, i);
7803 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7804 			}
7805 			lun->pr_key_count = 1;
7806 			lun->pr_res_type = type;
7807 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7808 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7809 				lun->pr_res_idx = residx;
7810 			lun->pr_generation++;
7811 			mtx_unlock(&lun->lun_lock);
7812 
7813 			/* send msg to other side */
7814 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7815 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7816 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7817 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7818 			persis_io.pr.pr_info.res_type = type;
7819 			memcpy(persis_io.pr.pr_info.sa_res_key,
7820 			       param->serv_act_res_key,
7821 			       sizeof(param->serv_act_res_key));
7822 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7823 			    sizeof(persis_io.pr), M_WAITOK);
7824 		} else {
7825 			/* not all registrants */
7826 			mtx_unlock(&lun->lun_lock);
7827 			free(ctsio->kern_data_ptr, M_CTL);
7828 			ctl_set_invalid_field(ctsio,
7829 					      /*sks_valid*/ 1,
7830 					      /*command*/ 0,
7831 					      /*field*/ 8,
7832 					      /*bit_valid*/ 0,
7833 					      /*bit*/ 0);
7834 			ctl_done((union ctl_io *)ctsio);
7835 			return (1);
7836 		}
7837 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7838 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7839 		int found = 0;
7840 
7841 		if (res_key == sa_res_key) {
7842 			/* special case */
7843 			/*
7844 			 * The spec implies this is not good but doesn't
7845 			 * say what to do. There are two choices either
7846 			 * generate a res conflict or check condition
7847 			 * with illegal field in parameter data. Since
7848 			 * that is what is done when the sa_res_key is
7849 			 * zero I'll take that approach since this has
7850 			 * to do with the sa_res_key.
7851 			 */
7852 			mtx_unlock(&lun->lun_lock);
7853 			free(ctsio->kern_data_ptr, M_CTL);
7854 			ctl_set_invalid_field(ctsio,
7855 					      /*sks_valid*/ 1,
7856 					      /*command*/ 0,
7857 					      /*field*/ 8,
7858 					      /*bit_valid*/ 0,
7859 					      /*bit*/ 0);
7860 			ctl_done((union ctl_io *)ctsio);
7861 			return (1);
7862 		}
7863 
7864 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7865 			if (ctl_get_prkey(lun, i) != sa_res_key)
7866 				continue;
7867 
7868 			found = 1;
7869 			ctl_clr_prkey(lun, i);
7870 			lun->pr_key_count--;
7871 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7872 		}
7873 		if (!found) {
7874 			mtx_unlock(&lun->lun_lock);
7875 			free(ctsio->kern_data_ptr, M_CTL);
7876 			ctl_set_reservation_conflict(ctsio);
7877 			ctl_done((union ctl_io *)ctsio);
7878 			return (CTL_RETVAL_COMPLETE);
7879 		}
7880 		lun->pr_generation++;
7881 		mtx_unlock(&lun->lun_lock);
7882 
7883 		/* send msg to other side */
7884 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7885 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7886 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7887 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7888 		persis_io.pr.pr_info.res_type = type;
7889 		memcpy(persis_io.pr.pr_info.sa_res_key,
7890 		       param->serv_act_res_key,
7891 		       sizeof(param->serv_act_res_key));
7892 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7893 		    sizeof(persis_io.pr), M_WAITOK);
7894 	} else {
7895 		/* Reserved but not all registrants */
7896 		/* sa_res_key is res holder */
7897 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7898 			/* validate scope and type */
7899 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7900 			     SPR_LU_SCOPE) {
7901 				mtx_unlock(&lun->lun_lock);
7902 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7903 						      /*sks_valid*/ 1,
7904 						      /*command*/ 1,
7905 						      /*field*/ 2,
7906 						      /*bit_valid*/ 1,
7907 						      /*bit*/ 4);
7908 				ctl_done((union ctl_io *)ctsio);
7909 				return (1);
7910 			}
7911 
7912 			if (type>8 || type==2 || type==4 || type==0) {
7913 				mtx_unlock(&lun->lun_lock);
7914 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7915 						      /*sks_valid*/ 1,
7916 						      /*command*/ 1,
7917 						      /*field*/ 2,
7918 						      /*bit_valid*/ 1,
7919 						      /*bit*/ 0);
7920 				ctl_done((union ctl_io *)ctsio);
7921 				return (1);
7922 			}
7923 
7924 			/*
7925 			 * Do the following:
7926 			 * if sa_res_key != res_key remove all
7927 			 * registrants w/sa_res_key and generate UA
7928 			 * for these registrants(Registrations
7929 			 * Preempted) if it wasn't an exclusive
7930 			 * reservation generate UA(Reservations
7931 			 * Preempted) for all other registered nexuses
7932 			 * if the type has changed. Establish the new
7933 			 * reservation and holder. If res_key and
7934 			 * sa_res_key are the same do the above
7935 			 * except don't unregister the res holder.
7936 			 */
7937 
7938 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7939 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7940 					continue;
7941 
7942 				if (sa_res_key == ctl_get_prkey(lun, i)) {
7943 					ctl_clr_prkey(lun, i);
7944 					lun->pr_key_count--;
7945 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7946 				} else if (type != lun->pr_res_type &&
7947 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7948 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7949 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7950 				}
7951 			}
7952 			lun->pr_res_type = type;
7953 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7954 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7955 				lun->pr_res_idx = residx;
7956 			else
7957 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7958 			lun->pr_generation++;
7959 			mtx_unlock(&lun->lun_lock);
7960 
7961 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7962 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7963 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7964 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7965 			persis_io.pr.pr_info.res_type = type;
7966 			memcpy(persis_io.pr.pr_info.sa_res_key,
7967 			       param->serv_act_res_key,
7968 			       sizeof(param->serv_act_res_key));
7969 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7970 			    sizeof(persis_io.pr), M_WAITOK);
7971 		} else {
7972 			/*
7973 			 * sa_res_key is not the res holder just
7974 			 * remove registrants
7975 			 */
7976 			int found=0;
7977 
7978 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7979 				if (sa_res_key != ctl_get_prkey(lun, i))
7980 					continue;
7981 
7982 				found = 1;
7983 				ctl_clr_prkey(lun, i);
7984 				lun->pr_key_count--;
7985 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7986 			}
7987 
7988 			if (!found) {
7989 				mtx_unlock(&lun->lun_lock);
7990 				free(ctsio->kern_data_ptr, M_CTL);
7991 				ctl_set_reservation_conflict(ctsio);
7992 				ctl_done((union ctl_io *)ctsio);
7993 		        	return (1);
7994 			}
7995 			lun->pr_generation++;
7996 			mtx_unlock(&lun->lun_lock);
7997 
7998 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7999 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8000 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8001 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8002 			persis_io.pr.pr_info.res_type = type;
8003 			memcpy(persis_io.pr.pr_info.sa_res_key,
8004 			       param->serv_act_res_key,
8005 			       sizeof(param->serv_act_res_key));
8006 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8007 			    sizeof(persis_io.pr), M_WAITOK);
8008 		}
8009 	}
8010 	return (0);
8011 }
8012 
8013 static void
8014 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8015 {
8016 	uint64_t sa_res_key;
8017 	int i;
8018 
8019 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8020 
8021 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8022 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8023 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8024 		if (sa_res_key == 0) {
8025 			/*
8026 			 * Unregister everybody else and build UA for
8027 			 * them
8028 			 */
8029 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8030 				if (i == msg->pr.pr_info.residx ||
8031 				    ctl_get_prkey(lun, i) == 0)
8032 					continue;
8033 
8034 				ctl_clr_prkey(lun, i);
8035 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8036 			}
8037 
8038 			lun->pr_key_count = 1;
8039 			lun->pr_res_type = msg->pr.pr_info.res_type;
8040 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8041 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8042 				lun->pr_res_idx = msg->pr.pr_info.residx;
8043 		} else {
8044 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8045 				if (sa_res_key == ctl_get_prkey(lun, i))
8046 					continue;
8047 
8048 				ctl_clr_prkey(lun, i);
8049 				lun->pr_key_count--;
8050 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8051 			}
8052 		}
8053 	} else {
8054 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8055 			if (i == msg->pr.pr_info.residx ||
8056 			    ctl_get_prkey(lun, i) == 0)
8057 				continue;
8058 
8059 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8060 				ctl_clr_prkey(lun, i);
8061 				lun->pr_key_count--;
8062 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8063 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8064 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8065 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8066 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8067 			}
8068 		}
8069 		lun->pr_res_type = msg->pr.pr_info.res_type;
8070 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8071 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8072 			lun->pr_res_idx = msg->pr.pr_info.residx;
8073 		else
8074 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8075 	}
8076 	lun->pr_generation++;
8077 
8078 }
8079 
8080 
8081 int
8082 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8083 {
8084 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8085 	struct ctl_lun *lun = CTL_LUN(ctsio);
8086 	int retval;
8087 	u_int32_t param_len;
8088 	struct scsi_per_res_out *cdb;
8089 	struct scsi_per_res_out_parms* param;
8090 	uint32_t residx;
8091 	uint64_t res_key, sa_res_key, key;
8092 	uint8_t type;
8093 	union ctl_ha_msg persis_io;
8094 	int    i;
8095 
8096 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8097 
8098 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8099 	retval = CTL_RETVAL_COMPLETE;
8100 
8101 	/*
8102 	 * We only support whole-LUN scope.  The scope & type are ignored for
8103 	 * register, register and ignore existing key and clear.
8104 	 * We sometimes ignore scope and type on preempts too!!
8105 	 * Verify reservation type here as well.
8106 	 */
8107 	type = cdb->scope_type & SPR_TYPE_MASK;
8108 	if ((cdb->action == SPRO_RESERVE)
8109 	 || (cdb->action == SPRO_RELEASE)) {
8110 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8111 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8112 					      /*sks_valid*/ 1,
8113 					      /*command*/ 1,
8114 					      /*field*/ 2,
8115 					      /*bit_valid*/ 1,
8116 					      /*bit*/ 4);
8117 			ctl_done((union ctl_io *)ctsio);
8118 			return (CTL_RETVAL_COMPLETE);
8119 		}
8120 
8121 		if (type>8 || type==2 || type==4 || type==0) {
8122 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8123 					      /*sks_valid*/ 1,
8124 					      /*command*/ 1,
8125 					      /*field*/ 2,
8126 					      /*bit_valid*/ 1,
8127 					      /*bit*/ 0);
8128 			ctl_done((union ctl_io *)ctsio);
8129 			return (CTL_RETVAL_COMPLETE);
8130 		}
8131 	}
8132 
8133 	param_len = scsi_4btoul(cdb->length);
8134 
8135 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8136 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8137 		ctsio->kern_data_len = param_len;
8138 		ctsio->kern_total_len = param_len;
8139 		ctsio->kern_rel_offset = 0;
8140 		ctsio->kern_sg_entries = 0;
8141 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8142 		ctsio->be_move_done = ctl_config_move_done;
8143 		ctl_datamove((union ctl_io *)ctsio);
8144 
8145 		return (CTL_RETVAL_COMPLETE);
8146 	}
8147 
8148 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8149 
8150 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8151 	res_key = scsi_8btou64(param->res_key.key);
8152 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8153 
8154 	/*
8155 	 * Validate the reservation key here except for SPRO_REG_IGNO
8156 	 * This must be done for all other service actions
8157 	 */
8158 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8159 		mtx_lock(&lun->lun_lock);
8160 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8161 			if (res_key != key) {
8162 				/*
8163 				 * The current key passed in doesn't match
8164 				 * the one the initiator previously
8165 				 * registered.
8166 				 */
8167 				mtx_unlock(&lun->lun_lock);
8168 				free(ctsio->kern_data_ptr, M_CTL);
8169 				ctl_set_reservation_conflict(ctsio);
8170 				ctl_done((union ctl_io *)ctsio);
8171 				return (CTL_RETVAL_COMPLETE);
8172 			}
8173 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8174 			/*
8175 			 * We are not registered
8176 			 */
8177 			mtx_unlock(&lun->lun_lock);
8178 			free(ctsio->kern_data_ptr, M_CTL);
8179 			ctl_set_reservation_conflict(ctsio);
8180 			ctl_done((union ctl_io *)ctsio);
8181 			return (CTL_RETVAL_COMPLETE);
8182 		} else if (res_key != 0) {
8183 			/*
8184 			 * We are not registered and trying to register but
8185 			 * the register key isn't zero.
8186 			 */
8187 			mtx_unlock(&lun->lun_lock);
8188 			free(ctsio->kern_data_ptr, M_CTL);
8189 			ctl_set_reservation_conflict(ctsio);
8190 			ctl_done((union ctl_io *)ctsio);
8191 			return (CTL_RETVAL_COMPLETE);
8192 		}
8193 		mtx_unlock(&lun->lun_lock);
8194 	}
8195 
8196 	switch (cdb->action & SPRO_ACTION_MASK) {
8197 	case SPRO_REGISTER:
8198 	case SPRO_REG_IGNO: {
8199 
8200 		/*
8201 		 * We don't support any of these options, as we report in
8202 		 * the read capabilities request (see
8203 		 * ctl_persistent_reserve_in(), above).
8204 		 */
8205 		if ((param->flags & SPR_SPEC_I_PT)
8206 		 || (param->flags & SPR_ALL_TG_PT)
8207 		 || (param->flags & SPR_APTPL)) {
8208 			int bit_ptr;
8209 
8210 			if (param->flags & SPR_APTPL)
8211 				bit_ptr = 0;
8212 			else if (param->flags & SPR_ALL_TG_PT)
8213 				bit_ptr = 2;
8214 			else /* SPR_SPEC_I_PT */
8215 				bit_ptr = 3;
8216 
8217 			free(ctsio->kern_data_ptr, M_CTL);
8218 			ctl_set_invalid_field(ctsio,
8219 					      /*sks_valid*/ 1,
8220 					      /*command*/ 0,
8221 					      /*field*/ 20,
8222 					      /*bit_valid*/ 1,
8223 					      /*bit*/ bit_ptr);
8224 			ctl_done((union ctl_io *)ctsio);
8225 			return (CTL_RETVAL_COMPLETE);
8226 		}
8227 
8228 		mtx_lock(&lun->lun_lock);
8229 
8230 		/*
8231 		 * The initiator wants to clear the
8232 		 * key/unregister.
8233 		 */
8234 		if (sa_res_key == 0) {
8235 			if ((res_key == 0
8236 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8237 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8238 			  && ctl_get_prkey(lun, residx) == 0)) {
8239 				mtx_unlock(&lun->lun_lock);
8240 				goto done;
8241 			}
8242 
8243 			ctl_clr_prkey(lun, residx);
8244 			lun->pr_key_count--;
8245 
8246 			if (residx == lun->pr_res_idx) {
8247 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8248 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8249 
8250 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8251 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8252 				    lun->pr_key_count) {
8253 					/*
8254 					 * If the reservation is a registrants
8255 					 * only type we need to generate a UA
8256 					 * for other registered inits.  The
8257 					 * sense code should be RESERVATIONS
8258 					 * RELEASED
8259 					 */
8260 
8261 					for (i = softc->init_min; i < softc->init_max; i++){
8262 						if (ctl_get_prkey(lun, i) == 0)
8263 							continue;
8264 						ctl_est_ua(lun, i,
8265 						    CTL_UA_RES_RELEASE);
8266 					}
8267 				}
8268 				lun->pr_res_type = 0;
8269 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8270 				if (lun->pr_key_count==0) {
8271 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8272 					lun->pr_res_type = 0;
8273 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8274 				}
8275 			}
8276 			lun->pr_generation++;
8277 			mtx_unlock(&lun->lun_lock);
8278 
8279 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8280 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8281 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8282 			persis_io.pr.pr_info.residx = residx;
8283 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8284 			    sizeof(persis_io.pr), M_WAITOK);
8285 		} else /* sa_res_key != 0 */ {
8286 
8287 			/*
8288 			 * If we aren't registered currently then increment
8289 			 * the key count and set the registered flag.
8290 			 */
8291 			ctl_alloc_prkey(lun, residx);
8292 			if (ctl_get_prkey(lun, residx) == 0)
8293 				lun->pr_key_count++;
8294 			ctl_set_prkey(lun, residx, sa_res_key);
8295 			lun->pr_generation++;
8296 			mtx_unlock(&lun->lun_lock);
8297 
8298 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8299 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8300 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8301 			persis_io.pr.pr_info.residx = residx;
8302 			memcpy(persis_io.pr.pr_info.sa_res_key,
8303 			       param->serv_act_res_key,
8304 			       sizeof(param->serv_act_res_key));
8305 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8306 			    sizeof(persis_io.pr), M_WAITOK);
8307 		}
8308 
8309 		break;
8310 	}
8311 	case SPRO_RESERVE:
8312 		mtx_lock(&lun->lun_lock);
8313 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8314 			/*
8315 			 * if this isn't the reservation holder and it's
8316 			 * not a "all registrants" type or if the type is
8317 			 * different then we have a conflict
8318 			 */
8319 			if ((lun->pr_res_idx != residx
8320 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8321 			 || lun->pr_res_type != type) {
8322 				mtx_unlock(&lun->lun_lock);
8323 				free(ctsio->kern_data_ptr, M_CTL);
8324 				ctl_set_reservation_conflict(ctsio);
8325 				ctl_done((union ctl_io *)ctsio);
8326 				return (CTL_RETVAL_COMPLETE);
8327 			}
8328 			mtx_unlock(&lun->lun_lock);
8329 		} else /* create a reservation */ {
8330 			/*
8331 			 * If it's not an "all registrants" type record
8332 			 * reservation holder
8333 			 */
8334 			if (type != SPR_TYPE_WR_EX_AR
8335 			 && type != SPR_TYPE_EX_AC_AR)
8336 				lun->pr_res_idx = residx; /* Res holder */
8337 			else
8338 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8339 
8340 			lun->flags |= CTL_LUN_PR_RESERVED;
8341 			lun->pr_res_type = type;
8342 
8343 			mtx_unlock(&lun->lun_lock);
8344 
8345 			/* send msg to other side */
8346 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8347 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8348 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8349 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8350 			persis_io.pr.pr_info.res_type = type;
8351 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8352 			    sizeof(persis_io.pr), M_WAITOK);
8353 		}
8354 		break;
8355 
8356 	case SPRO_RELEASE:
8357 		mtx_lock(&lun->lun_lock);
8358 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8359 			/* No reservation exists return good status */
8360 			mtx_unlock(&lun->lun_lock);
8361 			goto done;
8362 		}
8363 		/*
8364 		 * Is this nexus a reservation holder?
8365 		 */
8366 		if (lun->pr_res_idx != residx
8367 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8368 			/*
8369 			 * not a res holder return good status but
8370 			 * do nothing
8371 			 */
8372 			mtx_unlock(&lun->lun_lock);
8373 			goto done;
8374 		}
8375 
8376 		if (lun->pr_res_type != type) {
8377 			mtx_unlock(&lun->lun_lock);
8378 			free(ctsio->kern_data_ptr, M_CTL);
8379 			ctl_set_illegal_pr_release(ctsio);
8380 			ctl_done((union ctl_io *)ctsio);
8381 			return (CTL_RETVAL_COMPLETE);
8382 		}
8383 
8384 		/* okay to release */
8385 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8386 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8387 		lun->pr_res_type = 0;
8388 
8389 		/*
8390 		 * If this isn't an exclusive access reservation and NUAR
8391 		 * is not set, generate UA for all other registrants.
8392 		 */
8393 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8394 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8395 			for (i = softc->init_min; i < softc->init_max; i++) {
8396 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8397 					continue;
8398 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8399 			}
8400 		}
8401 		mtx_unlock(&lun->lun_lock);
8402 
8403 		/* Send msg to other side */
8404 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8405 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8406 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8407 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8408 		     sizeof(persis_io.pr), M_WAITOK);
8409 		break;
8410 
8411 	case SPRO_CLEAR:
8412 		/* send msg to other side */
8413 
8414 		mtx_lock(&lun->lun_lock);
8415 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8416 		lun->pr_res_type = 0;
8417 		lun->pr_key_count = 0;
8418 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8419 
8420 		ctl_clr_prkey(lun, residx);
8421 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8422 			if (ctl_get_prkey(lun, i) != 0) {
8423 				ctl_clr_prkey(lun, i);
8424 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8425 			}
8426 		lun->pr_generation++;
8427 		mtx_unlock(&lun->lun_lock);
8428 
8429 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8430 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8431 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8432 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8433 		     sizeof(persis_io.pr), M_WAITOK);
8434 		break;
8435 
8436 	case SPRO_PREEMPT:
8437 	case SPRO_PRE_ABO: {
8438 		int nretval;
8439 
8440 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8441 					  residx, ctsio, cdb, param);
8442 		if (nretval != 0)
8443 			return (CTL_RETVAL_COMPLETE);
8444 		break;
8445 	}
8446 	default:
8447 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8448 	}
8449 
8450 done:
8451 	free(ctsio->kern_data_ptr, M_CTL);
8452 	ctl_set_success(ctsio);
8453 	ctl_done((union ctl_io *)ctsio);
8454 
8455 	return (retval);
8456 }
8457 
8458 /*
8459  * This routine is for handling a message from the other SC pertaining to
8460  * persistent reserve out. All the error checking will have been done
8461  * so only perorming the action need be done here to keep the two
8462  * in sync.
8463  */
8464 static void
8465 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8466 {
8467 	struct ctl_softc *softc = CTL_SOFTC(io);
8468 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8469 	struct ctl_lun *lun;
8470 	int i;
8471 	uint32_t residx, targ_lun;
8472 
8473 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8474 	mtx_lock(&softc->ctl_lock);
8475 	if (targ_lun >= ctl_max_luns ||
8476 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8477 		mtx_unlock(&softc->ctl_lock);
8478 		return;
8479 	}
8480 	mtx_lock(&lun->lun_lock);
8481 	mtx_unlock(&softc->ctl_lock);
8482 	if (lun->flags & CTL_LUN_DISABLED) {
8483 		mtx_unlock(&lun->lun_lock);
8484 		return;
8485 	}
8486 	residx = ctl_get_initindex(&msg->hdr.nexus);
8487 	switch(msg->pr.pr_info.action) {
8488 	case CTL_PR_REG_KEY:
8489 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8490 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8491 			lun->pr_key_count++;
8492 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8493 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8494 		lun->pr_generation++;
8495 		break;
8496 
8497 	case CTL_PR_UNREG_KEY:
8498 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8499 		lun->pr_key_count--;
8500 
8501 		/* XXX Need to see if the reservation has been released */
8502 		/* if so do we need to generate UA? */
8503 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8504 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8505 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8506 
8507 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8508 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8509 			    lun->pr_key_count) {
8510 				/*
8511 				 * If the reservation is a registrants
8512 				 * only type we need to generate a UA
8513 				 * for other registered inits.  The
8514 				 * sense code should be RESERVATIONS
8515 				 * RELEASED
8516 				 */
8517 
8518 				for (i = softc->init_min; i < softc->init_max; i++) {
8519 					if (ctl_get_prkey(lun, i) == 0)
8520 						continue;
8521 
8522 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8523 				}
8524 			}
8525 			lun->pr_res_type = 0;
8526 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8527 			if (lun->pr_key_count==0) {
8528 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8529 				lun->pr_res_type = 0;
8530 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8531 			}
8532 		}
8533 		lun->pr_generation++;
8534 		break;
8535 
8536 	case CTL_PR_RESERVE:
8537 		lun->flags |= CTL_LUN_PR_RESERVED;
8538 		lun->pr_res_type = msg->pr.pr_info.res_type;
8539 		lun->pr_res_idx = msg->pr.pr_info.residx;
8540 
8541 		break;
8542 
8543 	case CTL_PR_RELEASE:
8544 		/*
8545 		 * If this isn't an exclusive access reservation and NUAR
8546 		 * is not set, generate UA for all other registrants.
8547 		 */
8548 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8549 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8550 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8551 			for (i = softc->init_min; i < softc->init_max; i++) {
8552 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8553 					continue;
8554 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8555 			}
8556 		}
8557 
8558 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8559 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8560 		lun->pr_res_type = 0;
8561 		break;
8562 
8563 	case CTL_PR_PREEMPT:
8564 		ctl_pro_preempt_other(lun, msg);
8565 		break;
8566 	case CTL_PR_CLEAR:
8567 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8568 		lun->pr_res_type = 0;
8569 		lun->pr_key_count = 0;
8570 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8571 
8572 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8573 			if (ctl_get_prkey(lun, i) == 0)
8574 				continue;
8575 			ctl_clr_prkey(lun, i);
8576 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8577 		}
8578 		lun->pr_generation++;
8579 		break;
8580 	}
8581 
8582 	mtx_unlock(&lun->lun_lock);
8583 }
8584 
8585 int
8586 ctl_read_write(struct ctl_scsiio *ctsio)
8587 {
8588 	struct ctl_lun *lun = CTL_LUN(ctsio);
8589 	struct ctl_lba_len_flags *lbalen;
8590 	uint64_t lba;
8591 	uint32_t num_blocks;
8592 	int flags, retval;
8593 	int isread;
8594 
8595 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8596 
8597 	flags = 0;
8598 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8599 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8600 	switch (ctsio->cdb[0]) {
8601 	case READ_6:
8602 	case WRITE_6: {
8603 		struct scsi_rw_6 *cdb;
8604 
8605 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8606 
8607 		lba = scsi_3btoul(cdb->addr);
8608 		/* only 5 bits are valid in the most significant address byte */
8609 		lba &= 0x1fffff;
8610 		num_blocks = cdb->length;
8611 		/*
8612 		 * This is correct according to SBC-2.
8613 		 */
8614 		if (num_blocks == 0)
8615 			num_blocks = 256;
8616 		break;
8617 	}
8618 	case READ_10:
8619 	case WRITE_10: {
8620 		struct scsi_rw_10 *cdb;
8621 
8622 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8623 		if (cdb->byte2 & SRW10_FUA)
8624 			flags |= CTL_LLF_FUA;
8625 		if (cdb->byte2 & SRW10_DPO)
8626 			flags |= CTL_LLF_DPO;
8627 		lba = scsi_4btoul(cdb->addr);
8628 		num_blocks = scsi_2btoul(cdb->length);
8629 		break;
8630 	}
8631 	case WRITE_VERIFY_10: {
8632 		struct scsi_write_verify_10 *cdb;
8633 
8634 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8635 		flags |= CTL_LLF_FUA;
8636 		if (cdb->byte2 & SWV_DPO)
8637 			flags |= CTL_LLF_DPO;
8638 		lba = scsi_4btoul(cdb->addr);
8639 		num_blocks = scsi_2btoul(cdb->length);
8640 		break;
8641 	}
8642 	case READ_12:
8643 	case WRITE_12: {
8644 		struct scsi_rw_12 *cdb;
8645 
8646 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8647 		if (cdb->byte2 & SRW12_FUA)
8648 			flags |= CTL_LLF_FUA;
8649 		if (cdb->byte2 & SRW12_DPO)
8650 			flags |= CTL_LLF_DPO;
8651 		lba = scsi_4btoul(cdb->addr);
8652 		num_blocks = scsi_4btoul(cdb->length);
8653 		break;
8654 	}
8655 	case WRITE_VERIFY_12: {
8656 		struct scsi_write_verify_12 *cdb;
8657 
8658 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8659 		flags |= CTL_LLF_FUA;
8660 		if (cdb->byte2 & SWV_DPO)
8661 			flags |= CTL_LLF_DPO;
8662 		lba = scsi_4btoul(cdb->addr);
8663 		num_blocks = scsi_4btoul(cdb->length);
8664 		break;
8665 	}
8666 	case READ_16:
8667 	case WRITE_16: {
8668 		struct scsi_rw_16 *cdb;
8669 
8670 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8671 		if (cdb->byte2 & SRW12_FUA)
8672 			flags |= CTL_LLF_FUA;
8673 		if (cdb->byte2 & SRW12_DPO)
8674 			flags |= CTL_LLF_DPO;
8675 		lba = scsi_8btou64(cdb->addr);
8676 		num_blocks = scsi_4btoul(cdb->length);
8677 		break;
8678 	}
8679 	case WRITE_ATOMIC_16: {
8680 		struct scsi_write_atomic_16 *cdb;
8681 
8682 		if (lun->be_lun->atomicblock == 0) {
8683 			ctl_set_invalid_opcode(ctsio);
8684 			ctl_done((union ctl_io *)ctsio);
8685 			return (CTL_RETVAL_COMPLETE);
8686 		}
8687 
8688 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8689 		if (cdb->byte2 & SRW12_FUA)
8690 			flags |= CTL_LLF_FUA;
8691 		if (cdb->byte2 & SRW12_DPO)
8692 			flags |= CTL_LLF_DPO;
8693 		lba = scsi_8btou64(cdb->addr);
8694 		num_blocks = scsi_2btoul(cdb->length);
8695 		if (num_blocks > lun->be_lun->atomicblock) {
8696 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8697 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8698 			    /*bit*/ 0);
8699 			ctl_done((union ctl_io *)ctsio);
8700 			return (CTL_RETVAL_COMPLETE);
8701 		}
8702 		break;
8703 	}
8704 	case WRITE_VERIFY_16: {
8705 		struct scsi_write_verify_16 *cdb;
8706 
8707 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8708 		flags |= CTL_LLF_FUA;
8709 		if (cdb->byte2 & SWV_DPO)
8710 			flags |= CTL_LLF_DPO;
8711 		lba = scsi_8btou64(cdb->addr);
8712 		num_blocks = scsi_4btoul(cdb->length);
8713 		break;
8714 	}
8715 	default:
8716 		/*
8717 		 * We got a command we don't support.  This shouldn't
8718 		 * happen, commands should be filtered out above us.
8719 		 */
8720 		ctl_set_invalid_opcode(ctsio);
8721 		ctl_done((union ctl_io *)ctsio);
8722 
8723 		return (CTL_RETVAL_COMPLETE);
8724 		break; /* NOTREACHED */
8725 	}
8726 
8727 	/*
8728 	 * The first check is to make sure we're in bounds, the second
8729 	 * check is to catch wrap-around problems.  If the lba + num blocks
8730 	 * is less than the lba, then we've wrapped around and the block
8731 	 * range is invalid anyway.
8732 	 */
8733 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8734 	 || ((lba + num_blocks) < lba)) {
8735 		ctl_set_lba_out_of_range(ctsio,
8736 		    MAX(lba, lun->be_lun->maxlba + 1));
8737 		ctl_done((union ctl_io *)ctsio);
8738 		return (CTL_RETVAL_COMPLETE);
8739 	}
8740 
8741 	/*
8742 	 * According to SBC-3, a transfer length of 0 is not an error.
8743 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8744 	 * translates to 256 blocks for those commands.
8745 	 */
8746 	if (num_blocks == 0) {
8747 		ctl_set_success(ctsio);
8748 		ctl_done((union ctl_io *)ctsio);
8749 		return (CTL_RETVAL_COMPLETE);
8750 	}
8751 
8752 	/* Set FUA and/or DPO if caches are disabled. */
8753 	if (isread) {
8754 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8755 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8756 	} else {
8757 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8758 			flags |= CTL_LLF_FUA;
8759 	}
8760 
8761 	lbalen = (struct ctl_lba_len_flags *)
8762 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8763 	lbalen->lba = lba;
8764 	lbalen->len = num_blocks;
8765 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8766 
8767 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8768 	ctsio->kern_rel_offset = 0;
8769 
8770 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8771 
8772 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8773 	return (retval);
8774 }
8775 
8776 static int
8777 ctl_cnw_cont(union ctl_io *io)
8778 {
8779 	struct ctl_lun *lun = CTL_LUN(io);
8780 	struct ctl_scsiio *ctsio;
8781 	struct ctl_lba_len_flags *lbalen;
8782 	int retval;
8783 
8784 	ctsio = &io->scsiio;
8785 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8786 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8787 	lbalen = (struct ctl_lba_len_flags *)
8788 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8789 	lbalen->flags &= ~CTL_LLF_COMPARE;
8790 	lbalen->flags |= CTL_LLF_WRITE;
8791 
8792 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8793 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8794 	return (retval);
8795 }
8796 
8797 int
8798 ctl_cnw(struct ctl_scsiio *ctsio)
8799 {
8800 	struct ctl_lun *lun = CTL_LUN(ctsio);
8801 	struct ctl_lba_len_flags *lbalen;
8802 	uint64_t lba;
8803 	uint32_t num_blocks;
8804 	int flags, retval;
8805 
8806 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8807 
8808 	flags = 0;
8809 	switch (ctsio->cdb[0]) {
8810 	case COMPARE_AND_WRITE: {
8811 		struct scsi_compare_and_write *cdb;
8812 
8813 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8814 		if (cdb->byte2 & SRW10_FUA)
8815 			flags |= CTL_LLF_FUA;
8816 		if (cdb->byte2 & SRW10_DPO)
8817 			flags |= CTL_LLF_DPO;
8818 		lba = scsi_8btou64(cdb->addr);
8819 		num_blocks = cdb->length;
8820 		break;
8821 	}
8822 	default:
8823 		/*
8824 		 * We got a command we don't support.  This shouldn't
8825 		 * happen, commands should be filtered out above us.
8826 		 */
8827 		ctl_set_invalid_opcode(ctsio);
8828 		ctl_done((union ctl_io *)ctsio);
8829 
8830 		return (CTL_RETVAL_COMPLETE);
8831 		break; /* NOTREACHED */
8832 	}
8833 
8834 	/*
8835 	 * The first check is to make sure we're in bounds, the second
8836 	 * check is to catch wrap-around problems.  If the lba + num blocks
8837 	 * is less than the lba, then we've wrapped around and the block
8838 	 * range is invalid anyway.
8839 	 */
8840 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8841 	 || ((lba + num_blocks) < lba)) {
8842 		ctl_set_lba_out_of_range(ctsio,
8843 		    MAX(lba, lun->be_lun->maxlba + 1));
8844 		ctl_done((union ctl_io *)ctsio);
8845 		return (CTL_RETVAL_COMPLETE);
8846 	}
8847 
8848 	/*
8849 	 * According to SBC-3, a transfer length of 0 is not an error.
8850 	 */
8851 	if (num_blocks == 0) {
8852 		ctl_set_success(ctsio);
8853 		ctl_done((union ctl_io *)ctsio);
8854 		return (CTL_RETVAL_COMPLETE);
8855 	}
8856 
8857 	/* Set FUA if write cache is disabled. */
8858 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8859 		flags |= CTL_LLF_FUA;
8860 
8861 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8862 	ctsio->kern_rel_offset = 0;
8863 
8864 	/*
8865 	 * Set the IO_CONT flag, so that if this I/O gets passed to
8866 	 * ctl_data_submit_done(), it'll get passed back to
8867 	 * ctl_ctl_cnw_cont() for further processing.
8868 	 */
8869 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8870 	ctsio->io_cont = ctl_cnw_cont;
8871 
8872 	lbalen = (struct ctl_lba_len_flags *)
8873 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8874 	lbalen->lba = lba;
8875 	lbalen->len = num_blocks;
8876 	lbalen->flags = CTL_LLF_COMPARE | flags;
8877 
8878 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8879 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8880 	return (retval);
8881 }
8882 
8883 int
8884 ctl_verify(struct ctl_scsiio *ctsio)
8885 {
8886 	struct ctl_lun *lun = CTL_LUN(ctsio);
8887 	struct ctl_lba_len_flags *lbalen;
8888 	uint64_t lba;
8889 	uint32_t num_blocks;
8890 	int bytchk, flags;
8891 	int retval;
8892 
8893 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8894 
8895 	bytchk = 0;
8896 	flags = CTL_LLF_FUA;
8897 	switch (ctsio->cdb[0]) {
8898 	case VERIFY_10: {
8899 		struct scsi_verify_10 *cdb;
8900 
8901 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8902 		if (cdb->byte2 & SVFY_BYTCHK)
8903 			bytchk = 1;
8904 		if (cdb->byte2 & SVFY_DPO)
8905 			flags |= CTL_LLF_DPO;
8906 		lba = scsi_4btoul(cdb->addr);
8907 		num_blocks = scsi_2btoul(cdb->length);
8908 		break;
8909 	}
8910 	case VERIFY_12: {
8911 		struct scsi_verify_12 *cdb;
8912 
8913 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8914 		if (cdb->byte2 & SVFY_BYTCHK)
8915 			bytchk = 1;
8916 		if (cdb->byte2 & SVFY_DPO)
8917 			flags |= CTL_LLF_DPO;
8918 		lba = scsi_4btoul(cdb->addr);
8919 		num_blocks = scsi_4btoul(cdb->length);
8920 		break;
8921 	}
8922 	case VERIFY_16: {
8923 		struct scsi_rw_16 *cdb;
8924 
8925 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8926 		if (cdb->byte2 & SVFY_BYTCHK)
8927 			bytchk = 1;
8928 		if (cdb->byte2 & SVFY_DPO)
8929 			flags |= CTL_LLF_DPO;
8930 		lba = scsi_8btou64(cdb->addr);
8931 		num_blocks = scsi_4btoul(cdb->length);
8932 		break;
8933 	}
8934 	default:
8935 		/*
8936 		 * We got a command we don't support.  This shouldn't
8937 		 * happen, commands should be filtered out above us.
8938 		 */
8939 		ctl_set_invalid_opcode(ctsio);
8940 		ctl_done((union ctl_io *)ctsio);
8941 		return (CTL_RETVAL_COMPLETE);
8942 	}
8943 
8944 	/*
8945 	 * The first check is to make sure we're in bounds, the second
8946 	 * check is to catch wrap-around problems.  If the lba + num blocks
8947 	 * is less than the lba, then we've wrapped around and the block
8948 	 * range is invalid anyway.
8949 	 */
8950 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8951 	 || ((lba + num_blocks) < lba)) {
8952 		ctl_set_lba_out_of_range(ctsio,
8953 		    MAX(lba, lun->be_lun->maxlba + 1));
8954 		ctl_done((union ctl_io *)ctsio);
8955 		return (CTL_RETVAL_COMPLETE);
8956 	}
8957 
8958 	/*
8959 	 * According to SBC-3, a transfer length of 0 is not an error.
8960 	 */
8961 	if (num_blocks == 0) {
8962 		ctl_set_success(ctsio);
8963 		ctl_done((union ctl_io *)ctsio);
8964 		return (CTL_RETVAL_COMPLETE);
8965 	}
8966 
8967 	lbalen = (struct ctl_lba_len_flags *)
8968 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8969 	lbalen->lba = lba;
8970 	lbalen->len = num_blocks;
8971 	if (bytchk) {
8972 		lbalen->flags = CTL_LLF_COMPARE | flags;
8973 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8974 	} else {
8975 		lbalen->flags = CTL_LLF_VERIFY | flags;
8976 		ctsio->kern_total_len = 0;
8977 	}
8978 	ctsio->kern_rel_offset = 0;
8979 
8980 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8981 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8982 	return (retval);
8983 }
8984 
8985 int
8986 ctl_report_luns(struct ctl_scsiio *ctsio)
8987 {
8988 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8989 	struct ctl_port *port = CTL_PORT(ctsio);
8990 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
8991 	struct scsi_report_luns *cdb;
8992 	struct scsi_report_luns_data *lun_data;
8993 	int num_filled, num_luns, num_port_luns, retval;
8994 	uint32_t alloc_len, lun_datalen;
8995 	uint32_t initidx, targ_lun_id, lun_id;
8996 
8997 	retval = CTL_RETVAL_COMPLETE;
8998 	cdb = (struct scsi_report_luns *)ctsio->cdb;
8999 
9000 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9001 
9002 	num_luns = 0;
9003 	num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
9004 	mtx_lock(&softc->ctl_lock);
9005 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9006 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9007 			num_luns++;
9008 	}
9009 	mtx_unlock(&softc->ctl_lock);
9010 
9011 	switch (cdb->select_report) {
9012 	case RPL_REPORT_DEFAULT:
9013 	case RPL_REPORT_ALL:
9014 	case RPL_REPORT_NONSUBSID:
9015 		break;
9016 	case RPL_REPORT_WELLKNOWN:
9017 	case RPL_REPORT_ADMIN:
9018 	case RPL_REPORT_CONGLOM:
9019 		num_luns = 0;
9020 		break;
9021 	default:
9022 		ctl_set_invalid_field(ctsio,
9023 				      /*sks_valid*/ 1,
9024 				      /*command*/ 1,
9025 				      /*field*/ 2,
9026 				      /*bit_valid*/ 0,
9027 				      /*bit*/ 0);
9028 		ctl_done((union ctl_io *)ctsio);
9029 		return (retval);
9030 		break; /* NOTREACHED */
9031 	}
9032 
9033 	alloc_len = scsi_4btoul(cdb->length);
9034 	/*
9035 	 * The initiator has to allocate at least 16 bytes for this request,
9036 	 * so he can at least get the header and the first LUN.  Otherwise
9037 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9038 	 */
9039 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9040 	    sizeof(struct scsi_report_luns_lundata))) {
9041 		ctl_set_invalid_field(ctsio,
9042 				      /*sks_valid*/ 1,
9043 				      /*command*/ 1,
9044 				      /*field*/ 6,
9045 				      /*bit_valid*/ 0,
9046 				      /*bit*/ 0);
9047 		ctl_done((union ctl_io *)ctsio);
9048 		return (retval);
9049 	}
9050 
9051 	lun_datalen = sizeof(*lun_data) +
9052 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9053 
9054 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9055 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9056 	ctsio->kern_sg_entries = 0;
9057 
9058 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9059 
9060 	mtx_lock(&softc->ctl_lock);
9061 	for (targ_lun_id = 0, num_filled = 0;
9062 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9063 	    targ_lun_id++) {
9064 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9065 		if (lun_id == UINT32_MAX)
9066 			continue;
9067 		lun = softc->ctl_luns[lun_id];
9068 		if (lun == NULL)
9069 			continue;
9070 
9071 		be64enc(lun_data->luns[num_filled++].lundata,
9072 		    ctl_encode_lun(targ_lun_id));
9073 
9074 		/*
9075 		 * According to SPC-3, rev 14 section 6.21:
9076 		 *
9077 		 * "The execution of a REPORT LUNS command to any valid and
9078 		 * installed logical unit shall clear the REPORTED LUNS DATA
9079 		 * HAS CHANGED unit attention condition for all logical
9080 		 * units of that target with respect to the requesting
9081 		 * initiator. A valid and installed logical unit is one
9082 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9083 		 * INQUIRY data (see 6.4.2)."
9084 		 *
9085 		 * If request_lun is NULL, the LUN this report luns command
9086 		 * was issued to is either disabled or doesn't exist. In that
9087 		 * case, we shouldn't clear any pending lun change unit
9088 		 * attention.
9089 		 */
9090 		if (request_lun != NULL) {
9091 			mtx_lock(&lun->lun_lock);
9092 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9093 			mtx_unlock(&lun->lun_lock);
9094 		}
9095 	}
9096 	mtx_unlock(&softc->ctl_lock);
9097 
9098 	/*
9099 	 * It's quite possible that we've returned fewer LUNs than we allocated
9100 	 * space for.  Trim it.
9101 	 */
9102 	lun_datalen = sizeof(*lun_data) +
9103 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9104 	ctsio->kern_rel_offset = 0;
9105 	ctsio->kern_sg_entries = 0;
9106 	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9107 	ctsio->kern_total_len = ctsio->kern_data_len;
9108 
9109 	/*
9110 	 * We set this to the actual data length, regardless of how much
9111 	 * space we actually have to return results.  If the user looks at
9112 	 * this value, he'll know whether or not he allocated enough space
9113 	 * and reissue the command if necessary.  We don't support well
9114 	 * known logical units, so if the user asks for that, return none.
9115 	 */
9116 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9117 
9118 	/*
9119 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9120 	 * this request.
9121 	 */
9122 	ctl_set_success(ctsio);
9123 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9124 	ctsio->be_move_done = ctl_config_move_done;
9125 	ctl_datamove((union ctl_io *)ctsio);
9126 	return (retval);
9127 }
9128 
9129 int
9130 ctl_request_sense(struct ctl_scsiio *ctsio)
9131 {
9132 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9133 	struct ctl_lun *lun = CTL_LUN(ctsio);
9134 	struct scsi_request_sense *cdb;
9135 	struct scsi_sense_data *sense_ptr, *ps;
9136 	uint32_t initidx;
9137 	int have_error;
9138 	u_int sense_len = SSD_FULL_SIZE;
9139 	scsi_sense_data_type sense_format;
9140 	ctl_ua_type ua_type;
9141 	uint8_t asc = 0, ascq = 0;
9142 
9143 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9144 
9145 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9146 
9147 	/*
9148 	 * Determine which sense format the user wants.
9149 	 */
9150 	if (cdb->byte2 & SRS_DESC)
9151 		sense_format = SSD_TYPE_DESC;
9152 	else
9153 		sense_format = SSD_TYPE_FIXED;
9154 
9155 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9156 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9157 	ctsio->kern_sg_entries = 0;
9158 	ctsio->kern_rel_offset = 0;
9159 
9160 	/*
9161 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9162 	 * larger than the largest allowed value for the length field in the
9163 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9164 	 */
9165 	ctsio->kern_data_len = cdb->length;
9166 	ctsio->kern_total_len = cdb->length;
9167 
9168 	/*
9169 	 * If we don't have a LUN, we don't have any pending sense.
9170 	 */
9171 	if (lun == NULL ||
9172 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9173 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9174 		/* "Logical unit not supported" */
9175 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9176 		    /*current_error*/ 1,
9177 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9178 		    /*asc*/ 0x25,
9179 		    /*ascq*/ 0x00,
9180 		    SSD_ELEM_NONE);
9181 		goto send;
9182 	}
9183 
9184 	have_error = 0;
9185 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9186 	/*
9187 	 * Check for pending sense, and then for pending unit attentions.
9188 	 * Pending sense gets returned first, then pending unit attentions.
9189 	 */
9190 	mtx_lock(&lun->lun_lock);
9191 	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9192 	if (ps != NULL)
9193 		ps += initidx % CTL_MAX_INIT_PER_PORT;
9194 	if (ps != NULL && ps->error_code != 0) {
9195 		scsi_sense_data_type stored_format;
9196 
9197 		/*
9198 		 * Check to see which sense format was used for the stored
9199 		 * sense data.
9200 		 */
9201 		stored_format = scsi_sense_type(ps);
9202 
9203 		/*
9204 		 * If the user requested a different sense format than the
9205 		 * one we stored, then we need to convert it to the other
9206 		 * format.  If we're going from descriptor to fixed format
9207 		 * sense data, we may lose things in translation, depending
9208 		 * on what options were used.
9209 		 *
9210 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9211 		 * for some reason we'll just copy it out as-is.
9212 		 */
9213 		if ((stored_format == SSD_TYPE_FIXED)
9214 		 && (sense_format == SSD_TYPE_DESC))
9215 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9216 			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9217 		else if ((stored_format == SSD_TYPE_DESC)
9218 		      && (sense_format == SSD_TYPE_FIXED))
9219 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9220 			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9221 		else
9222 			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9223 
9224 		ps->error_code = 0;
9225 		have_error = 1;
9226 	} else {
9227 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9228 		    sense_format);
9229 		if (ua_type != CTL_UA_NONE)
9230 			have_error = 1;
9231 	}
9232 	if (have_error == 0) {
9233 		/*
9234 		 * Report informational exception if have one and allowed.
9235 		 */
9236 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9237 			asc = lun->ie_asc;
9238 			ascq = lun->ie_ascq;
9239 		}
9240 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9241 		    /*current_error*/ 1,
9242 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9243 		    /*asc*/ asc,
9244 		    /*ascq*/ ascq,
9245 		    SSD_ELEM_NONE);
9246 	}
9247 	mtx_unlock(&lun->lun_lock);
9248 
9249 send:
9250 	/*
9251 	 * We report the SCSI status as OK, since the status of the command
9252 	 * itself is OK.  We're reporting sense as parameter data.
9253 	 */
9254 	ctl_set_success(ctsio);
9255 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9256 	ctsio->be_move_done = ctl_config_move_done;
9257 	ctl_datamove((union ctl_io *)ctsio);
9258 	return (CTL_RETVAL_COMPLETE);
9259 }
9260 
9261 int
9262 ctl_tur(struct ctl_scsiio *ctsio)
9263 {
9264 
9265 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9266 
9267 	ctl_set_success(ctsio);
9268 	ctl_done((union ctl_io *)ctsio);
9269 
9270 	return (CTL_RETVAL_COMPLETE);
9271 }
9272 
9273 /*
9274  * SCSI VPD page 0x00, the Supported VPD Pages page.
9275  */
9276 static int
9277 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9278 {
9279 	struct ctl_lun *lun = CTL_LUN(ctsio);
9280 	struct scsi_vpd_supported_pages *pages;
9281 	int sup_page_size;
9282 	int p;
9283 
9284 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9285 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9286 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9287 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9288 	ctsio->kern_rel_offset = 0;
9289 	ctsio->kern_sg_entries = 0;
9290 	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9291 	ctsio->kern_total_len = ctsio->kern_data_len;
9292 
9293 	/*
9294 	 * The control device is always connected.  The disk device, on the
9295 	 * other hand, may not be online all the time.  Need to change this
9296 	 * to figure out whether the disk device is actually online or not.
9297 	 */
9298 	if (lun != NULL)
9299 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9300 				lun->be_lun->lun_type;
9301 	else
9302 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9303 
9304 	p = 0;
9305 	/* Supported VPD pages */
9306 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9307 	/* Serial Number */
9308 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9309 	/* Device Identification */
9310 	pages->page_list[p++] = SVPD_DEVICE_ID;
9311 	/* Extended INQUIRY Data */
9312 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9313 	/* Mode Page Policy */
9314 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9315 	/* SCSI Ports */
9316 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9317 	/* Third-party Copy */
9318 	pages->page_list[p++] = SVPD_SCSI_TPC;
9319 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9320 		/* Block limits */
9321 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9322 		/* Block Device Characteristics */
9323 		pages->page_list[p++] = SVPD_BDC;
9324 		/* Logical Block Provisioning */
9325 		pages->page_list[p++] = SVPD_LBP;
9326 	}
9327 	pages->length = p;
9328 
9329 	ctl_set_success(ctsio);
9330 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9331 	ctsio->be_move_done = ctl_config_move_done;
9332 	ctl_datamove((union ctl_io *)ctsio);
9333 	return (CTL_RETVAL_COMPLETE);
9334 }
9335 
9336 /*
9337  * SCSI VPD page 0x80, the Unit Serial Number page.
9338  */
9339 static int
9340 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9341 {
9342 	struct ctl_lun *lun = CTL_LUN(ctsio);
9343 	struct scsi_vpd_unit_serial_number *sn_ptr;
9344 	int data_len;
9345 
9346 	data_len = 4 + CTL_SN_LEN;
9347 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9348 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9349 	ctsio->kern_rel_offset = 0;
9350 	ctsio->kern_sg_entries = 0;
9351 	ctsio->kern_data_len = min(data_len, alloc_len);
9352 	ctsio->kern_total_len = ctsio->kern_data_len;
9353 
9354 	/*
9355 	 * The control device is always connected.  The disk device, on the
9356 	 * other hand, may not be online all the time.  Need to change this
9357 	 * to figure out whether the disk device is actually online or not.
9358 	 */
9359 	if (lun != NULL)
9360 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9361 				  lun->be_lun->lun_type;
9362 	else
9363 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9364 
9365 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9366 	sn_ptr->length = CTL_SN_LEN;
9367 	/*
9368 	 * If we don't have a LUN, we just leave the serial number as
9369 	 * all spaces.
9370 	 */
9371 	if (lun != NULL) {
9372 		strncpy((char *)sn_ptr->serial_num,
9373 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9374 	} else
9375 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9376 
9377 	ctl_set_success(ctsio);
9378 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9379 	ctsio->be_move_done = ctl_config_move_done;
9380 	ctl_datamove((union ctl_io *)ctsio);
9381 	return (CTL_RETVAL_COMPLETE);
9382 }
9383 
9384 
9385 /*
9386  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9387  */
9388 static int
9389 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9390 {
9391 	struct ctl_lun *lun = CTL_LUN(ctsio);
9392 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9393 	int data_len;
9394 
9395 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9396 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9397 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9398 	ctsio->kern_sg_entries = 0;
9399 	ctsio->kern_rel_offset = 0;
9400 	ctsio->kern_data_len = min(data_len, alloc_len);
9401 	ctsio->kern_total_len = ctsio->kern_data_len;
9402 
9403 	/*
9404 	 * The control device is always connected.  The disk device, on the
9405 	 * other hand, may not be online all the time.
9406 	 */
9407 	if (lun != NULL)
9408 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9409 				     lun->be_lun->lun_type;
9410 	else
9411 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9412 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9413 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9414 	/*
9415 	 * We support head of queue, ordered and simple tags.
9416 	 */
9417 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9418 	/*
9419 	 * Volatile cache supported.
9420 	 */
9421 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9422 
9423 	/*
9424 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9425 	 * attention for a particular IT nexus on all LUNs once we report
9426 	 * it to that nexus once.  This bit is required as of SPC-4.
9427 	 */
9428 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9429 
9430 	/*
9431 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9432 	 */
9433 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9434 
9435 	/*
9436 	 * XXX KDM in order to correctly answer this, we would need
9437 	 * information from the SIM to determine how much sense data it
9438 	 * can send.  So this would really be a path inquiry field, most
9439 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9440 	 * but the hardware may or may not be able to support that much.
9441 	 * 0 just means that the maximum sense data length is not reported.
9442 	 */
9443 	eid_ptr->max_sense_length = 0;
9444 
9445 	ctl_set_success(ctsio);
9446 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9447 	ctsio->be_move_done = ctl_config_move_done;
9448 	ctl_datamove((union ctl_io *)ctsio);
9449 	return (CTL_RETVAL_COMPLETE);
9450 }
9451 
9452 static int
9453 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9454 {
9455 	struct ctl_lun *lun = CTL_LUN(ctsio);
9456 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9457 	int data_len;
9458 
9459 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9460 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9461 
9462 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9463 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9464 	ctsio->kern_rel_offset = 0;
9465 	ctsio->kern_sg_entries = 0;
9466 	ctsio->kern_data_len = min(data_len, alloc_len);
9467 	ctsio->kern_total_len = ctsio->kern_data_len;
9468 
9469 	/*
9470 	 * The control device is always connected.  The disk device, on the
9471 	 * other hand, may not be online all the time.
9472 	 */
9473 	if (lun != NULL)
9474 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9475 				     lun->be_lun->lun_type;
9476 	else
9477 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9478 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9479 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9480 	mpp_ptr->descr[0].page_code = 0x3f;
9481 	mpp_ptr->descr[0].subpage_code = 0xff;
9482 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9483 
9484 	ctl_set_success(ctsio);
9485 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9486 	ctsio->be_move_done = ctl_config_move_done;
9487 	ctl_datamove((union ctl_io *)ctsio);
9488 	return (CTL_RETVAL_COMPLETE);
9489 }
9490 
9491 /*
9492  * SCSI VPD page 0x83, the Device Identification page.
9493  */
9494 static int
9495 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9496 {
9497 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9498 	struct ctl_port *port = CTL_PORT(ctsio);
9499 	struct ctl_lun *lun = CTL_LUN(ctsio);
9500 	struct scsi_vpd_device_id *devid_ptr;
9501 	struct scsi_vpd_id_descriptor *desc;
9502 	int data_len, g;
9503 	uint8_t proto;
9504 
9505 	data_len = sizeof(struct scsi_vpd_device_id) +
9506 	    sizeof(struct scsi_vpd_id_descriptor) +
9507 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9508 	    sizeof(struct scsi_vpd_id_descriptor) +
9509 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9510 	if (lun && lun->lun_devid)
9511 		data_len += lun->lun_devid->len;
9512 	if (port && port->port_devid)
9513 		data_len += port->port_devid->len;
9514 	if (port && port->target_devid)
9515 		data_len += port->target_devid->len;
9516 
9517 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9518 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9519 	ctsio->kern_sg_entries = 0;
9520 	ctsio->kern_rel_offset = 0;
9521 	ctsio->kern_sg_entries = 0;
9522 	ctsio->kern_data_len = min(data_len, alloc_len);
9523 	ctsio->kern_total_len = ctsio->kern_data_len;
9524 
9525 	/*
9526 	 * The control device is always connected.  The disk device, on the
9527 	 * other hand, may not be online all the time.
9528 	 */
9529 	if (lun != NULL)
9530 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9531 				     lun->be_lun->lun_type;
9532 	else
9533 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9534 	devid_ptr->page_code = SVPD_DEVICE_ID;
9535 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9536 
9537 	if (port && port->port_type == CTL_PORT_FC)
9538 		proto = SCSI_PROTO_FC << 4;
9539 	else if (port && port->port_type == CTL_PORT_SAS)
9540 		proto = SCSI_PROTO_SAS << 4;
9541 	else if (port && port->port_type == CTL_PORT_ISCSI)
9542 		proto = SCSI_PROTO_ISCSI << 4;
9543 	else
9544 		proto = SCSI_PROTO_SPI << 4;
9545 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9546 
9547 	/*
9548 	 * We're using a LUN association here.  i.e., this device ID is a
9549 	 * per-LUN identifier.
9550 	 */
9551 	if (lun && lun->lun_devid) {
9552 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9553 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9554 		    lun->lun_devid->len);
9555 	}
9556 
9557 	/*
9558 	 * This is for the WWPN which is a port association.
9559 	 */
9560 	if (port && port->port_devid) {
9561 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9562 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9563 		    port->port_devid->len);
9564 	}
9565 
9566 	/*
9567 	 * This is for the Relative Target Port(type 4h) identifier
9568 	 */
9569 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9570 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9571 	    SVPD_ID_TYPE_RELTARG;
9572 	desc->length = 4;
9573 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9574 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9575 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9576 
9577 	/*
9578 	 * This is for the Target Port Group(type 5h) identifier
9579 	 */
9580 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9581 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9582 	    SVPD_ID_TYPE_TPORTGRP;
9583 	desc->length = 4;
9584 	if (softc->is_single ||
9585 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9586 		g = 1;
9587 	else
9588 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9589 	scsi_ulto2b(g, &desc->identifier[2]);
9590 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9591 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9592 
9593 	/*
9594 	 * This is for the Target identifier
9595 	 */
9596 	if (port && port->target_devid) {
9597 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9598 	}
9599 
9600 	ctl_set_success(ctsio);
9601 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9602 	ctsio->be_move_done = ctl_config_move_done;
9603 	ctl_datamove((union ctl_io *)ctsio);
9604 	return (CTL_RETVAL_COMPLETE);
9605 }
9606 
9607 static int
9608 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9609 {
9610 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9611 	struct ctl_lun *lun = CTL_LUN(ctsio);
9612 	struct scsi_vpd_scsi_ports *sp;
9613 	struct scsi_vpd_port_designation *pd;
9614 	struct scsi_vpd_port_designation_cont *pdc;
9615 	struct ctl_port *port;
9616 	int data_len, num_target_ports, iid_len, id_len;
9617 
9618 	num_target_ports = 0;
9619 	iid_len = 0;
9620 	id_len = 0;
9621 	mtx_lock(&softc->ctl_lock);
9622 	STAILQ_FOREACH(port, &softc->port_list, links) {
9623 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9624 			continue;
9625 		if (lun != NULL &&
9626 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9627 			continue;
9628 		num_target_ports++;
9629 		if (port->init_devid)
9630 			iid_len += port->init_devid->len;
9631 		if (port->port_devid)
9632 			id_len += port->port_devid->len;
9633 	}
9634 	mtx_unlock(&softc->ctl_lock);
9635 
9636 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9637 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9638 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9639 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9640 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9641 	ctsio->kern_sg_entries = 0;
9642 	ctsio->kern_rel_offset = 0;
9643 	ctsio->kern_sg_entries = 0;
9644 	ctsio->kern_data_len = min(data_len, alloc_len);
9645 	ctsio->kern_total_len = ctsio->kern_data_len;
9646 
9647 	/*
9648 	 * The control device is always connected.  The disk device, on the
9649 	 * other hand, may not be online all the time.  Need to change this
9650 	 * to figure out whether the disk device is actually online or not.
9651 	 */
9652 	if (lun != NULL)
9653 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9654 				  lun->be_lun->lun_type;
9655 	else
9656 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9657 
9658 	sp->page_code = SVPD_SCSI_PORTS;
9659 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9660 	    sp->page_length);
9661 	pd = &sp->design[0];
9662 
9663 	mtx_lock(&softc->ctl_lock);
9664 	STAILQ_FOREACH(port, &softc->port_list, links) {
9665 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9666 			continue;
9667 		if (lun != NULL &&
9668 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9669 			continue;
9670 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9671 		if (port->init_devid) {
9672 			iid_len = port->init_devid->len;
9673 			memcpy(pd->initiator_transportid,
9674 			    port->init_devid->data, port->init_devid->len);
9675 		} else
9676 			iid_len = 0;
9677 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9678 		pdc = (struct scsi_vpd_port_designation_cont *)
9679 		    (&pd->initiator_transportid[iid_len]);
9680 		if (port->port_devid) {
9681 			id_len = port->port_devid->len;
9682 			memcpy(pdc->target_port_descriptors,
9683 			    port->port_devid->data, port->port_devid->len);
9684 		} else
9685 			id_len = 0;
9686 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9687 		pd = (struct scsi_vpd_port_designation *)
9688 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9689 	}
9690 	mtx_unlock(&softc->ctl_lock);
9691 
9692 	ctl_set_success(ctsio);
9693 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9694 	ctsio->be_move_done = ctl_config_move_done;
9695 	ctl_datamove((union ctl_io *)ctsio);
9696 	return (CTL_RETVAL_COMPLETE);
9697 }
9698 
9699 static int
9700 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9701 {
9702 	struct ctl_lun *lun = CTL_LUN(ctsio);
9703 	struct scsi_vpd_block_limits *bl_ptr;
9704 	const char *val;
9705 	uint64_t ival;
9706 
9707 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9708 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9709 	ctsio->kern_sg_entries = 0;
9710 	ctsio->kern_rel_offset = 0;
9711 	ctsio->kern_sg_entries = 0;
9712 	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9713 	ctsio->kern_total_len = ctsio->kern_data_len;
9714 
9715 	/*
9716 	 * The control device is always connected.  The disk device, on the
9717 	 * other hand, may not be online all the time.  Need to change this
9718 	 * to figure out whether the disk device is actually online or not.
9719 	 */
9720 	if (lun != NULL)
9721 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9722 				  lun->be_lun->lun_type;
9723 	else
9724 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9725 
9726 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9727 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9728 	bl_ptr->max_cmp_write_len = 0xff;
9729 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9730 	if (lun != NULL) {
9731 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9732 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9733 			ival = 0xffffffff;
9734 			val = dnvlist_get_string(lun->be_lun->options,
9735 			    "unmap_max_lba", NULL);
9736 			if (val != NULL)
9737 				ctl_expand_number(val, &ival);
9738 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9739 			ival = 0xffffffff;
9740 			val = dnvlist_get_string(lun->be_lun->options,
9741 			    "unmap_max_descr", NULL);
9742 			if (val != NULL)
9743 				ctl_expand_number(val, &ival);
9744 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9745 			if (lun->be_lun->ublockexp != 0) {
9746 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9747 				    bl_ptr->opt_unmap_grain);
9748 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9749 				    bl_ptr->unmap_grain_align);
9750 			}
9751 		}
9752 		scsi_ulto4b(lun->be_lun->atomicblock,
9753 		    bl_ptr->max_atomic_transfer_length);
9754 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9755 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9756 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9757 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9758 		ival = UINT64_MAX;
9759 		val = dnvlist_get_string(lun->be_lun->options,
9760 		    "write_same_max_lba", NULL);
9761 		if (val != NULL)
9762 			ctl_expand_number(val, &ival);
9763 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9764 	}
9765 
9766 	ctl_set_success(ctsio);
9767 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9768 	ctsio->be_move_done = ctl_config_move_done;
9769 	ctl_datamove((union ctl_io *)ctsio);
9770 	return (CTL_RETVAL_COMPLETE);
9771 }
9772 
9773 static int
9774 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9775 {
9776 	struct ctl_lun *lun = CTL_LUN(ctsio);
9777 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9778 	const char *value;
9779 	u_int i;
9780 
9781 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9782 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9783 	ctsio->kern_sg_entries = 0;
9784 	ctsio->kern_rel_offset = 0;
9785 	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
9786 	ctsio->kern_total_len = ctsio->kern_data_len;
9787 
9788 	/*
9789 	 * The control device is always connected.  The disk device, on the
9790 	 * other hand, may not be online all the time.  Need to change this
9791 	 * to figure out whether the disk device is actually online or not.
9792 	 */
9793 	if (lun != NULL)
9794 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9795 				  lun->be_lun->lun_type;
9796 	else
9797 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9798 	bdc_ptr->page_code = SVPD_BDC;
9799 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9800 	if (lun != NULL &&
9801 	    (value = dnvlist_get_string(lun->be_lun->options, "rpm", NULL)) != NULL)
9802 		i = strtol(value, NULL, 0);
9803 	else
9804 		i = CTL_DEFAULT_ROTATION_RATE;
9805 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9806 	if (lun != NULL &&
9807 	    (value = dnvlist_get_string(lun->be_lun->options, "formfactor", NULL)) != NULL)
9808 		i = strtol(value, NULL, 0);
9809 	else
9810 		i = 0;
9811 	bdc_ptr->wab_wac_ff = (i & 0x0f);
9812 	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9813 
9814 	ctl_set_success(ctsio);
9815 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9816 	ctsio->be_move_done = ctl_config_move_done;
9817 	ctl_datamove((union ctl_io *)ctsio);
9818 	return (CTL_RETVAL_COMPLETE);
9819 }
9820 
9821 static int
9822 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9823 {
9824 	struct ctl_lun *lun = CTL_LUN(ctsio);
9825 	struct scsi_vpd_logical_block_prov *lbp_ptr;
9826 	const char *value;
9827 
9828 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9829 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9830 	ctsio->kern_sg_entries = 0;
9831 	ctsio->kern_rel_offset = 0;
9832 	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
9833 	ctsio->kern_total_len = ctsio->kern_data_len;
9834 
9835 	/*
9836 	 * The control device is always connected.  The disk device, on the
9837 	 * other hand, may not be online all the time.  Need to change this
9838 	 * to figure out whether the disk device is actually online or not.
9839 	 */
9840 	if (lun != NULL)
9841 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9842 				  lun->be_lun->lun_type;
9843 	else
9844 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9845 
9846 	lbp_ptr->page_code = SVPD_LBP;
9847 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9848 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9849 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9850 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9851 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9852 		value = dnvlist_get_string(lun->be_lun->options,
9853 		    "provisioning_type", NULL);
9854 		if (value != NULL) {
9855 			if (strcmp(value, "resource") == 0)
9856 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
9857 			else if (strcmp(value, "thin") == 0)
9858 				lbp_ptr->prov_type = SVPD_LBP_THIN;
9859 		} else
9860 			lbp_ptr->prov_type = SVPD_LBP_THIN;
9861 	}
9862 
9863 	ctl_set_success(ctsio);
9864 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9865 	ctsio->be_move_done = ctl_config_move_done;
9866 	ctl_datamove((union ctl_io *)ctsio);
9867 	return (CTL_RETVAL_COMPLETE);
9868 }
9869 
9870 /*
9871  * INQUIRY with the EVPD bit set.
9872  */
9873 static int
9874 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9875 {
9876 	struct ctl_lun *lun = CTL_LUN(ctsio);
9877 	struct scsi_inquiry *cdb;
9878 	int alloc_len, retval;
9879 
9880 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9881 	alloc_len = scsi_2btoul(cdb->length);
9882 
9883 	switch (cdb->page_code) {
9884 	case SVPD_SUPPORTED_PAGES:
9885 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9886 		break;
9887 	case SVPD_UNIT_SERIAL_NUMBER:
9888 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9889 		break;
9890 	case SVPD_DEVICE_ID:
9891 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9892 		break;
9893 	case SVPD_EXTENDED_INQUIRY_DATA:
9894 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9895 		break;
9896 	case SVPD_MODE_PAGE_POLICY:
9897 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9898 		break;
9899 	case SVPD_SCSI_PORTS:
9900 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9901 		break;
9902 	case SVPD_SCSI_TPC:
9903 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
9904 		break;
9905 	case SVPD_BLOCK_LIMITS:
9906 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9907 			goto err;
9908 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9909 		break;
9910 	case SVPD_BDC:
9911 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9912 			goto err;
9913 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
9914 		break;
9915 	case SVPD_LBP:
9916 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9917 			goto err;
9918 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
9919 		break;
9920 	default:
9921 err:
9922 		ctl_set_invalid_field(ctsio,
9923 				      /*sks_valid*/ 1,
9924 				      /*command*/ 1,
9925 				      /*field*/ 2,
9926 				      /*bit_valid*/ 0,
9927 				      /*bit*/ 0);
9928 		ctl_done((union ctl_io *)ctsio);
9929 		retval = CTL_RETVAL_COMPLETE;
9930 		break;
9931 	}
9932 
9933 	return (retval);
9934 }
9935 
9936 /*
9937  * Standard INQUIRY data.
9938  */
9939 static int
9940 ctl_inquiry_std(struct ctl_scsiio *ctsio)
9941 {
9942 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9943 	struct ctl_port *port = CTL_PORT(ctsio);
9944 	struct ctl_lun *lun = CTL_LUN(ctsio);
9945 	struct scsi_inquiry_data *inq_ptr;
9946 	struct scsi_inquiry *cdb;
9947 	const char *val;
9948 	uint32_t alloc_len, data_len;
9949 	ctl_port_type port_type;
9950 
9951 	port_type = port->port_type;
9952 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
9953 		port_type = CTL_PORT_SCSI;
9954 
9955 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9956 	alloc_len = scsi_2btoul(cdb->length);
9957 
9958 	/*
9959 	 * We malloc the full inquiry data size here and fill it
9960 	 * in.  If the user only asks for less, we'll give him
9961 	 * that much.
9962 	 */
9963 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
9964 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9965 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
9966 	ctsio->kern_sg_entries = 0;
9967 	ctsio->kern_rel_offset = 0;
9968 	ctsio->kern_data_len = min(data_len, alloc_len);
9969 	ctsio->kern_total_len = ctsio->kern_data_len;
9970 
9971 	if (lun != NULL) {
9972 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
9973 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
9974 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9975 			    lun->be_lun->lun_type;
9976 		} else {
9977 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
9978 			    lun->be_lun->lun_type;
9979 		}
9980 		if (lun->flags & CTL_LUN_REMOVABLE)
9981 			inq_ptr->dev_qual2 |= SID_RMB;
9982 	} else
9983 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
9984 
9985 	/* RMB in byte 2 is 0 */
9986 	inq_ptr->version = SCSI_REV_SPC5;
9987 
9988 	/*
9989 	 * According to SAM-3, even if a device only supports a single
9990 	 * level of LUN addressing, it should still set the HISUP bit:
9991 	 *
9992 	 * 4.9.1 Logical unit numbers overview
9993 	 *
9994 	 * All logical unit number formats described in this standard are
9995 	 * hierarchical in structure even when only a single level in that
9996 	 * hierarchy is used. The HISUP bit shall be set to one in the
9997 	 * standard INQUIRY data (see SPC-2) when any logical unit number
9998 	 * format described in this standard is used.  Non-hierarchical
9999 	 * formats are outside the scope of this standard.
10000 	 *
10001 	 * Therefore we set the HiSup bit here.
10002 	 *
10003 	 * The response format is 2, per SPC-3.
10004 	 */
10005 	inq_ptr->response_format = SID_HiSup | 2;
10006 
10007 	inq_ptr->additional_length = data_len -
10008 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10009 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10010 			 inq_ptr->additional_length));
10011 
10012 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10013 	if (port_type == CTL_PORT_SCSI)
10014 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10015 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10016 	inq_ptr->flags = SID_CmdQue;
10017 	if (port_type == CTL_PORT_SCSI)
10018 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10019 
10020 	/*
10021 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10022 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10023 	 * name and 4 bytes for the revision.
10024 	 */
10025 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10026 	    "vendor", NULL)) == NULL) {
10027 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10028 	} else {
10029 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10030 		strncpy(inq_ptr->vendor, val,
10031 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10032 	}
10033 	if (lun == NULL) {
10034 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10035 		    sizeof(inq_ptr->product));
10036 	} else if ((val = dnvlist_get_string(lun->be_lun->options, "product",
10037 	    NULL)) == NULL) {
10038 		switch (lun->be_lun->lun_type) {
10039 		case T_DIRECT:
10040 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10041 			    sizeof(inq_ptr->product));
10042 			break;
10043 		case T_PROCESSOR:
10044 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10045 			    sizeof(inq_ptr->product));
10046 			break;
10047 		case T_CDROM:
10048 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10049 			    sizeof(inq_ptr->product));
10050 			break;
10051 		default:
10052 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10053 			    sizeof(inq_ptr->product));
10054 			break;
10055 		}
10056 	} else {
10057 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10058 		strncpy(inq_ptr->product, val,
10059 		    min(sizeof(inq_ptr->product), strlen(val)));
10060 	}
10061 
10062 	/*
10063 	 * XXX make this a macro somewhere so it automatically gets
10064 	 * incremented when we make changes.
10065 	 */
10066 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10067 	    "revision", NULL)) == NULL) {
10068 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10069 	} else {
10070 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10071 		strncpy(inq_ptr->revision, val,
10072 		    min(sizeof(inq_ptr->revision), strlen(val)));
10073 	}
10074 
10075 	/*
10076 	 * For parallel SCSI, we support double transition and single
10077 	 * transition clocking.  We also support QAS (Quick Arbitration
10078 	 * and Selection) and Information Unit transfers on both the
10079 	 * control and array devices.
10080 	 */
10081 	if (port_type == CTL_PORT_SCSI)
10082 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10083 				    SID_SPI_IUS;
10084 
10085 	/* SAM-6 (no version claimed) */
10086 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10087 	/* SPC-5 (no version claimed) */
10088 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10089 	if (port_type == CTL_PORT_FC) {
10090 		/* FCP-2 ANSI INCITS.350:2003 */
10091 		scsi_ulto2b(0x0917, inq_ptr->version3);
10092 	} else if (port_type == CTL_PORT_SCSI) {
10093 		/* SPI-4 ANSI INCITS.362:200x */
10094 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10095 	} else if (port_type == CTL_PORT_ISCSI) {
10096 		/* iSCSI (no version claimed) */
10097 		scsi_ulto2b(0x0960, inq_ptr->version3);
10098 	} else if (port_type == CTL_PORT_SAS) {
10099 		/* SAS (no version claimed) */
10100 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10101 	} else if (port_type == CTL_PORT_UMASS) {
10102 		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10103 		scsi_ulto2b(0x1730, inq_ptr->version3);
10104 	}
10105 
10106 	if (lun == NULL) {
10107 		/* SBC-4 (no version claimed) */
10108 		scsi_ulto2b(0x0600, inq_ptr->version4);
10109 	} else {
10110 		switch (lun->be_lun->lun_type) {
10111 		case T_DIRECT:
10112 			/* SBC-4 (no version claimed) */
10113 			scsi_ulto2b(0x0600, inq_ptr->version4);
10114 			break;
10115 		case T_PROCESSOR:
10116 			break;
10117 		case T_CDROM:
10118 			/* MMC-6 (no version claimed) */
10119 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10120 			break;
10121 		default:
10122 			break;
10123 		}
10124 	}
10125 
10126 	ctl_set_success(ctsio);
10127 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10128 	ctsio->be_move_done = ctl_config_move_done;
10129 	ctl_datamove((union ctl_io *)ctsio);
10130 	return (CTL_RETVAL_COMPLETE);
10131 }
10132 
10133 int
10134 ctl_inquiry(struct ctl_scsiio *ctsio)
10135 {
10136 	struct scsi_inquiry *cdb;
10137 	int retval;
10138 
10139 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10140 
10141 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10142 	if (cdb->byte2 & SI_EVPD)
10143 		retval = ctl_inquiry_evpd(ctsio);
10144 	else if (cdb->page_code == 0)
10145 		retval = ctl_inquiry_std(ctsio);
10146 	else {
10147 		ctl_set_invalid_field(ctsio,
10148 				      /*sks_valid*/ 1,
10149 				      /*command*/ 1,
10150 				      /*field*/ 2,
10151 				      /*bit_valid*/ 0,
10152 				      /*bit*/ 0);
10153 		ctl_done((union ctl_io *)ctsio);
10154 		return (CTL_RETVAL_COMPLETE);
10155 	}
10156 
10157 	return (retval);
10158 }
10159 
10160 int
10161 ctl_get_config(struct ctl_scsiio *ctsio)
10162 {
10163 	struct ctl_lun *lun = CTL_LUN(ctsio);
10164 	struct scsi_get_config_header *hdr;
10165 	struct scsi_get_config_feature *feature;
10166 	struct scsi_get_config *cdb;
10167 	uint32_t alloc_len, data_len;
10168 	int rt, starting;
10169 
10170 	cdb = (struct scsi_get_config *)ctsio->cdb;
10171 	rt = (cdb->rt & SGC_RT_MASK);
10172 	starting = scsi_2btoul(cdb->starting_feature);
10173 	alloc_len = scsi_2btoul(cdb->length);
10174 
10175 	data_len = sizeof(struct scsi_get_config_header) +
10176 	    sizeof(struct scsi_get_config_feature) + 8 +
10177 	    sizeof(struct scsi_get_config_feature) + 8 +
10178 	    sizeof(struct scsi_get_config_feature) + 4 +
10179 	    sizeof(struct scsi_get_config_feature) + 4 +
10180 	    sizeof(struct scsi_get_config_feature) + 8 +
10181 	    sizeof(struct scsi_get_config_feature) +
10182 	    sizeof(struct scsi_get_config_feature) + 4 +
10183 	    sizeof(struct scsi_get_config_feature) + 4 +
10184 	    sizeof(struct scsi_get_config_feature) + 4 +
10185 	    sizeof(struct scsi_get_config_feature) + 4 +
10186 	    sizeof(struct scsi_get_config_feature) + 4 +
10187 	    sizeof(struct scsi_get_config_feature) + 4;
10188 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10189 	ctsio->kern_sg_entries = 0;
10190 	ctsio->kern_rel_offset = 0;
10191 
10192 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10193 	if (lun->flags & CTL_LUN_NO_MEDIA)
10194 		scsi_ulto2b(0x0000, hdr->current_profile);
10195 	else
10196 		scsi_ulto2b(0x0010, hdr->current_profile);
10197 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10198 
10199 	if (starting > 0x003b)
10200 		goto done;
10201 	if (starting > 0x003a)
10202 		goto f3b;
10203 	if (starting > 0x002b)
10204 		goto f3a;
10205 	if (starting > 0x002a)
10206 		goto f2b;
10207 	if (starting > 0x001f)
10208 		goto f2a;
10209 	if (starting > 0x001e)
10210 		goto f1f;
10211 	if (starting > 0x001d)
10212 		goto f1e;
10213 	if (starting > 0x0010)
10214 		goto f1d;
10215 	if (starting > 0x0003)
10216 		goto f10;
10217 	if (starting > 0x0002)
10218 		goto f3;
10219 	if (starting > 0x0001)
10220 		goto f2;
10221 	if (starting > 0x0000)
10222 		goto f1;
10223 
10224 	/* Profile List */
10225 	scsi_ulto2b(0x0000, feature->feature_code);
10226 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10227 	feature->add_length = 8;
10228 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10229 	feature->feature_data[2] = 0x00;
10230 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10231 	feature->feature_data[6] = 0x01;
10232 	feature = (struct scsi_get_config_feature *)
10233 	    &feature->feature_data[feature->add_length];
10234 
10235 f1:	/* Core */
10236 	scsi_ulto2b(0x0001, feature->feature_code);
10237 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10238 	feature->add_length = 8;
10239 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10240 	feature->feature_data[4] = 0x03;
10241 	feature = (struct scsi_get_config_feature *)
10242 	    &feature->feature_data[feature->add_length];
10243 
10244 f2:	/* Morphing */
10245 	scsi_ulto2b(0x0002, feature->feature_code);
10246 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10247 	feature->add_length = 4;
10248 	feature->feature_data[0] = 0x02;
10249 	feature = (struct scsi_get_config_feature *)
10250 	    &feature->feature_data[feature->add_length];
10251 
10252 f3:	/* Removable Medium */
10253 	scsi_ulto2b(0x0003, feature->feature_code);
10254 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10255 	feature->add_length = 4;
10256 	feature->feature_data[0] = 0x39;
10257 	feature = (struct scsi_get_config_feature *)
10258 	    &feature->feature_data[feature->add_length];
10259 
10260 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10261 		goto done;
10262 
10263 f10:	/* Random Read */
10264 	scsi_ulto2b(0x0010, feature->feature_code);
10265 	feature->flags = 0x00;
10266 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10267 		feature->flags |= SGC_F_CURRENT;
10268 	feature->add_length = 8;
10269 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10270 	scsi_ulto2b(1, &feature->feature_data[4]);
10271 	feature->feature_data[6] = 0x00;
10272 	feature = (struct scsi_get_config_feature *)
10273 	    &feature->feature_data[feature->add_length];
10274 
10275 f1d:	/* Multi-Read */
10276 	scsi_ulto2b(0x001D, feature->feature_code);
10277 	feature->flags = 0x00;
10278 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10279 		feature->flags |= SGC_F_CURRENT;
10280 	feature->add_length = 0;
10281 	feature = (struct scsi_get_config_feature *)
10282 	    &feature->feature_data[feature->add_length];
10283 
10284 f1e:	/* CD Read */
10285 	scsi_ulto2b(0x001E, feature->feature_code);
10286 	feature->flags = 0x00;
10287 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10288 		feature->flags |= SGC_F_CURRENT;
10289 	feature->add_length = 4;
10290 	feature->feature_data[0] = 0x00;
10291 	feature = (struct scsi_get_config_feature *)
10292 	    &feature->feature_data[feature->add_length];
10293 
10294 f1f:	/* DVD Read */
10295 	scsi_ulto2b(0x001F, feature->feature_code);
10296 	feature->flags = 0x08;
10297 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10298 		feature->flags |= SGC_F_CURRENT;
10299 	feature->add_length = 4;
10300 	feature->feature_data[0] = 0x01;
10301 	feature->feature_data[2] = 0x03;
10302 	feature = (struct scsi_get_config_feature *)
10303 	    &feature->feature_data[feature->add_length];
10304 
10305 f2a:	/* DVD+RW */
10306 	scsi_ulto2b(0x002A, feature->feature_code);
10307 	feature->flags = 0x04;
10308 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10309 		feature->flags |= SGC_F_CURRENT;
10310 	feature->add_length = 4;
10311 	feature->feature_data[0] = 0x00;
10312 	feature->feature_data[1] = 0x00;
10313 	feature = (struct scsi_get_config_feature *)
10314 	    &feature->feature_data[feature->add_length];
10315 
10316 f2b:	/* DVD+R */
10317 	scsi_ulto2b(0x002B, feature->feature_code);
10318 	feature->flags = 0x00;
10319 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10320 		feature->flags |= SGC_F_CURRENT;
10321 	feature->add_length = 4;
10322 	feature->feature_data[0] = 0x00;
10323 	feature = (struct scsi_get_config_feature *)
10324 	    &feature->feature_data[feature->add_length];
10325 
10326 f3a:	/* DVD+RW Dual Layer */
10327 	scsi_ulto2b(0x003A, feature->feature_code);
10328 	feature->flags = 0x00;
10329 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10330 		feature->flags |= SGC_F_CURRENT;
10331 	feature->add_length = 4;
10332 	feature->feature_data[0] = 0x00;
10333 	feature->feature_data[1] = 0x00;
10334 	feature = (struct scsi_get_config_feature *)
10335 	    &feature->feature_data[feature->add_length];
10336 
10337 f3b:	/* DVD+R Dual Layer */
10338 	scsi_ulto2b(0x003B, feature->feature_code);
10339 	feature->flags = 0x00;
10340 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10341 		feature->flags |= SGC_F_CURRENT;
10342 	feature->add_length = 4;
10343 	feature->feature_data[0] = 0x00;
10344 	feature = (struct scsi_get_config_feature *)
10345 	    &feature->feature_data[feature->add_length];
10346 
10347 done:
10348 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10349 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10350 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10351 		if (scsi_2btoul(feature->feature_code) == starting)
10352 			feature = (struct scsi_get_config_feature *)
10353 			    &feature->feature_data[feature->add_length];
10354 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10355 	}
10356 	scsi_ulto4b(data_len - 4, hdr->data_length);
10357 	ctsio->kern_data_len = min(data_len, alloc_len);
10358 	ctsio->kern_total_len = ctsio->kern_data_len;
10359 
10360 	ctl_set_success(ctsio);
10361 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10362 	ctsio->be_move_done = ctl_config_move_done;
10363 	ctl_datamove((union ctl_io *)ctsio);
10364 	return (CTL_RETVAL_COMPLETE);
10365 }
10366 
10367 int
10368 ctl_get_event_status(struct ctl_scsiio *ctsio)
10369 {
10370 	struct scsi_get_event_status_header *hdr;
10371 	struct scsi_get_event_status *cdb;
10372 	uint32_t alloc_len, data_len;
10373 
10374 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10375 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10376 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10377 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10378 		ctl_done((union ctl_io *)ctsio);
10379 		return (CTL_RETVAL_COMPLETE);
10380 	}
10381 	alloc_len = scsi_2btoul(cdb->length);
10382 
10383 	data_len = sizeof(struct scsi_get_event_status_header);
10384 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10385 	ctsio->kern_sg_entries = 0;
10386 	ctsio->kern_rel_offset = 0;
10387 	ctsio->kern_data_len = min(data_len, alloc_len);
10388 	ctsio->kern_total_len = ctsio->kern_data_len;
10389 
10390 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10391 	scsi_ulto2b(0, hdr->descr_length);
10392 	hdr->nea_class = SGESN_NEA;
10393 	hdr->supported_class = 0;
10394 
10395 	ctl_set_success(ctsio);
10396 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10397 	ctsio->be_move_done = ctl_config_move_done;
10398 	ctl_datamove((union ctl_io *)ctsio);
10399 	return (CTL_RETVAL_COMPLETE);
10400 }
10401 
10402 int
10403 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10404 {
10405 	struct scsi_mechanism_status_header *hdr;
10406 	struct scsi_mechanism_status *cdb;
10407 	uint32_t alloc_len, data_len;
10408 
10409 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10410 	alloc_len = scsi_2btoul(cdb->length);
10411 
10412 	data_len = sizeof(struct scsi_mechanism_status_header);
10413 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10414 	ctsio->kern_sg_entries = 0;
10415 	ctsio->kern_rel_offset = 0;
10416 	ctsio->kern_data_len = min(data_len, alloc_len);
10417 	ctsio->kern_total_len = ctsio->kern_data_len;
10418 
10419 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10420 	hdr->state1 = 0x00;
10421 	hdr->state2 = 0xe0;
10422 	scsi_ulto3b(0, hdr->lba);
10423 	hdr->slots_num = 0;
10424 	scsi_ulto2b(0, hdr->slots_length);
10425 
10426 	ctl_set_success(ctsio);
10427 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10428 	ctsio->be_move_done = ctl_config_move_done;
10429 	ctl_datamove((union ctl_io *)ctsio);
10430 	return (CTL_RETVAL_COMPLETE);
10431 }
10432 
10433 static void
10434 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10435 {
10436 
10437 	lba += 150;
10438 	buf[0] = 0;
10439 	buf[1] = bin2bcd((lba / 75) / 60);
10440 	buf[2] = bin2bcd((lba / 75) % 60);
10441 	buf[3] = bin2bcd(lba % 75);
10442 }
10443 
10444 int
10445 ctl_read_toc(struct ctl_scsiio *ctsio)
10446 {
10447 	struct ctl_lun *lun = CTL_LUN(ctsio);
10448 	struct scsi_read_toc_hdr *hdr;
10449 	struct scsi_read_toc_type01_descr *descr;
10450 	struct scsi_read_toc *cdb;
10451 	uint32_t alloc_len, data_len;
10452 	int format, msf;
10453 
10454 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10455 	msf = (cdb->byte2 & CD_MSF) != 0;
10456 	format = cdb->format;
10457 	alloc_len = scsi_2btoul(cdb->data_len);
10458 
10459 	data_len = sizeof(struct scsi_read_toc_hdr);
10460 	if (format == 0)
10461 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10462 	else
10463 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10464 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10465 	ctsio->kern_sg_entries = 0;
10466 	ctsio->kern_rel_offset = 0;
10467 	ctsio->kern_data_len = min(data_len, alloc_len);
10468 	ctsio->kern_total_len = ctsio->kern_data_len;
10469 
10470 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10471 	if (format == 0) {
10472 		scsi_ulto2b(0x12, hdr->data_length);
10473 		hdr->first = 1;
10474 		hdr->last = 1;
10475 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10476 		descr->addr_ctl = 0x14;
10477 		descr->track_number = 1;
10478 		if (msf)
10479 			ctl_ultomsf(0, descr->track_start);
10480 		else
10481 			scsi_ulto4b(0, descr->track_start);
10482 		descr++;
10483 		descr->addr_ctl = 0x14;
10484 		descr->track_number = 0xaa;
10485 		if (msf)
10486 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10487 		else
10488 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10489 	} else {
10490 		scsi_ulto2b(0x0a, hdr->data_length);
10491 		hdr->first = 1;
10492 		hdr->last = 1;
10493 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10494 		descr->addr_ctl = 0x14;
10495 		descr->track_number = 1;
10496 		if (msf)
10497 			ctl_ultomsf(0, descr->track_start);
10498 		else
10499 			scsi_ulto4b(0, descr->track_start);
10500 	}
10501 
10502 	ctl_set_success(ctsio);
10503 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10504 	ctsio->be_move_done = ctl_config_move_done;
10505 	ctl_datamove((union ctl_io *)ctsio);
10506 	return (CTL_RETVAL_COMPLETE);
10507 }
10508 
10509 /*
10510  * For known CDB types, parse the LBA and length.
10511  */
10512 static int
10513 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10514 {
10515 	if (io->io_hdr.io_type != CTL_IO_SCSI)
10516 		return (1);
10517 
10518 	switch (io->scsiio.cdb[0]) {
10519 	case COMPARE_AND_WRITE: {
10520 		struct scsi_compare_and_write *cdb;
10521 
10522 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10523 
10524 		*lba = scsi_8btou64(cdb->addr);
10525 		*len = cdb->length;
10526 		break;
10527 	}
10528 	case READ_6:
10529 	case WRITE_6: {
10530 		struct scsi_rw_6 *cdb;
10531 
10532 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10533 
10534 		*lba = scsi_3btoul(cdb->addr);
10535 		/* only 5 bits are valid in the most significant address byte */
10536 		*lba &= 0x1fffff;
10537 		*len = cdb->length;
10538 		break;
10539 	}
10540 	case READ_10:
10541 	case WRITE_10: {
10542 		struct scsi_rw_10 *cdb;
10543 
10544 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10545 
10546 		*lba = scsi_4btoul(cdb->addr);
10547 		*len = scsi_2btoul(cdb->length);
10548 		break;
10549 	}
10550 	case WRITE_VERIFY_10: {
10551 		struct scsi_write_verify_10 *cdb;
10552 
10553 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10554 
10555 		*lba = scsi_4btoul(cdb->addr);
10556 		*len = scsi_2btoul(cdb->length);
10557 		break;
10558 	}
10559 	case READ_12:
10560 	case WRITE_12: {
10561 		struct scsi_rw_12 *cdb;
10562 
10563 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10564 
10565 		*lba = scsi_4btoul(cdb->addr);
10566 		*len = scsi_4btoul(cdb->length);
10567 		break;
10568 	}
10569 	case WRITE_VERIFY_12: {
10570 		struct scsi_write_verify_12 *cdb;
10571 
10572 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10573 
10574 		*lba = scsi_4btoul(cdb->addr);
10575 		*len = scsi_4btoul(cdb->length);
10576 		break;
10577 	}
10578 	case READ_16:
10579 	case WRITE_16: {
10580 		struct scsi_rw_16 *cdb;
10581 
10582 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10583 
10584 		*lba = scsi_8btou64(cdb->addr);
10585 		*len = scsi_4btoul(cdb->length);
10586 		break;
10587 	}
10588 	case WRITE_ATOMIC_16: {
10589 		struct scsi_write_atomic_16 *cdb;
10590 
10591 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10592 
10593 		*lba = scsi_8btou64(cdb->addr);
10594 		*len = scsi_2btoul(cdb->length);
10595 		break;
10596 	}
10597 	case WRITE_VERIFY_16: {
10598 		struct scsi_write_verify_16 *cdb;
10599 
10600 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10601 
10602 		*lba = scsi_8btou64(cdb->addr);
10603 		*len = scsi_4btoul(cdb->length);
10604 		break;
10605 	}
10606 	case WRITE_SAME_10: {
10607 		struct scsi_write_same_10 *cdb;
10608 
10609 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10610 
10611 		*lba = scsi_4btoul(cdb->addr);
10612 		*len = scsi_2btoul(cdb->length);
10613 		break;
10614 	}
10615 	case WRITE_SAME_16: {
10616 		struct scsi_write_same_16 *cdb;
10617 
10618 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10619 
10620 		*lba = scsi_8btou64(cdb->addr);
10621 		*len = scsi_4btoul(cdb->length);
10622 		break;
10623 	}
10624 	case VERIFY_10: {
10625 		struct scsi_verify_10 *cdb;
10626 
10627 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10628 
10629 		*lba = scsi_4btoul(cdb->addr);
10630 		*len = scsi_2btoul(cdb->length);
10631 		break;
10632 	}
10633 	case VERIFY_12: {
10634 		struct scsi_verify_12 *cdb;
10635 
10636 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10637 
10638 		*lba = scsi_4btoul(cdb->addr);
10639 		*len = scsi_4btoul(cdb->length);
10640 		break;
10641 	}
10642 	case VERIFY_16: {
10643 		struct scsi_verify_16 *cdb;
10644 
10645 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10646 
10647 		*lba = scsi_8btou64(cdb->addr);
10648 		*len = scsi_4btoul(cdb->length);
10649 		break;
10650 	}
10651 	case UNMAP: {
10652 		*lba = 0;
10653 		*len = UINT64_MAX;
10654 		break;
10655 	}
10656 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10657 		struct scsi_get_lba_status *cdb;
10658 
10659 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10660 		*lba = scsi_8btou64(cdb->addr);
10661 		*len = UINT32_MAX;
10662 		break;
10663 	}
10664 	default:
10665 		return (1);
10666 		break; /* NOTREACHED */
10667 	}
10668 
10669 	return (0);
10670 }
10671 
10672 static ctl_action
10673 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10674     bool seq)
10675 {
10676 	uint64_t endlba1, endlba2;
10677 
10678 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10679 	endlba2 = lba2 + len2 - 1;
10680 
10681 	if ((endlba1 < lba2) || (endlba2 < lba1))
10682 		return (CTL_ACTION_PASS);
10683 	else
10684 		return (CTL_ACTION_BLOCK);
10685 }
10686 
10687 static int
10688 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10689 {
10690 	struct ctl_ptr_len_flags *ptrlen;
10691 	struct scsi_unmap_desc *buf, *end, *range;
10692 	uint64_t lba;
10693 	uint32_t len;
10694 
10695 	/* If not UNMAP -- go other way. */
10696 	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10697 	    io->scsiio.cdb[0] != UNMAP)
10698 		return (CTL_ACTION_ERROR);
10699 
10700 	/* If UNMAP without data -- block and wait for data. */
10701 	ptrlen = (struct ctl_ptr_len_flags *)
10702 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10703 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10704 	    ptrlen->ptr == NULL)
10705 		return (CTL_ACTION_BLOCK);
10706 
10707 	/* UNMAP with data -- check for collision. */
10708 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10709 	end = buf + ptrlen->len / sizeof(*buf);
10710 	for (range = buf; range < end; range++) {
10711 		lba = scsi_8btou64(range->lba);
10712 		len = scsi_4btoul(range->length);
10713 		if ((lba < lba2 + len2) && (lba + len > lba2))
10714 			return (CTL_ACTION_BLOCK);
10715 	}
10716 	return (CTL_ACTION_PASS);
10717 }
10718 
10719 static ctl_action
10720 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10721 {
10722 	uint64_t lba1, lba2;
10723 	uint64_t len1, len2;
10724 	int retval;
10725 
10726 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10727 		return (CTL_ACTION_ERROR);
10728 
10729 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10730 	if (retval != CTL_ACTION_ERROR)
10731 		return (retval);
10732 
10733 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10734 		return (CTL_ACTION_ERROR);
10735 
10736 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10737 		seq = FALSE;
10738 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10739 }
10740 
10741 static ctl_action
10742 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10743 {
10744 	uint64_t lba1, lba2;
10745 	uint64_t len1, len2;
10746 
10747 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10748 		return (CTL_ACTION_PASS);
10749 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10750 		return (CTL_ACTION_ERROR);
10751 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10752 		return (CTL_ACTION_ERROR);
10753 
10754 	if (lba1 + len1 == lba2)
10755 		return (CTL_ACTION_BLOCK);
10756 	return (CTL_ACTION_PASS);
10757 }
10758 
10759 static ctl_action
10760 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10761     union ctl_io *ooa_io)
10762 {
10763 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10764 	const ctl_serialize_action *serialize_row;
10765 
10766 	/*
10767 	 * Aborted commands are not going to be executed and may even
10768 	 * not report completion, so we don't care about their order.
10769 	 * Let them complete ASAP to clean the OOA queue.
10770 	 */
10771 	if (pending_io->io_hdr.flags & CTL_FLAG_ABORT)
10772 		return (CTL_ACTION_SKIP);
10773 
10774 	/*
10775 	 * The initiator attempted multiple untagged commands at the same
10776 	 * time.  Can't do that.
10777 	 */
10778 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10779 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10780 	 && ((pending_io->io_hdr.nexus.targ_port ==
10781 	      ooa_io->io_hdr.nexus.targ_port)
10782 	  && (pending_io->io_hdr.nexus.initid ==
10783 	      ooa_io->io_hdr.nexus.initid))
10784 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10785 	      CTL_FLAG_STATUS_SENT)) == 0))
10786 		return (CTL_ACTION_OVERLAP);
10787 
10788 	/*
10789 	 * The initiator attempted to send multiple tagged commands with
10790 	 * the same ID.  (It's fine if different initiators have the same
10791 	 * tag ID.)
10792 	 *
10793 	 * Even if all of those conditions are true, we don't kill the I/O
10794 	 * if the command ahead of us has been aborted.  We won't end up
10795 	 * sending it to the FETD, and it's perfectly legal to resend a
10796 	 * command with the same tag number as long as the previous
10797 	 * instance of this tag number has been aborted somehow.
10798 	 */
10799 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10800 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10801 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10802 	 && ((pending_io->io_hdr.nexus.targ_port ==
10803 	      ooa_io->io_hdr.nexus.targ_port)
10804 	  && (pending_io->io_hdr.nexus.initid ==
10805 	      ooa_io->io_hdr.nexus.initid))
10806 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10807 	      CTL_FLAG_STATUS_SENT)) == 0))
10808 		return (CTL_ACTION_OVERLAP_TAG);
10809 
10810 	/*
10811 	 * If we get a head of queue tag, SAM-3 says that we should
10812 	 * immediately execute it.
10813 	 *
10814 	 * What happens if this command would normally block for some other
10815 	 * reason?  e.g. a request sense with a head of queue tag
10816 	 * immediately after a write.  Normally that would block, but this
10817 	 * will result in its getting executed immediately...
10818 	 *
10819 	 * We currently return "pass" instead of "skip", so we'll end up
10820 	 * going through the rest of the queue to check for overlapped tags.
10821 	 *
10822 	 * XXX KDM check for other types of blockage first??
10823 	 */
10824 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10825 		return (CTL_ACTION_PASS);
10826 
10827 	/*
10828 	 * Ordered tags have to block until all items ahead of them
10829 	 * have completed.  If we get called with an ordered tag, we always
10830 	 * block, if something else is ahead of us in the queue.
10831 	 */
10832 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10833 		return (CTL_ACTION_BLOCK);
10834 
10835 	/*
10836 	 * Simple tags get blocked until all head of queue and ordered tags
10837 	 * ahead of them have completed.  I'm lumping untagged commands in
10838 	 * with simple tags here.  XXX KDM is that the right thing to do?
10839 	 */
10840 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10841 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10842 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10843 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10844 		return (CTL_ACTION_BLOCK);
10845 
10846 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10847 	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
10848 	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
10849 	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
10850 	     pending_io->scsiio.cdb[1], pending_io));
10851 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10852 	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
10853 		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
10854 	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
10855 	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
10856 	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
10857 	     ooa_io->scsiio.cdb[1], ooa_io));
10858 
10859 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10860 
10861 	switch (serialize_row[pending_entry->seridx]) {
10862 	case CTL_SER_BLOCK:
10863 		return (CTL_ACTION_BLOCK);
10864 	case CTL_SER_EXTENT:
10865 		return (ctl_extent_check(ooa_io, pending_io,
10866 		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10867 	case CTL_SER_EXTENTOPT:
10868 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
10869 		    SCP_QUEUE_ALG_UNRESTRICTED)
10870 			return (ctl_extent_check(ooa_io, pending_io,
10871 			    (lun->be_lun &&
10872 			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10873 		return (CTL_ACTION_PASS);
10874 	case CTL_SER_EXTENTSEQ:
10875 		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10876 			return (ctl_extent_check_seq(ooa_io, pending_io));
10877 		return (CTL_ACTION_PASS);
10878 	case CTL_SER_PASS:
10879 		return (CTL_ACTION_PASS);
10880 	case CTL_SER_BLOCKOPT:
10881 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
10882 		    SCP_QUEUE_ALG_UNRESTRICTED)
10883 			return (CTL_ACTION_BLOCK);
10884 		return (CTL_ACTION_PASS);
10885 	case CTL_SER_SKIP:
10886 		return (CTL_ACTION_SKIP);
10887 	default:
10888 		panic("%s: Invalid serialization value %d for %d => %d",
10889 		    __func__, serialize_row[pending_entry->seridx],
10890 		    pending_entry->seridx, ooa_entry->seridx);
10891 	}
10892 
10893 	return (CTL_ACTION_ERROR);
10894 }
10895 
10896 /*
10897  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10898  * Assumptions:
10899  * - pending_io is generally either incoming, or on the blocked queue
10900  * - starting I/O is the I/O we want to start the check with.
10901  */
10902 static ctl_action
10903 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10904 	      union ctl_io **starting_io)
10905 {
10906 	union ctl_io *ooa_io;
10907 	ctl_action action;
10908 
10909 	mtx_assert(&lun->lun_lock, MA_OWNED);
10910 
10911 	/*
10912 	 * Run back along the OOA queue, starting with the current
10913 	 * blocked I/O and going through every I/O before it on the
10914 	 * queue.  If starting_io is NULL, we'll just end up returning
10915 	 * CTL_ACTION_PASS.
10916 	 */
10917 	for (ooa_io = *starting_io; ooa_io != NULL;
10918 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10919 	     ooa_links)){
10920 		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10921 		if (action != CTL_ACTION_PASS) {
10922 			*starting_io = ooa_io;
10923 			return (action);
10924 		}
10925 	}
10926 
10927 	*starting_io = NULL;
10928 	return (CTL_ACTION_PASS);
10929 }
10930 
10931 /*
10932  * Try to unblock the specified I/O.
10933  *
10934  * skip parameter allows explicitly skip present blocker of the I/O,
10935  * starting from the previous one on OOA queue.  It can be used when
10936  * we know for sure that the blocker I/O does no longer count.
10937  */
10938 static void
10939 ctl_try_unblock_io(struct ctl_lun *lun, union ctl_io *io, bool skip)
10940 {
10941 	struct ctl_softc *softc = lun->ctl_softc;
10942 	union ctl_io *bio, *obio;
10943 	const struct ctl_cmd_entry *entry;
10944 	union ctl_ha_msg msg_info;
10945 	ctl_action action;
10946 
10947 	mtx_assert(&lun->lun_lock, MA_OWNED);
10948 
10949 	if (io->io_hdr.blocker == NULL)
10950 		return;
10951 
10952 	obio = bio = io->io_hdr.blocker;
10953 	if (skip)
10954 		bio = (union ctl_io *)TAILQ_PREV(&bio->io_hdr, ctl_ooaq,
10955 		    ooa_links);
10956 	action = ctl_check_ooa(lun, io, &bio);
10957 	if (action == CTL_ACTION_BLOCK) {
10958 		/* Still blocked, but may be by different I/O now. */
10959 		if (bio != obio) {
10960 			TAILQ_REMOVE(&obio->io_hdr.blocked_queue,
10961 			    &io->io_hdr, blocked_links);
10962 			TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue,
10963 			    &io->io_hdr, blocked_links);
10964 			io->io_hdr.blocker = bio;
10965 		}
10966 		return;
10967 	}
10968 
10969 	/* No longer blocked, one way or another. */
10970 	TAILQ_REMOVE(&obio->io_hdr.blocked_queue, &io->io_hdr, blocked_links);
10971 	io->io_hdr.blocker = NULL;
10972 
10973 	switch (action) {
10974 	case CTL_ACTION_OVERLAP:
10975 		ctl_set_overlapped_cmd(&io->scsiio);
10976 		goto error;
10977 	case CTL_ACTION_OVERLAP_TAG:
10978 		ctl_set_overlapped_tag(&io->scsiio,
10979 		    io->scsiio.tag_num & 0xff);
10980 		goto error;
10981 	case CTL_ACTION_PASS:
10982 	case CTL_ACTION_SKIP:
10983 
10984 		/* Serializing commands from the other SC retire there. */
10985 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
10986 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
10987 			io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
10988 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
10989 			msg_info.hdr.serializing_sc = io;
10990 			msg_info.hdr.msg_type = CTL_MSG_R2R;
10991 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
10992 			    sizeof(msg_info.hdr), M_NOWAIT);
10993 			break;
10994 		}
10995 
10996 		/*
10997 		 * Check this I/O for LUN state changes that may have happened
10998 		 * while this command was blocked. The LUN state may have been
10999 		 * changed by a command ahead of us in the queue.
11000 		 */
11001 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
11002 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
11003 			ctl_done(io);
11004 			break;
11005 		}
11006 
11007 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11008 		ctl_enqueue_rtr(io);
11009 		break;
11010 	case CTL_ACTION_ERROR:
11011 	default:
11012 		ctl_set_internal_failure(&io->scsiio,
11013 					 /*sks_valid*/ 0,
11014 					 /*retry_count*/ 0);
11015 
11016 error:
11017 		/* Serializing commands from the other SC are done here. */
11018 		if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) &&
11019 		    (softc->ha_mode != CTL_HA_MODE_XFER)) {
11020 			ctl_try_unblock_others(lun, io, TRUE);
11021 			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
11022 
11023 			ctl_copy_sense_data_back(io, &msg_info);
11024 			msg_info.hdr.original_sc = io->io_hdr.remote_io;
11025 			msg_info.hdr.serializing_sc = NULL;
11026 			msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
11027 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11028 			    sizeof(msg_info.scsi), M_WAITOK);
11029 			ctl_free_io(io);
11030 			break;
11031 		}
11032 
11033 		ctl_done(io);
11034 		break;
11035 	}
11036 }
11037 
11038 /*
11039  * Try to unblock I/Os blocked by the specified I/O.
11040  *
11041  * skip parameter allows explicitly skip the specified I/O as blocker,
11042  * starting from the previous one on the OOA queue.  It can be used when
11043  * we know for sure that the specified I/O does no longer count (done).
11044  * It has to be still on OOA queue though so that we know where to start.
11045  */
11046 static void
11047 ctl_try_unblock_others(struct ctl_lun *lun, union ctl_io *bio, bool skip)
11048 {
11049 	union ctl_io *io, *next_io;
11050 
11051 	mtx_assert(&lun->lun_lock, MA_OWNED);
11052 
11053 	for (io = (union ctl_io *)TAILQ_FIRST(&bio->io_hdr.blocked_queue);
11054 	     io != NULL; io = next_io) {
11055 		next_io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr, blocked_links);
11056 
11057 		KASSERT(io->io_hdr.blocker != NULL,
11058 		    ("I/O %p on blocked list without blocker", io));
11059 		ctl_try_unblock_io(lun, io, skip);
11060 	}
11061 	KASSERT(!skip || TAILQ_EMPTY(&bio->io_hdr.blocked_queue),
11062 	    ("blocked_queue is not empty after skipping %p", bio));
11063 }
11064 
11065 /*
11066  * This routine (with one exception) checks LUN flags that can be set by
11067  * commands ahead of us in the OOA queue.  These flags have to be checked
11068  * when a command initially comes in, and when we pull a command off the
11069  * blocked queue and are preparing to execute it.  The reason we have to
11070  * check these flags for commands on the blocked queue is that the LUN
11071  * state may have been changed by a command ahead of us while we're on the
11072  * blocked queue.
11073  *
11074  * Ordering is somewhat important with these checks, so please pay
11075  * careful attention to the placement of any new checks.
11076  */
11077 static int
11078 ctl_scsiio_lun_check(struct ctl_lun *lun,
11079     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11080 {
11081 	struct ctl_softc *softc = lun->ctl_softc;
11082 	int retval;
11083 	uint32_t residx;
11084 
11085 	retval = 0;
11086 
11087 	mtx_assert(&lun->lun_lock, MA_OWNED);
11088 
11089 	/*
11090 	 * If this shelf is a secondary shelf controller, we may have to
11091 	 * reject some commands disallowed by HA mode and link state.
11092 	 */
11093 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11094 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11095 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11096 			ctl_set_lun_unavail(ctsio);
11097 			retval = 1;
11098 			goto bailout;
11099 		}
11100 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11101 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11102 			ctl_set_lun_transit(ctsio);
11103 			retval = 1;
11104 			goto bailout;
11105 		}
11106 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11107 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11108 			ctl_set_lun_standby(ctsio);
11109 			retval = 1;
11110 			goto bailout;
11111 		}
11112 
11113 		/* The rest of checks are only done on executing side */
11114 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11115 			goto bailout;
11116 	}
11117 
11118 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11119 		if (lun->be_lun &&
11120 		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11121 			ctl_set_hw_write_protected(ctsio);
11122 			retval = 1;
11123 			goto bailout;
11124 		}
11125 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11126 			ctl_set_sense(ctsio, /*current_error*/ 1,
11127 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11128 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11129 			retval = 1;
11130 			goto bailout;
11131 		}
11132 	}
11133 
11134 	/*
11135 	 * Check for a reservation conflict.  If this command isn't allowed
11136 	 * even on reserved LUNs, and if this initiator isn't the one who
11137 	 * reserved us, reject the command with a reservation conflict.
11138 	 */
11139 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11140 	if ((lun->flags & CTL_LUN_RESERVED)
11141 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11142 		if (lun->res_idx != residx) {
11143 			ctl_set_reservation_conflict(ctsio);
11144 			retval = 1;
11145 			goto bailout;
11146 		}
11147 	}
11148 
11149 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11150 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11151 		/* No reservation or command is allowed. */;
11152 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11153 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11154 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11155 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11156 		/* The command is allowed for Write Exclusive resv. */;
11157 	} else {
11158 		/*
11159 		 * if we aren't registered or it's a res holder type
11160 		 * reservation and this isn't the res holder then set a
11161 		 * conflict.
11162 		 */
11163 		if (ctl_get_prkey(lun, residx) == 0 ||
11164 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11165 			ctl_set_reservation_conflict(ctsio);
11166 			retval = 1;
11167 			goto bailout;
11168 		}
11169 	}
11170 
11171 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11172 		if (lun->flags & CTL_LUN_EJECTED)
11173 			ctl_set_lun_ejected(ctsio);
11174 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11175 			if (lun->flags & CTL_LUN_REMOVABLE)
11176 				ctl_set_lun_no_media(ctsio);
11177 			else
11178 				ctl_set_lun_int_reqd(ctsio);
11179 		} else if (lun->flags & CTL_LUN_STOPPED)
11180 			ctl_set_lun_stopped(ctsio);
11181 		else
11182 			goto bailout;
11183 		retval = 1;
11184 		goto bailout;
11185 	}
11186 
11187 bailout:
11188 	return (retval);
11189 }
11190 
11191 static void
11192 ctl_failover_io(union ctl_io *io, int have_lock)
11193 {
11194 	ctl_set_busy(&io->scsiio);
11195 	ctl_done(io);
11196 }
11197 
11198 static void
11199 ctl_failover_lun(union ctl_io *rio)
11200 {
11201 	struct ctl_softc *softc = CTL_SOFTC(rio);
11202 	struct ctl_lun *lun;
11203 	struct ctl_io_hdr *io, *next_io;
11204 	uint32_t targ_lun;
11205 
11206 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11207 	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11208 
11209 	/* Find and lock the LUN. */
11210 	mtx_lock(&softc->ctl_lock);
11211 	if (targ_lun > ctl_max_luns ||
11212 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11213 		mtx_unlock(&softc->ctl_lock);
11214 		return;
11215 	}
11216 	mtx_lock(&lun->lun_lock);
11217 	mtx_unlock(&softc->ctl_lock);
11218 	if (lun->flags & CTL_LUN_DISABLED) {
11219 		mtx_unlock(&lun->lun_lock);
11220 		return;
11221 	}
11222 
11223 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11224 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11225 			/* We are master */
11226 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11227 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11228 					io->flags |= CTL_FLAG_ABORT;
11229 					io->flags |= CTL_FLAG_FAILOVER;
11230 					ctl_try_unblock_io(lun,
11231 					    (union ctl_io *)io, FALSE);
11232 				} else { /* This can be only due to DATAMOVE */
11233 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11234 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11235 					io->flags |= CTL_FLAG_IO_ACTIVE;
11236 					io->port_status = 31340;
11237 					ctl_enqueue_isc((union ctl_io *)io);
11238 				}
11239 			} else
11240 			/* We are slave */
11241 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11242 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11243 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11244 					io->flags |= CTL_FLAG_FAILOVER;
11245 				} else {
11246 					ctl_set_busy(&((union ctl_io *)io)->
11247 					    scsiio);
11248 					ctl_done((union ctl_io *)io);
11249 				}
11250 			}
11251 		}
11252 	} else { /* SERIALIZE modes */
11253 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11254 			/* We are master */
11255 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11256 				if (io->blocker != NULL) {
11257 					TAILQ_REMOVE(&io->blocker->io_hdr.blocked_queue,
11258 					    io, blocked_links);
11259 					io->blocker = NULL;
11260 				}
11261 				ctl_try_unblock_others(lun, (union ctl_io *)io,
11262 				    TRUE);
11263 				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11264 				ctl_free_io((union ctl_io *)io);
11265 			} else
11266 			/* We are slave */
11267 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11268 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11269 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11270 					ctl_set_busy(&((union ctl_io *)io)->
11271 					    scsiio);
11272 					ctl_done((union ctl_io *)io);
11273 				}
11274 			}
11275 		}
11276 	}
11277 	mtx_unlock(&lun->lun_lock);
11278 }
11279 
11280 static int
11281 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11282 {
11283 	struct ctl_lun *lun;
11284 	const struct ctl_cmd_entry *entry;
11285 	union ctl_io *bio;
11286 	uint32_t initidx, targ_lun;
11287 	int retval = 0;
11288 
11289 	lun = NULL;
11290 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11291 	if (targ_lun < ctl_max_luns)
11292 		lun = softc->ctl_luns[targ_lun];
11293 	if (lun) {
11294 		/*
11295 		 * If the LUN is invalid, pretend that it doesn't exist.
11296 		 * It will go away as soon as all pending I/O has been
11297 		 * completed.
11298 		 */
11299 		mtx_lock(&lun->lun_lock);
11300 		if (lun->flags & CTL_LUN_DISABLED) {
11301 			mtx_unlock(&lun->lun_lock);
11302 			lun = NULL;
11303 		}
11304 	}
11305 	CTL_LUN(ctsio) = lun;
11306 	if (lun) {
11307 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11308 
11309 		/*
11310 		 * Every I/O goes into the OOA queue for a particular LUN,
11311 		 * and stays there until completion.
11312 		 */
11313 #ifdef CTL_TIME_IO
11314 		if (TAILQ_EMPTY(&lun->ooa_queue))
11315 			lun->idle_time += getsbinuptime() - lun->last_busy;
11316 #endif
11317 		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11318 	}
11319 
11320 	/* Get command entry and return error if it is unsuppotyed. */
11321 	entry = ctl_validate_command(ctsio);
11322 	if (entry == NULL) {
11323 		if (lun)
11324 			mtx_unlock(&lun->lun_lock);
11325 		return (retval);
11326 	}
11327 
11328 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11329 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11330 
11331 	/*
11332 	 * Check to see whether we can send this command to LUNs that don't
11333 	 * exist.  This should pretty much only be the case for inquiry
11334 	 * and request sense.  Further checks, below, really require having
11335 	 * a LUN, so we can't really check the command anymore.  Just put
11336 	 * it on the rtr queue.
11337 	 */
11338 	if (lun == NULL) {
11339 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11340 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11341 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11342 			return (retval);
11343 		}
11344 
11345 		ctl_set_unsupported_lun(ctsio);
11346 		ctl_done((union ctl_io *)ctsio);
11347 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11348 		return (retval);
11349 	} else {
11350 		/*
11351 		 * Make sure we support this particular command on this LUN.
11352 		 * e.g., we don't support writes to the control LUN.
11353 		 */
11354 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11355 			mtx_unlock(&lun->lun_lock);
11356 			ctl_set_invalid_opcode(ctsio);
11357 			ctl_done((union ctl_io *)ctsio);
11358 			return (retval);
11359 		}
11360 	}
11361 
11362 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11363 
11364 	/*
11365 	 * If we've got a request sense, it'll clear the contingent
11366 	 * allegiance condition.  Otherwise, if we have a CA condition for
11367 	 * this initiator, clear it, because it sent down a command other
11368 	 * than request sense.
11369 	 */
11370 	if (ctsio->cdb[0] != REQUEST_SENSE) {
11371 		struct scsi_sense_data *ps;
11372 
11373 		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11374 		if (ps != NULL)
11375 			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11376 	}
11377 
11378 	/*
11379 	 * If the command has this flag set, it handles its own unit
11380 	 * attention reporting, we shouldn't do anything.  Otherwise we
11381 	 * check for any pending unit attentions, and send them back to the
11382 	 * initiator.  We only do this when a command initially comes in,
11383 	 * not when we pull it off the blocked queue.
11384 	 *
11385 	 * According to SAM-3, section 5.3.2, the order that things get
11386 	 * presented back to the host is basically unit attentions caused
11387 	 * by some sort of reset event, busy status, reservation conflicts
11388 	 * or task set full, and finally any other status.
11389 	 *
11390 	 * One issue here is that some of the unit attentions we report
11391 	 * don't fall into the "reset" category (e.g. "reported luns data
11392 	 * has changed").  So reporting it here, before the reservation
11393 	 * check, may be technically wrong.  I guess the only thing to do
11394 	 * would be to check for and report the reset events here, and then
11395 	 * check for the other unit attention types after we check for a
11396 	 * reservation conflict.
11397 	 *
11398 	 * XXX KDM need to fix this
11399 	 */
11400 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11401 		ctl_ua_type ua_type;
11402 		u_int sense_len = 0;
11403 
11404 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11405 		    &sense_len, SSD_TYPE_NONE);
11406 		if (ua_type != CTL_UA_NONE) {
11407 			mtx_unlock(&lun->lun_lock);
11408 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11409 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11410 			ctsio->sense_len = sense_len;
11411 			ctl_done((union ctl_io *)ctsio);
11412 			return (retval);
11413 		}
11414 	}
11415 
11416 
11417 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11418 		mtx_unlock(&lun->lun_lock);
11419 		ctl_done((union ctl_io *)ctsio);
11420 		return (retval);
11421 	}
11422 
11423 	/*
11424 	 * XXX CHD this is where we want to send IO to other side if
11425 	 * this LUN is secondary on this SC. We will need to make a copy
11426 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11427 	 * the copy we send as FROM_OTHER.
11428 	 * We also need to stuff the address of the original IO so we can
11429 	 * find it easily. Something similar will need be done on the other
11430 	 * side so when we are done we can find the copy.
11431 	 */
11432 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11433 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11434 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11435 		union ctl_ha_msg msg_info;
11436 		int isc_retval;
11437 
11438 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11439 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11440 		mtx_unlock(&lun->lun_lock);
11441 
11442 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11443 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11444 		msg_info.hdr.serializing_sc = NULL;
11445 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11446 		msg_info.scsi.tag_num = ctsio->tag_num;
11447 		msg_info.scsi.tag_type = ctsio->tag_type;
11448 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11449 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11450 
11451 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11452 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11453 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11454 			ctl_set_busy(ctsio);
11455 			ctl_done((union ctl_io *)ctsio);
11456 			return (retval);
11457 		}
11458 		return (retval);
11459 	}
11460 
11461 	bio = (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq, ooa_links);
11462 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio, &bio)) {
11463 	case CTL_ACTION_BLOCK:
11464 		ctsio->io_hdr.blocker = bio;
11465 		TAILQ_INSERT_TAIL(&bio->io_hdr.blocked_queue, &ctsio->io_hdr,
11466 				  blocked_links);
11467 		mtx_unlock(&lun->lun_lock);
11468 		return (retval);
11469 	case CTL_ACTION_PASS:
11470 	case CTL_ACTION_SKIP:
11471 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11472 		mtx_unlock(&lun->lun_lock);
11473 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11474 		break;
11475 	case CTL_ACTION_OVERLAP:
11476 		mtx_unlock(&lun->lun_lock);
11477 		ctl_set_overlapped_cmd(ctsio);
11478 		ctl_done((union ctl_io *)ctsio);
11479 		break;
11480 	case CTL_ACTION_OVERLAP_TAG:
11481 		mtx_unlock(&lun->lun_lock);
11482 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11483 		ctl_done((union ctl_io *)ctsio);
11484 		break;
11485 	case CTL_ACTION_ERROR:
11486 	default:
11487 		mtx_unlock(&lun->lun_lock);
11488 		ctl_set_internal_failure(ctsio,
11489 					 /*sks_valid*/ 0,
11490 					 /*retry_count*/ 0);
11491 		ctl_done((union ctl_io *)ctsio);
11492 		break;
11493 	}
11494 	return (retval);
11495 }
11496 
11497 const struct ctl_cmd_entry *
11498 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11499 {
11500 	const struct ctl_cmd_entry *entry;
11501 	int service_action;
11502 
11503 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11504 	if (sa)
11505 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11506 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11507 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11508 		entry = &((const struct ctl_cmd_entry *)
11509 		    entry->execute)[service_action];
11510 	}
11511 	return (entry);
11512 }
11513 
11514 const struct ctl_cmd_entry *
11515 ctl_validate_command(struct ctl_scsiio *ctsio)
11516 {
11517 	const struct ctl_cmd_entry *entry;
11518 	int i, sa;
11519 	uint8_t diff;
11520 
11521 	entry = ctl_get_cmd_entry(ctsio, &sa);
11522 	if (entry->execute == NULL) {
11523 		if (sa)
11524 			ctl_set_invalid_field(ctsio,
11525 					      /*sks_valid*/ 1,
11526 					      /*command*/ 1,
11527 					      /*field*/ 1,
11528 					      /*bit_valid*/ 1,
11529 					      /*bit*/ 4);
11530 		else
11531 			ctl_set_invalid_opcode(ctsio);
11532 		ctl_done((union ctl_io *)ctsio);
11533 		return (NULL);
11534 	}
11535 	KASSERT(entry->length > 0,
11536 	    ("Not defined length for command 0x%02x/0x%02x",
11537 	     ctsio->cdb[0], ctsio->cdb[1]));
11538 	for (i = 1; i < entry->length; i++) {
11539 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11540 		if (diff == 0)
11541 			continue;
11542 		ctl_set_invalid_field(ctsio,
11543 				      /*sks_valid*/ 1,
11544 				      /*command*/ 1,
11545 				      /*field*/ i,
11546 				      /*bit_valid*/ 1,
11547 				      /*bit*/ fls(diff) - 1);
11548 		ctl_done((union ctl_io *)ctsio);
11549 		return (NULL);
11550 	}
11551 	return (entry);
11552 }
11553 
11554 static int
11555 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11556 {
11557 
11558 	switch (lun_type) {
11559 	case T_DIRECT:
11560 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11561 			return (0);
11562 		break;
11563 	case T_PROCESSOR:
11564 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11565 			return (0);
11566 		break;
11567 	case T_CDROM:
11568 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11569 			return (0);
11570 		break;
11571 	default:
11572 		return (0);
11573 	}
11574 	return (1);
11575 }
11576 
11577 static int
11578 ctl_scsiio(struct ctl_scsiio *ctsio)
11579 {
11580 	int retval;
11581 	const struct ctl_cmd_entry *entry;
11582 
11583 	retval = CTL_RETVAL_COMPLETE;
11584 
11585 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11586 
11587 	entry = ctl_get_cmd_entry(ctsio, NULL);
11588 
11589 	/*
11590 	 * If this I/O has been aborted, just send it straight to
11591 	 * ctl_done() without executing it.
11592 	 */
11593 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11594 		ctl_done((union ctl_io *)ctsio);
11595 		goto bailout;
11596 	}
11597 
11598 	/*
11599 	 * All the checks should have been handled by ctl_scsiio_precheck().
11600 	 * We should be clear now to just execute the I/O.
11601 	 */
11602 	retval = entry->execute(ctsio);
11603 
11604 bailout:
11605 	return (retval);
11606 }
11607 
11608 static int
11609 ctl_target_reset(union ctl_io *io)
11610 {
11611 	struct ctl_softc *softc = CTL_SOFTC(io);
11612 	struct ctl_port *port = CTL_PORT(io);
11613 	struct ctl_lun *lun;
11614 	uint32_t initidx;
11615 	ctl_ua_type ua_type;
11616 
11617 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11618 		union ctl_ha_msg msg_info;
11619 
11620 		msg_info.hdr.nexus = io->io_hdr.nexus;
11621 		msg_info.task.task_action = io->taskio.task_action;
11622 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11623 		msg_info.hdr.original_sc = NULL;
11624 		msg_info.hdr.serializing_sc = NULL;
11625 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11626 		    sizeof(msg_info.task), M_WAITOK);
11627 	}
11628 
11629 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11630 	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11631 		ua_type = CTL_UA_TARG_RESET;
11632 	else
11633 		ua_type = CTL_UA_BUS_RESET;
11634 	mtx_lock(&softc->ctl_lock);
11635 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11636 		if (port != NULL &&
11637 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11638 			continue;
11639 		ctl_do_lun_reset(lun, initidx, ua_type);
11640 	}
11641 	mtx_unlock(&softc->ctl_lock);
11642 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11643 	return (0);
11644 }
11645 
11646 /*
11647  * The LUN should always be set.  The I/O is optional, and is used to
11648  * distinguish between I/Os sent by this initiator, and by other
11649  * initiators.  We set unit attention for initiators other than this one.
11650  * SAM-3 is vague on this point.  It does say that a unit attention should
11651  * be established for other initiators when a LUN is reset (see section
11652  * 5.7.3), but it doesn't specifically say that the unit attention should
11653  * be established for this particular initiator when a LUN is reset.  Here
11654  * is the relevant text, from SAM-3 rev 8:
11655  *
11656  * 5.7.2 When a SCSI initiator port aborts its own tasks
11657  *
11658  * When a SCSI initiator port causes its own task(s) to be aborted, no
11659  * notification that the task(s) have been aborted shall be returned to
11660  * the SCSI initiator port other than the completion response for the
11661  * command or task management function action that caused the task(s) to
11662  * be aborted and notification(s) associated with related effects of the
11663  * action (e.g., a reset unit attention condition).
11664  *
11665  * XXX KDM for now, we're setting unit attention for all initiators.
11666  */
11667 static void
11668 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11669 {
11670 	union ctl_io *xio;
11671 	int i;
11672 
11673 	mtx_lock(&lun->lun_lock);
11674 	/* Abort tasks. */
11675 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11676 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11677 		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11678 		ctl_try_unblock_io(lun, xio, FALSE);
11679 	}
11680 	/* Clear CA. */
11681 	for (i = 0; i < ctl_max_ports; i++) {
11682 		free(lun->pending_sense[i], M_CTL);
11683 		lun->pending_sense[i] = NULL;
11684 	}
11685 	/* Clear reservation. */
11686 	lun->flags &= ~CTL_LUN_RESERVED;
11687 	/* Clear prevent media removal. */
11688 	if (lun->prevent) {
11689 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11690 			ctl_clear_mask(lun->prevent, i);
11691 		lun->prevent_count = 0;
11692 	}
11693 	/* Clear TPC status */
11694 	ctl_tpc_lun_clear(lun, -1);
11695 	/* Establish UA. */
11696 #if 0
11697 	ctl_est_ua_all(lun, initidx, ua_type);
11698 #else
11699 	ctl_est_ua_all(lun, -1, ua_type);
11700 #endif
11701 	mtx_unlock(&lun->lun_lock);
11702 }
11703 
11704 static int
11705 ctl_lun_reset(union ctl_io *io)
11706 {
11707 	struct ctl_softc *softc = CTL_SOFTC(io);
11708 	struct ctl_lun *lun;
11709 	uint32_t targ_lun, initidx;
11710 
11711 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11712 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11713 	mtx_lock(&softc->ctl_lock);
11714 	if (targ_lun >= ctl_max_luns ||
11715 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11716 		mtx_unlock(&softc->ctl_lock);
11717 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11718 		return (1);
11719 	}
11720 	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11721 	mtx_unlock(&softc->ctl_lock);
11722 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11723 
11724 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11725 		union ctl_ha_msg msg_info;
11726 
11727 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11728 		msg_info.hdr.nexus = io->io_hdr.nexus;
11729 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11730 		msg_info.hdr.original_sc = NULL;
11731 		msg_info.hdr.serializing_sc = NULL;
11732 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11733 		    sizeof(msg_info.task), M_WAITOK);
11734 	}
11735 	return (0);
11736 }
11737 
11738 static void
11739 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11740     int other_sc)
11741 {
11742 	union ctl_io *xio;
11743 
11744 	mtx_assert(&lun->lun_lock, MA_OWNED);
11745 
11746 	/*
11747 	 * Run through the OOA queue and attempt to find the given I/O.
11748 	 * The target port, initiator ID, tag type and tag number have to
11749 	 * match the values that we got from the initiator.  If we have an
11750 	 * untagged command to abort, simply abort the first untagged command
11751 	 * we come to.  We only allow one untagged command at a time of course.
11752 	 */
11753 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11754 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11755 
11756 		if ((targ_port == UINT32_MAX ||
11757 		     targ_port == xio->io_hdr.nexus.targ_port) &&
11758 		    (init_id == UINT32_MAX ||
11759 		     init_id == xio->io_hdr.nexus.initid)) {
11760 			if (targ_port != xio->io_hdr.nexus.targ_port ||
11761 			    init_id != xio->io_hdr.nexus.initid)
11762 				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11763 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11764 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11765 				union ctl_ha_msg msg_info;
11766 
11767 				msg_info.hdr.nexus = xio->io_hdr.nexus;
11768 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11769 				msg_info.task.tag_num = xio->scsiio.tag_num;
11770 				msg_info.task.tag_type = xio->scsiio.tag_type;
11771 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11772 				msg_info.hdr.original_sc = NULL;
11773 				msg_info.hdr.serializing_sc = NULL;
11774 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11775 				    sizeof(msg_info.task), M_NOWAIT);
11776 			}
11777 			ctl_try_unblock_io(lun, xio, FALSE);
11778 		}
11779 	}
11780 }
11781 
11782 static int
11783 ctl_abort_task_set(union ctl_io *io)
11784 {
11785 	struct ctl_softc *softc = CTL_SOFTC(io);
11786 	struct ctl_lun *lun;
11787 	uint32_t targ_lun;
11788 
11789 	/*
11790 	 * Look up the LUN.
11791 	 */
11792 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11793 	mtx_lock(&softc->ctl_lock);
11794 	if (targ_lun >= ctl_max_luns ||
11795 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11796 		mtx_unlock(&softc->ctl_lock);
11797 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11798 		return (1);
11799 	}
11800 
11801 	mtx_lock(&lun->lun_lock);
11802 	mtx_unlock(&softc->ctl_lock);
11803 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11804 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11805 		    io->io_hdr.nexus.initid,
11806 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11807 	} else { /* CTL_TASK_CLEAR_TASK_SET */
11808 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11809 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11810 	}
11811 	mtx_unlock(&lun->lun_lock);
11812 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11813 	return (0);
11814 }
11815 
11816 static void
11817 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
11818     ctl_ua_type ua_type)
11819 {
11820 	struct ctl_lun *lun;
11821 	struct scsi_sense_data *ps;
11822 	uint32_t p, i;
11823 
11824 	p = initidx / CTL_MAX_INIT_PER_PORT;
11825 	i = initidx % CTL_MAX_INIT_PER_PORT;
11826 	mtx_lock(&softc->ctl_lock);
11827 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11828 		mtx_lock(&lun->lun_lock);
11829 		/* Abort tasks. */
11830 		ctl_abort_tasks_lun(lun, p, i, 1);
11831 		/* Clear CA. */
11832 		ps = lun->pending_sense[p];
11833 		if (ps != NULL)
11834 			ps[i].error_code = 0;
11835 		/* Clear reservation. */
11836 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11837 			lun->flags &= ~CTL_LUN_RESERVED;
11838 		/* Clear prevent media removal. */
11839 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
11840 			ctl_clear_mask(lun->prevent, initidx);
11841 			lun->prevent_count--;
11842 		}
11843 		/* Clear TPC status */
11844 		ctl_tpc_lun_clear(lun, initidx);
11845 		/* Establish UA. */
11846 		ctl_est_ua(lun, initidx, ua_type);
11847 		mtx_unlock(&lun->lun_lock);
11848 	}
11849 	mtx_unlock(&softc->ctl_lock);
11850 }
11851 
11852 static int
11853 ctl_i_t_nexus_reset(union ctl_io *io)
11854 {
11855 	struct ctl_softc *softc = CTL_SOFTC(io);
11856 	uint32_t initidx;
11857 
11858 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11859 		union ctl_ha_msg msg_info;
11860 
11861 		msg_info.hdr.nexus = io->io_hdr.nexus;
11862 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11863 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11864 		msg_info.hdr.original_sc = NULL;
11865 		msg_info.hdr.serializing_sc = NULL;
11866 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11867 		    sizeof(msg_info.task), M_WAITOK);
11868 	}
11869 
11870 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11871 	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
11872 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11873 	return (0);
11874 }
11875 
11876 static int
11877 ctl_abort_task(union ctl_io *io)
11878 {
11879 	struct ctl_softc *softc = CTL_SOFTC(io);
11880 	union ctl_io *xio;
11881 	struct ctl_lun *lun;
11882 	uint32_t targ_lun;
11883 
11884 	/*
11885 	 * Look up the LUN.
11886 	 */
11887 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11888 	mtx_lock(&softc->ctl_lock);
11889 	if (targ_lun >= ctl_max_luns ||
11890 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11891 		mtx_unlock(&softc->ctl_lock);
11892 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11893 		return (1);
11894 	}
11895 
11896 	mtx_lock(&lun->lun_lock);
11897 	mtx_unlock(&softc->ctl_lock);
11898 	/*
11899 	 * Run through the OOA queue and attempt to find the given I/O.
11900 	 * The target port, initiator ID, tag type and tag number have to
11901 	 * match the values that we got from the initiator.  If we have an
11902 	 * untagged command to abort, simply abort the first untagged command
11903 	 * we come to.  We only allow one untagged command at a time of course.
11904 	 */
11905 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11906 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11907 
11908 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11909 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11910 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11911 			continue;
11912 
11913 		/*
11914 		 * If the abort says that the task is untagged, the
11915 		 * task in the queue must be untagged.  Otherwise,
11916 		 * we just check to see whether the tag numbers
11917 		 * match.  This is because the QLogic firmware
11918 		 * doesn't pass back the tag type in an abort
11919 		 * request.
11920 		 */
11921 #if 0
11922 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11923 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11924 		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
11925 #else
11926 		/*
11927 		 * XXX KDM we've got problems with FC, because it
11928 		 * doesn't send down a tag type with aborts.  So we
11929 		 * can only really go by the tag number...
11930 		 * This may cause problems with parallel SCSI.
11931 		 * Need to figure that out!!
11932 		 */
11933 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
11934 #endif
11935 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11936 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11937 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11938 				union ctl_ha_msg msg_info;
11939 
11940 				msg_info.hdr.nexus = io->io_hdr.nexus;
11941 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11942 				msg_info.task.tag_num = io->taskio.tag_num;
11943 				msg_info.task.tag_type = io->taskio.tag_type;
11944 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11945 				msg_info.hdr.original_sc = NULL;
11946 				msg_info.hdr.serializing_sc = NULL;
11947 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11948 				    sizeof(msg_info.task), M_NOWAIT);
11949 			}
11950 			ctl_try_unblock_io(lun, xio, FALSE);
11951 		}
11952 	}
11953 	mtx_unlock(&lun->lun_lock);
11954 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11955 	return (0);
11956 }
11957 
11958 static int
11959 ctl_query_task(union ctl_io *io, int task_set)
11960 {
11961 	struct ctl_softc *softc = CTL_SOFTC(io);
11962 	union ctl_io *xio;
11963 	struct ctl_lun *lun;
11964 	int found = 0;
11965 	uint32_t targ_lun;
11966 
11967 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11968 	mtx_lock(&softc->ctl_lock);
11969 	if (targ_lun >= ctl_max_luns ||
11970 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11971 		mtx_unlock(&softc->ctl_lock);
11972 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11973 		return (1);
11974 	}
11975 	mtx_lock(&lun->lun_lock);
11976 	mtx_unlock(&softc->ctl_lock);
11977 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11978 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11979 
11980 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11981 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11982 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11983 			continue;
11984 
11985 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
11986 			found = 1;
11987 			break;
11988 		}
11989 	}
11990 	mtx_unlock(&lun->lun_lock);
11991 	if (found)
11992 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
11993 	else
11994 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11995 	return (0);
11996 }
11997 
11998 static int
11999 ctl_query_async_event(union ctl_io *io)
12000 {
12001 	struct ctl_softc *softc = CTL_SOFTC(io);
12002 	struct ctl_lun *lun;
12003 	ctl_ua_type ua;
12004 	uint32_t targ_lun, initidx;
12005 
12006 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12007 	mtx_lock(&softc->ctl_lock);
12008 	if (targ_lun >= ctl_max_luns ||
12009 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12010 		mtx_unlock(&softc->ctl_lock);
12011 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12012 		return (1);
12013 	}
12014 	mtx_lock(&lun->lun_lock);
12015 	mtx_unlock(&softc->ctl_lock);
12016 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12017 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12018 	mtx_unlock(&lun->lun_lock);
12019 	if (ua != CTL_UA_NONE)
12020 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12021 	else
12022 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12023 	return (0);
12024 }
12025 
12026 static void
12027 ctl_run_task(union ctl_io *io)
12028 {
12029 	int retval = 1;
12030 
12031 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12032 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12033 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12034 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12035 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12036 	switch (io->taskio.task_action) {
12037 	case CTL_TASK_ABORT_TASK:
12038 		retval = ctl_abort_task(io);
12039 		break;
12040 	case CTL_TASK_ABORT_TASK_SET:
12041 	case CTL_TASK_CLEAR_TASK_SET:
12042 		retval = ctl_abort_task_set(io);
12043 		break;
12044 	case CTL_TASK_CLEAR_ACA:
12045 		break;
12046 	case CTL_TASK_I_T_NEXUS_RESET:
12047 		retval = ctl_i_t_nexus_reset(io);
12048 		break;
12049 	case CTL_TASK_LUN_RESET:
12050 		retval = ctl_lun_reset(io);
12051 		break;
12052 	case CTL_TASK_TARGET_RESET:
12053 	case CTL_TASK_BUS_RESET:
12054 		retval = ctl_target_reset(io);
12055 		break;
12056 	case CTL_TASK_PORT_LOGIN:
12057 		break;
12058 	case CTL_TASK_PORT_LOGOUT:
12059 		break;
12060 	case CTL_TASK_QUERY_TASK:
12061 		retval = ctl_query_task(io, 0);
12062 		break;
12063 	case CTL_TASK_QUERY_TASK_SET:
12064 		retval = ctl_query_task(io, 1);
12065 		break;
12066 	case CTL_TASK_QUERY_ASYNC_EVENT:
12067 		retval = ctl_query_async_event(io);
12068 		break;
12069 	default:
12070 		printf("%s: got unknown task management event %d\n",
12071 		       __func__, io->taskio.task_action);
12072 		break;
12073 	}
12074 	if (retval == 0)
12075 		io->io_hdr.status = CTL_SUCCESS;
12076 	else
12077 		io->io_hdr.status = CTL_ERROR;
12078 	ctl_done(io);
12079 }
12080 
12081 /*
12082  * For HA operation.  Handle commands that come in from the other
12083  * controller.
12084  */
12085 static void
12086 ctl_handle_isc(union ctl_io *io)
12087 {
12088 	struct ctl_softc *softc = CTL_SOFTC(io);
12089 	struct ctl_lun *lun;
12090 	const struct ctl_cmd_entry *entry;
12091 	uint32_t targ_lun;
12092 
12093 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12094 	switch (io->io_hdr.msg_type) {
12095 	case CTL_MSG_SERIALIZE:
12096 		ctl_serialize_other_sc_cmd(&io->scsiio);
12097 		break;
12098 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12099 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12100 		if (targ_lun >= ctl_max_luns ||
12101 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12102 			ctl_done(io);
12103 			break;
12104 		}
12105 		mtx_lock(&lun->lun_lock);
12106 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12107 			mtx_unlock(&lun->lun_lock);
12108 			ctl_done(io);
12109 			break;
12110 		}
12111 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12112 		mtx_unlock(&lun->lun_lock);
12113 		ctl_enqueue_rtr(io);
12114 		break;
12115 	case CTL_MSG_FINISH_IO:
12116 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12117 			ctl_done(io);
12118 			break;
12119 		}
12120 		if (targ_lun >= ctl_max_luns ||
12121 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12122 			ctl_free_io(io);
12123 			break;
12124 		}
12125 		mtx_lock(&lun->lun_lock);
12126 		ctl_try_unblock_others(lun, io, TRUE);
12127 		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12128 		mtx_unlock(&lun->lun_lock);
12129 		ctl_free_io(io);
12130 		break;
12131 	case CTL_MSG_PERS_ACTION:
12132 		ctl_hndl_per_res_out_on_other_sc(io);
12133 		ctl_free_io(io);
12134 		break;
12135 	case CTL_MSG_BAD_JUJU:
12136 		ctl_done(io);
12137 		break;
12138 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12139 		ctl_datamove_remote(io);
12140 		break;
12141 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12142 		io->scsiio.be_move_done(io);
12143 		break;
12144 	case CTL_MSG_FAILOVER:
12145 		ctl_failover_lun(io);
12146 		ctl_free_io(io);
12147 		break;
12148 	default:
12149 		printf("%s: Invalid message type %d\n",
12150 		       __func__, io->io_hdr.msg_type);
12151 		ctl_free_io(io);
12152 		break;
12153 	}
12154 
12155 }
12156 
12157 
12158 /*
12159  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12160  * there is no match.
12161  */
12162 static ctl_lun_error_pattern
12163 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12164 {
12165 	const struct ctl_cmd_entry *entry;
12166 	ctl_lun_error_pattern filtered_pattern, pattern;
12167 
12168 	pattern = desc->error_pattern;
12169 
12170 	/*
12171 	 * XXX KDM we need more data passed into this function to match a
12172 	 * custom pattern, and we actually need to implement custom pattern
12173 	 * matching.
12174 	 */
12175 	if (pattern & CTL_LUN_PAT_CMD)
12176 		return (CTL_LUN_PAT_CMD);
12177 
12178 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12179 		return (CTL_LUN_PAT_ANY);
12180 
12181 	entry = ctl_get_cmd_entry(ctsio, NULL);
12182 
12183 	filtered_pattern = entry->pattern & pattern;
12184 
12185 	/*
12186 	 * If the user requested specific flags in the pattern (e.g.
12187 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12188 	 * flags.
12189 	 *
12190 	 * If the user did not specify any flags, it doesn't matter whether
12191 	 * or not the command supports the flags.
12192 	 */
12193 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12194 	     (pattern & ~CTL_LUN_PAT_MASK))
12195 		return (CTL_LUN_PAT_NONE);
12196 
12197 	/*
12198 	 * If the user asked for a range check, see if the requested LBA
12199 	 * range overlaps with this command's LBA range.
12200 	 */
12201 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12202 		uint64_t lba1;
12203 		uint64_t len1;
12204 		ctl_action action;
12205 		int retval;
12206 
12207 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12208 		if (retval != 0)
12209 			return (CTL_LUN_PAT_NONE);
12210 
12211 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12212 					      desc->lba_range.len, FALSE);
12213 		/*
12214 		 * A "pass" means that the LBA ranges don't overlap, so
12215 		 * this doesn't match the user's range criteria.
12216 		 */
12217 		if (action == CTL_ACTION_PASS)
12218 			return (CTL_LUN_PAT_NONE);
12219 	}
12220 
12221 	return (filtered_pattern);
12222 }
12223 
12224 static void
12225 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12226 {
12227 	struct ctl_error_desc *desc, *desc2;
12228 
12229 	mtx_assert(&lun->lun_lock, MA_OWNED);
12230 
12231 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12232 		ctl_lun_error_pattern pattern;
12233 		/*
12234 		 * Check to see whether this particular command matches
12235 		 * the pattern in the descriptor.
12236 		 */
12237 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12238 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12239 			continue;
12240 
12241 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12242 		case CTL_LUN_INJ_ABORTED:
12243 			ctl_set_aborted(&io->scsiio);
12244 			break;
12245 		case CTL_LUN_INJ_MEDIUM_ERR:
12246 			ctl_set_medium_error(&io->scsiio,
12247 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12248 			     CTL_FLAG_DATA_OUT);
12249 			break;
12250 		case CTL_LUN_INJ_UA:
12251 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12252 			 * OCCURRED */
12253 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12254 			break;
12255 		case CTL_LUN_INJ_CUSTOM:
12256 			/*
12257 			 * We're assuming the user knows what he is doing.
12258 			 * Just copy the sense information without doing
12259 			 * checks.
12260 			 */
12261 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12262 			      MIN(sizeof(desc->custom_sense),
12263 				  sizeof(io->scsiio.sense_data)));
12264 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12265 			io->scsiio.sense_len = SSD_FULL_SIZE;
12266 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12267 			break;
12268 		case CTL_LUN_INJ_NONE:
12269 		default:
12270 			/*
12271 			 * If this is an error injection type we don't know
12272 			 * about, clear the continuous flag (if it is set)
12273 			 * so it will get deleted below.
12274 			 */
12275 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12276 			break;
12277 		}
12278 		/*
12279 		 * By default, each error injection action is a one-shot
12280 		 */
12281 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12282 			continue;
12283 
12284 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12285 
12286 		free(desc, M_CTL);
12287 	}
12288 }
12289 
12290 #ifdef CTL_IO_DELAY
12291 static void
12292 ctl_datamove_timer_wakeup(void *arg)
12293 {
12294 	union ctl_io *io;
12295 
12296 	io = (union ctl_io *)arg;
12297 
12298 	ctl_datamove(io);
12299 }
12300 #endif /* CTL_IO_DELAY */
12301 
12302 void
12303 ctl_datamove(union ctl_io *io)
12304 {
12305 	void (*fe_datamove)(union ctl_io *io);
12306 
12307 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12308 
12309 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12310 
12311 	/* No data transferred yet.  Frontend must update this when done. */
12312 	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12313 
12314 #ifdef CTL_TIME_IO
12315 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12316 		char str[256];
12317 		char path_str[64];
12318 		struct sbuf sb;
12319 
12320 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12321 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12322 
12323 		sbuf_cat(&sb, path_str);
12324 		switch (io->io_hdr.io_type) {
12325 		case CTL_IO_SCSI:
12326 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12327 			sbuf_printf(&sb, "\n");
12328 			sbuf_cat(&sb, path_str);
12329 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12330 				    io->scsiio.tag_num, io->scsiio.tag_type);
12331 			break;
12332 		case CTL_IO_TASK:
12333 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12334 				    "Tag Type: %d\n", io->taskio.task_action,
12335 				    io->taskio.tag_num, io->taskio.tag_type);
12336 			break;
12337 		default:
12338 			panic("%s: Invalid CTL I/O type %d\n",
12339 			    __func__, io->io_hdr.io_type);
12340 		}
12341 		sbuf_cat(&sb, path_str);
12342 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12343 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12344 		sbuf_finish(&sb);
12345 		printf("%s", sbuf_data(&sb));
12346 	}
12347 #endif /* CTL_TIME_IO */
12348 
12349 #ifdef CTL_IO_DELAY
12350 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12351 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12352 	} else {
12353 		struct ctl_lun *lun;
12354 
12355 		lun = CTL_LUN(io);
12356 		if ((lun != NULL)
12357 		 && (lun->delay_info.datamove_delay > 0)) {
12358 
12359 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12360 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12361 			callout_reset(&io->io_hdr.delay_callout,
12362 				      lun->delay_info.datamove_delay * hz,
12363 				      ctl_datamove_timer_wakeup, io);
12364 			if (lun->delay_info.datamove_type ==
12365 			    CTL_DELAY_TYPE_ONESHOT)
12366 				lun->delay_info.datamove_delay = 0;
12367 			return;
12368 		}
12369 	}
12370 #endif
12371 
12372 	/*
12373 	 * This command has been aborted.  Set the port status, so we fail
12374 	 * the data move.
12375 	 */
12376 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12377 		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12378 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12379 		       io->io_hdr.nexus.targ_port,
12380 		       io->io_hdr.nexus.targ_lun);
12381 		io->io_hdr.port_status = 31337;
12382 		/*
12383 		 * Note that the backend, in this case, will get the
12384 		 * callback in its context.  In other cases it may get
12385 		 * called in the frontend's interrupt thread context.
12386 		 */
12387 		io->scsiio.be_move_done(io);
12388 		return;
12389 	}
12390 
12391 	/* Don't confuse frontend with zero length data move. */
12392 	if (io->scsiio.kern_data_len == 0) {
12393 		io->scsiio.be_move_done(io);
12394 		return;
12395 	}
12396 
12397 	fe_datamove = CTL_PORT(io)->fe_datamove;
12398 	fe_datamove(io);
12399 }
12400 
12401 static void
12402 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12403 {
12404 	union ctl_ha_msg msg;
12405 #ifdef CTL_TIME_IO
12406 	struct bintime cur_bt;
12407 #endif
12408 
12409 	memset(&msg, 0, sizeof(msg));
12410 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12411 	msg.hdr.original_sc = io;
12412 	msg.hdr.serializing_sc = io->io_hdr.remote_io;
12413 	msg.hdr.nexus = io->io_hdr.nexus;
12414 	msg.hdr.status = io->io_hdr.status;
12415 	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12416 	msg.scsi.tag_num = io->scsiio.tag_num;
12417 	msg.scsi.tag_type = io->scsiio.tag_type;
12418 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12419 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12420 	       io->scsiio.sense_len);
12421 	msg.scsi.sense_len = io->scsiio.sense_len;
12422 	msg.scsi.port_status = io->io_hdr.port_status;
12423 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12424 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12425 		ctl_failover_io(io, /*have_lock*/ have_lock);
12426 		return;
12427 	}
12428 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12429 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12430 	    msg.scsi.sense_len, M_WAITOK);
12431 
12432 #ifdef CTL_TIME_IO
12433 	getbinuptime(&cur_bt);
12434 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12435 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12436 #endif
12437 	io->io_hdr.num_dmas++;
12438 }
12439 
12440 /*
12441  * The DMA to the remote side is done, now we need to tell the other side
12442  * we're done so it can continue with its data movement.
12443  */
12444 static void
12445 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12446 {
12447 	union ctl_io *io;
12448 	uint32_t i;
12449 
12450 	io = rq->context;
12451 
12452 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12453 		printf("%s: ISC DMA write failed with error %d", __func__,
12454 		       rq->ret);
12455 		ctl_set_internal_failure(&io->scsiio,
12456 					 /*sks_valid*/ 1,
12457 					 /*retry_count*/ rq->ret);
12458 	}
12459 
12460 	ctl_dt_req_free(rq);
12461 
12462 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12463 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12464 	free(CTL_RSGL(io), M_CTL);
12465 	CTL_RSGL(io) = NULL;
12466 	CTL_LSGL(io) = NULL;
12467 
12468 	/*
12469 	 * The data is in local and remote memory, so now we need to send
12470 	 * status (good or back) back to the other side.
12471 	 */
12472 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12473 }
12474 
12475 /*
12476  * We've moved the data from the host/controller into local memory.  Now we
12477  * need to push it over to the remote controller's memory.
12478  */
12479 static int
12480 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12481 {
12482 	int retval;
12483 
12484 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12485 					  ctl_datamove_remote_write_cb);
12486 	return (retval);
12487 }
12488 
12489 static void
12490 ctl_datamove_remote_write(union ctl_io *io)
12491 {
12492 	int retval;
12493 	void (*fe_datamove)(union ctl_io *io);
12494 
12495 	/*
12496 	 * - Get the data from the host/HBA into local memory.
12497 	 * - DMA memory from the local controller to the remote controller.
12498 	 * - Send status back to the remote controller.
12499 	 */
12500 
12501 	retval = ctl_datamove_remote_sgl_setup(io);
12502 	if (retval != 0)
12503 		return;
12504 
12505 	/* Switch the pointer over so the FETD knows what to do */
12506 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12507 
12508 	/*
12509 	 * Use a custom move done callback, since we need to send completion
12510 	 * back to the other controller, not to the backend on this side.
12511 	 */
12512 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12513 
12514 	fe_datamove = CTL_PORT(io)->fe_datamove;
12515 	fe_datamove(io);
12516 }
12517 
12518 static int
12519 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12520 {
12521 	uint32_t i;
12522 
12523 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12524 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12525 	free(CTL_RSGL(io), M_CTL);
12526 	CTL_RSGL(io) = NULL;
12527 	CTL_LSGL(io) = NULL;
12528 
12529 	/*
12530 	 * The read is done, now we need to send status (good or bad) back
12531 	 * to the other side.
12532 	 */
12533 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12534 
12535 	return (0);
12536 }
12537 
12538 static void
12539 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12540 {
12541 	union ctl_io *io;
12542 	void (*fe_datamove)(union ctl_io *io);
12543 
12544 	io = rq->context;
12545 
12546 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12547 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12548 		       rq->ret);
12549 		ctl_set_internal_failure(&io->scsiio,
12550 					 /*sks_valid*/ 1,
12551 					 /*retry_count*/ rq->ret);
12552 	}
12553 
12554 	ctl_dt_req_free(rq);
12555 
12556 	/* Switch the pointer over so the FETD knows what to do */
12557 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12558 
12559 	/*
12560 	 * Use a custom move done callback, since we need to send completion
12561 	 * back to the other controller, not to the backend on this side.
12562 	 */
12563 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12564 
12565 	/* XXX KDM add checks like the ones in ctl_datamove? */
12566 
12567 	fe_datamove = CTL_PORT(io)->fe_datamove;
12568 	fe_datamove(io);
12569 }
12570 
12571 static int
12572 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12573 {
12574 	struct ctl_sg_entry *local_sglist;
12575 	uint32_t len_to_go;
12576 	int retval;
12577 	int i;
12578 
12579 	retval = 0;
12580 	local_sglist = CTL_LSGL(io);
12581 	len_to_go = io->scsiio.kern_data_len;
12582 
12583 	/*
12584 	 * The difficult thing here is that the size of the various
12585 	 * S/G segments may be different than the size from the
12586 	 * remote controller.  That'll make it harder when DMAing
12587 	 * the data back to the other side.
12588 	 */
12589 	for (i = 0; len_to_go > 0; i++) {
12590 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12591 		local_sglist[i].addr =
12592 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12593 
12594 		len_to_go -= local_sglist[i].len;
12595 	}
12596 	/*
12597 	 * Reset the number of S/G entries accordingly.  The original
12598 	 * number of S/G entries is available in rem_sg_entries.
12599 	 */
12600 	io->scsiio.kern_sg_entries = i;
12601 
12602 	return (retval);
12603 }
12604 
12605 static int
12606 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12607 			 ctl_ha_dt_cb callback)
12608 {
12609 	struct ctl_ha_dt_req *rq;
12610 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12611 	uint32_t local_used, remote_used, total_used;
12612 	int i, j, isc_ret;
12613 
12614 	rq = ctl_dt_req_alloc();
12615 
12616 	/*
12617 	 * If we failed to allocate the request, and if the DMA didn't fail
12618 	 * anyway, set busy status.  This is just a resource allocation
12619 	 * failure.
12620 	 */
12621 	if ((rq == NULL)
12622 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12623 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12624 		ctl_set_busy(&io->scsiio);
12625 
12626 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12627 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12628 
12629 		if (rq != NULL)
12630 			ctl_dt_req_free(rq);
12631 
12632 		/*
12633 		 * The data move failed.  We need to return status back
12634 		 * to the other controller.  No point in trying to DMA
12635 		 * data to the remote controller.
12636 		 */
12637 
12638 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12639 
12640 		return (1);
12641 	}
12642 
12643 	local_sglist = CTL_LSGL(io);
12644 	remote_sglist = CTL_RSGL(io);
12645 	local_used = 0;
12646 	remote_used = 0;
12647 	total_used = 0;
12648 
12649 	/*
12650 	 * Pull/push the data over the wire from/to the other controller.
12651 	 * This takes into account the possibility that the local and
12652 	 * remote sglists may not be identical in terms of the size of
12653 	 * the elements and the number of elements.
12654 	 *
12655 	 * One fundamental assumption here is that the length allocated for
12656 	 * both the local and remote sglists is identical.  Otherwise, we've
12657 	 * essentially got a coding error of some sort.
12658 	 */
12659 	isc_ret = CTL_HA_STATUS_SUCCESS;
12660 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12661 		uint32_t cur_len;
12662 		uint8_t *tmp_ptr;
12663 
12664 		rq->command = command;
12665 		rq->context = io;
12666 
12667 		/*
12668 		 * Both pointers should be aligned.  But it is possible
12669 		 * that the allocation length is not.  They should both
12670 		 * also have enough slack left over at the end, though,
12671 		 * to round up to the next 8 byte boundary.
12672 		 */
12673 		cur_len = MIN(local_sglist[i].len - local_used,
12674 			      remote_sglist[j].len - remote_used);
12675 		rq->size = cur_len;
12676 
12677 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12678 		tmp_ptr += local_used;
12679 
12680 #if 0
12681 		/* Use physical addresses when talking to ISC hardware */
12682 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12683 			/* XXX KDM use busdma */
12684 			rq->local = vtophys(tmp_ptr);
12685 		} else
12686 			rq->local = tmp_ptr;
12687 #else
12688 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12689 		    ("HA does not support BUS_ADDR"));
12690 		rq->local = tmp_ptr;
12691 #endif
12692 
12693 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12694 		tmp_ptr += remote_used;
12695 		rq->remote = tmp_ptr;
12696 
12697 		rq->callback = NULL;
12698 
12699 		local_used += cur_len;
12700 		if (local_used >= local_sglist[i].len) {
12701 			i++;
12702 			local_used = 0;
12703 		}
12704 
12705 		remote_used += cur_len;
12706 		if (remote_used >= remote_sglist[j].len) {
12707 			j++;
12708 			remote_used = 0;
12709 		}
12710 		total_used += cur_len;
12711 
12712 		if (total_used >= io->scsiio.kern_data_len)
12713 			rq->callback = callback;
12714 
12715 		isc_ret = ctl_dt_single(rq);
12716 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12717 			break;
12718 	}
12719 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12720 		rq->ret = isc_ret;
12721 		callback(rq);
12722 	}
12723 
12724 	return (0);
12725 }
12726 
12727 static void
12728 ctl_datamove_remote_read(union ctl_io *io)
12729 {
12730 	int retval;
12731 	uint32_t i;
12732 
12733 	/*
12734 	 * This will send an error to the other controller in the case of a
12735 	 * failure.
12736 	 */
12737 	retval = ctl_datamove_remote_sgl_setup(io);
12738 	if (retval != 0)
12739 		return;
12740 
12741 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12742 					  ctl_datamove_remote_read_cb);
12743 	if (retval != 0) {
12744 		/*
12745 		 * Make sure we free memory if there was an error..  The
12746 		 * ctl_datamove_remote_xfer() function will send the
12747 		 * datamove done message, or call the callback with an
12748 		 * error if there is a problem.
12749 		 */
12750 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12751 			free(CTL_LSGLT(io)[i].addr, M_CTL);
12752 		free(CTL_RSGL(io), M_CTL);
12753 		CTL_RSGL(io) = NULL;
12754 		CTL_LSGL(io) = NULL;
12755 	}
12756 }
12757 
12758 /*
12759  * Process a datamove request from the other controller.  This is used for
12760  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12761  * first.  Once that is complete, the data gets DMAed into the remote
12762  * controller's memory.  For reads, we DMA from the remote controller's
12763  * memory into our memory first, and then move it out to the FETD.
12764  */
12765 static void
12766 ctl_datamove_remote(union ctl_io *io)
12767 {
12768 
12769 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12770 
12771 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12772 		ctl_failover_io(io, /*have_lock*/ 0);
12773 		return;
12774 	}
12775 
12776 	/*
12777 	 * Note that we look for an aborted I/O here, but don't do some of
12778 	 * the other checks that ctl_datamove() normally does.
12779 	 * We don't need to run the datamove delay code, since that should
12780 	 * have been done if need be on the other controller.
12781 	 */
12782 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12783 		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12784 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12785 		       io->io_hdr.nexus.targ_port,
12786 		       io->io_hdr.nexus.targ_lun);
12787 		io->io_hdr.port_status = 31338;
12788 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12789 		return;
12790 	}
12791 
12792 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12793 		ctl_datamove_remote_write(io);
12794 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12795 		ctl_datamove_remote_read(io);
12796 	else {
12797 		io->io_hdr.port_status = 31339;
12798 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12799 	}
12800 }
12801 
12802 static void
12803 ctl_process_done(union ctl_io *io)
12804 {
12805 	struct ctl_softc *softc = CTL_SOFTC(io);
12806 	struct ctl_port *port = CTL_PORT(io);
12807 	struct ctl_lun *lun = CTL_LUN(io);
12808 	void (*fe_done)(union ctl_io *io);
12809 	union ctl_ha_msg msg;
12810 
12811 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12812 	fe_done = port->fe_done;
12813 
12814 #ifdef CTL_TIME_IO
12815 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12816 		char str[256];
12817 		char path_str[64];
12818 		struct sbuf sb;
12819 
12820 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12821 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12822 
12823 		sbuf_cat(&sb, path_str);
12824 		switch (io->io_hdr.io_type) {
12825 		case CTL_IO_SCSI:
12826 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12827 			sbuf_printf(&sb, "\n");
12828 			sbuf_cat(&sb, path_str);
12829 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12830 				    io->scsiio.tag_num, io->scsiio.tag_type);
12831 			break;
12832 		case CTL_IO_TASK:
12833 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12834 				    "Tag Type: %d\n", io->taskio.task_action,
12835 				    io->taskio.tag_num, io->taskio.tag_type);
12836 			break;
12837 		default:
12838 			panic("%s: Invalid CTL I/O type %d\n",
12839 			    __func__, io->io_hdr.io_type);
12840 		}
12841 		sbuf_cat(&sb, path_str);
12842 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12843 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12844 		sbuf_finish(&sb);
12845 		printf("%s", sbuf_data(&sb));
12846 	}
12847 #endif /* CTL_TIME_IO */
12848 
12849 	switch (io->io_hdr.io_type) {
12850 	case CTL_IO_SCSI:
12851 		break;
12852 	case CTL_IO_TASK:
12853 		if (ctl_debug & CTL_DEBUG_INFO)
12854 			ctl_io_error_print(io, NULL);
12855 		fe_done(io);
12856 		return;
12857 	default:
12858 		panic("%s: Invalid CTL I/O type %d\n",
12859 		    __func__, io->io_hdr.io_type);
12860 	}
12861 
12862 	if (lun == NULL) {
12863 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12864 				 io->io_hdr.nexus.targ_mapped_lun));
12865 		goto bailout;
12866 	}
12867 
12868 	mtx_lock(&lun->lun_lock);
12869 
12870 	/*
12871 	 * Check to see if we have any informational exception and status
12872 	 * of this command can be modified to report it in form of either
12873 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
12874 	 */
12875 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
12876 	    io->io_hdr.status == CTL_SUCCESS &&
12877 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
12878 		uint8_t mrie = lun->MODE_IE.mrie;
12879 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
12880 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
12881 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
12882 		     mrie == SIEP_MRIE_REC_UNCOND ||
12883 		     mrie == SIEP_MRIE_NO_SENSE) &&
12884 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
12885 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
12886 			ctl_set_sense(&io->scsiio,
12887 			      /*current_error*/ 1,
12888 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
12889 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
12890 			      /*asc*/ lun->ie_asc,
12891 			      /*ascq*/ lun->ie_ascq,
12892 			      SSD_ELEM_NONE);
12893 			lun->ie_reported = 1;
12894 		}
12895 	} else if (lun->ie_reported < 0)
12896 		lun->ie_reported = 0;
12897 
12898 	/*
12899 	 * Check to see if we have any errors to inject here.  We only
12900 	 * inject errors for commands that don't already have errors set.
12901 	 */
12902 	if (!STAILQ_EMPTY(&lun->error_list) &&
12903 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
12904 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
12905 		ctl_inject_error(lun, io);
12906 
12907 	/*
12908 	 * XXX KDM how do we treat commands that aren't completed
12909 	 * successfully?
12910 	 *
12911 	 * XXX KDM should we also track I/O latency?
12912 	 */
12913 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
12914 	    io->io_hdr.io_type == CTL_IO_SCSI) {
12915 		int type;
12916 #ifdef CTL_TIME_IO
12917 		struct bintime bt;
12918 
12919 		getbinuptime(&bt);
12920 		bintime_sub(&bt, &io->io_hdr.start_bt);
12921 #endif
12922 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12923 		    CTL_FLAG_DATA_IN)
12924 			type = CTL_STATS_READ;
12925 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12926 		    CTL_FLAG_DATA_OUT)
12927 			type = CTL_STATS_WRITE;
12928 		else
12929 			type = CTL_STATS_NO_IO;
12930 
12931 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
12932 		lun->stats.operations[type] ++;
12933 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
12934 #ifdef CTL_TIME_IO
12935 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
12936 		bintime_add(&lun->stats.time[type], &bt);
12937 #endif
12938 
12939 		mtx_lock(&port->port_lock);
12940 		port->stats.bytes[type] += io->scsiio.kern_total_len;
12941 		port->stats.operations[type] ++;
12942 		port->stats.dmas[type] += io->io_hdr.num_dmas;
12943 #ifdef CTL_TIME_IO
12944 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
12945 		bintime_add(&port->stats.time[type], &bt);
12946 #endif
12947 		mtx_unlock(&port->port_lock);
12948 	}
12949 
12950 	/*
12951 	 * Run through the blocked queue of this I/O and see if anything
12952 	 * can be unblocked, now that this I/O is done and will be removed.
12953 	 * We need to do it before removal to have OOA position to start.
12954 	 */
12955 	ctl_try_unblock_others(lun, io, TRUE);
12956 
12957 	/*
12958 	 * Remove this from the OOA queue.
12959 	 */
12960 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12961 #ifdef CTL_TIME_IO
12962 	if (TAILQ_EMPTY(&lun->ooa_queue))
12963 		lun->last_busy = getsbinuptime();
12964 #endif
12965 
12966 	/*
12967 	 * If the LUN has been invalidated, free it if there is nothing
12968 	 * left on its OOA queue.
12969 	 */
12970 	if ((lun->flags & CTL_LUN_INVALID)
12971 	 && TAILQ_EMPTY(&lun->ooa_queue)) {
12972 		mtx_unlock(&lun->lun_lock);
12973 		ctl_free_lun(lun);
12974 	} else
12975 		mtx_unlock(&lun->lun_lock);
12976 
12977 bailout:
12978 
12979 	/*
12980 	 * If this command has been aborted, make sure we set the status
12981 	 * properly.  The FETD is responsible for freeing the I/O and doing
12982 	 * whatever it needs to do to clean up its state.
12983 	 */
12984 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
12985 		ctl_set_task_aborted(&io->scsiio);
12986 
12987 	/*
12988 	 * If enabled, print command error status.
12989 	 */
12990 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
12991 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
12992 		ctl_io_error_print(io, NULL);
12993 
12994 	/*
12995 	 * Tell the FETD or the other shelf controller we're done with this
12996 	 * command.  Note that only SCSI commands get to this point.  Task
12997 	 * management commands are completed above.
12998 	 */
12999 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13000 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13001 		memset(&msg, 0, sizeof(msg));
13002 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13003 		msg.hdr.serializing_sc = io->io_hdr.remote_io;
13004 		msg.hdr.nexus = io->io_hdr.nexus;
13005 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13006 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13007 		    M_WAITOK);
13008 	}
13009 
13010 	fe_done(io);
13011 }
13012 
13013 /*
13014  * Front end should call this if it doesn't do autosense.  When the request
13015  * sense comes back in from the initiator, we'll dequeue this and send it.
13016  */
13017 int
13018 ctl_queue_sense(union ctl_io *io)
13019 {
13020 	struct ctl_softc *softc = CTL_SOFTC(io);
13021 	struct ctl_port *port = CTL_PORT(io);
13022 	struct ctl_lun *lun;
13023 	struct scsi_sense_data *ps;
13024 	uint32_t initidx, p, targ_lun;
13025 
13026 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13027 
13028 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13029 
13030 	/*
13031 	 * LUN lookup will likely move to the ctl_work_thread() once we
13032 	 * have our new queueing infrastructure (that doesn't put things on
13033 	 * a per-LUN queue initially).  That is so that we can handle
13034 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13035 	 * can't deal with that right now.
13036 	 * If we don't have a LUN for this, just toss the sense information.
13037 	 */
13038 	mtx_lock(&softc->ctl_lock);
13039 	if (targ_lun >= ctl_max_luns ||
13040 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13041 		mtx_unlock(&softc->ctl_lock);
13042 		goto bailout;
13043 	}
13044 	mtx_lock(&lun->lun_lock);
13045 	mtx_unlock(&softc->ctl_lock);
13046 
13047 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13048 	p = initidx / CTL_MAX_INIT_PER_PORT;
13049 	if (lun->pending_sense[p] == NULL) {
13050 		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13051 		    M_CTL, M_NOWAIT | M_ZERO);
13052 	}
13053 	if ((ps = lun->pending_sense[p]) != NULL) {
13054 		ps += initidx % CTL_MAX_INIT_PER_PORT;
13055 		memset(ps, 0, sizeof(*ps));
13056 		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13057 	}
13058 	mtx_unlock(&lun->lun_lock);
13059 
13060 bailout:
13061 	ctl_free_io(io);
13062 	return (CTL_RETVAL_COMPLETE);
13063 }
13064 
13065 /*
13066  * Primary command inlet from frontend ports.  All SCSI and task I/O
13067  * requests must go through this function.
13068  */
13069 int
13070 ctl_queue(union ctl_io *io)
13071 {
13072 	struct ctl_port *port = CTL_PORT(io);
13073 
13074 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13075 
13076 #ifdef CTL_TIME_IO
13077 	io->io_hdr.start_time = time_uptime;
13078 	getbinuptime(&io->io_hdr.start_bt);
13079 #endif /* CTL_TIME_IO */
13080 
13081 	/* Map FE-specific LUN ID into global one. */
13082 	io->io_hdr.nexus.targ_mapped_lun =
13083 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13084 
13085 	switch (io->io_hdr.io_type) {
13086 	case CTL_IO_SCSI:
13087 	case CTL_IO_TASK:
13088 		if (ctl_debug & CTL_DEBUG_CDB)
13089 			ctl_io_print(io);
13090 		ctl_enqueue_incoming(io);
13091 		break;
13092 	default:
13093 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13094 		return (EINVAL);
13095 	}
13096 
13097 	return (CTL_RETVAL_COMPLETE);
13098 }
13099 
13100 #ifdef CTL_IO_DELAY
13101 static void
13102 ctl_done_timer_wakeup(void *arg)
13103 {
13104 	union ctl_io *io;
13105 
13106 	io = (union ctl_io *)arg;
13107 	ctl_done(io);
13108 }
13109 #endif /* CTL_IO_DELAY */
13110 
13111 void
13112 ctl_serseq_done(union ctl_io *io)
13113 {
13114 	struct ctl_lun *lun = CTL_LUN(io);;
13115 
13116 	if (lun->be_lun == NULL ||
13117 	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13118 		return;
13119 	mtx_lock(&lun->lun_lock);
13120 	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13121 	ctl_try_unblock_others(lun, io, FALSE);
13122 	mtx_unlock(&lun->lun_lock);
13123 }
13124 
13125 void
13126 ctl_done(union ctl_io *io)
13127 {
13128 
13129 	/*
13130 	 * Enable this to catch duplicate completion issues.
13131 	 */
13132 #if 0
13133 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13134 		printf("%s: type %d msg %d cdb %x iptl: "
13135 		       "%u:%u:%u tag 0x%04x "
13136 		       "flag %#x status %x\n",
13137 			__func__,
13138 			io->io_hdr.io_type,
13139 			io->io_hdr.msg_type,
13140 			io->scsiio.cdb[0],
13141 			io->io_hdr.nexus.initid,
13142 			io->io_hdr.nexus.targ_port,
13143 			io->io_hdr.nexus.targ_lun,
13144 			(io->io_hdr.io_type ==
13145 			CTL_IO_TASK) ?
13146 			io->taskio.tag_num :
13147 			io->scsiio.tag_num,
13148 		        io->io_hdr.flags,
13149 			io->io_hdr.status);
13150 	} else
13151 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13152 #endif
13153 
13154 	/*
13155 	 * This is an internal copy of an I/O, and should not go through
13156 	 * the normal done processing logic.
13157 	 */
13158 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13159 		return;
13160 
13161 #ifdef CTL_IO_DELAY
13162 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13163 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13164 	} else {
13165 		struct ctl_lun *lun = CTL_LUN(io);
13166 
13167 		if ((lun != NULL)
13168 		 && (lun->delay_info.done_delay > 0)) {
13169 
13170 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13171 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13172 			callout_reset(&io->io_hdr.delay_callout,
13173 				      lun->delay_info.done_delay * hz,
13174 				      ctl_done_timer_wakeup, io);
13175 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13176 				lun->delay_info.done_delay = 0;
13177 			return;
13178 		}
13179 	}
13180 #endif /* CTL_IO_DELAY */
13181 
13182 	ctl_enqueue_done(io);
13183 }
13184 
13185 static void
13186 ctl_work_thread(void *arg)
13187 {
13188 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13189 	struct ctl_softc *softc = thr->ctl_softc;
13190 	union ctl_io *io;
13191 	int retval;
13192 
13193 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13194 
13195 	while (!softc->shutdown) {
13196 		/*
13197 		 * We handle the queues in this order:
13198 		 * - ISC
13199 		 * - done queue (to free up resources, unblock other commands)
13200 		 * - incoming queue
13201 		 * - RtR queue
13202 		 *
13203 		 * If those queues are empty, we break out of the loop and
13204 		 * go to sleep.
13205 		 */
13206 		mtx_lock(&thr->queue_lock);
13207 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13208 		if (io != NULL) {
13209 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13210 			mtx_unlock(&thr->queue_lock);
13211 			ctl_handle_isc(io);
13212 			continue;
13213 		}
13214 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13215 		if (io != NULL) {
13216 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13217 			/* clear any blocked commands, call fe_done */
13218 			mtx_unlock(&thr->queue_lock);
13219 			ctl_process_done(io);
13220 			continue;
13221 		}
13222 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13223 		if (io != NULL) {
13224 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13225 			mtx_unlock(&thr->queue_lock);
13226 			if (io->io_hdr.io_type == CTL_IO_TASK)
13227 				ctl_run_task(io);
13228 			else
13229 				ctl_scsiio_precheck(softc, &io->scsiio);
13230 			continue;
13231 		}
13232 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13233 		if (io != NULL) {
13234 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13235 			mtx_unlock(&thr->queue_lock);
13236 			retval = ctl_scsiio(&io->scsiio);
13237 			if (retval != CTL_RETVAL_COMPLETE)
13238 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13239 			continue;
13240 		}
13241 
13242 		/* Sleep until we have something to do. */
13243 		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13244 	}
13245 	thr->thread = NULL;
13246 	kthread_exit();
13247 }
13248 
13249 static void
13250 ctl_lun_thread(void *arg)
13251 {
13252 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13253 	struct ctl_be_lun *be_lun;
13254 
13255 	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13256 
13257 	while (!softc->shutdown) {
13258 		mtx_lock(&softc->ctl_lock);
13259 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13260 		if (be_lun != NULL) {
13261 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13262 			mtx_unlock(&softc->ctl_lock);
13263 			ctl_create_lun(be_lun);
13264 			continue;
13265 		}
13266 
13267 		/* Sleep until we have something to do. */
13268 		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13269 		    PDROP | PRIBIO, "-", 0);
13270 	}
13271 	softc->lun_thread = NULL;
13272 	kthread_exit();
13273 }
13274 
13275 static void
13276 ctl_thresh_thread(void *arg)
13277 {
13278 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13279 	struct ctl_lun *lun;
13280 	struct ctl_logical_block_provisioning_page *page;
13281 	const char *attr;
13282 	union ctl_ha_msg msg;
13283 	uint64_t thres, val;
13284 	int i, e, set;
13285 
13286 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13287 
13288 	while (!softc->shutdown) {
13289 		mtx_lock(&softc->ctl_lock);
13290 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13291 			if ((lun->flags & CTL_LUN_DISABLED) ||
13292 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13293 			    lun->backend->lun_attr == NULL)
13294 				continue;
13295 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13296 			    softc->ha_mode == CTL_HA_MODE_XFER)
13297 				continue;
13298 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13299 				continue;
13300 			e = 0;
13301 			page = &lun->MODE_LBP;
13302 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13303 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13304 					continue;
13305 				thres = scsi_4btoul(page->descr[i].count);
13306 				thres <<= CTL_LBP_EXPONENT;
13307 				switch (page->descr[i].resource) {
13308 				case 0x01:
13309 					attr = "blocksavail";
13310 					break;
13311 				case 0x02:
13312 					attr = "blocksused";
13313 					break;
13314 				case 0xf1:
13315 					attr = "poolblocksavail";
13316 					break;
13317 				case 0xf2:
13318 					attr = "poolblocksused";
13319 					break;
13320 				default:
13321 					continue;
13322 				}
13323 				mtx_unlock(&softc->ctl_lock); // XXX
13324 				val = lun->backend->lun_attr(
13325 				    lun->be_lun->be_lun, attr);
13326 				mtx_lock(&softc->ctl_lock);
13327 				if (val == UINT64_MAX)
13328 					continue;
13329 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13330 				    == SLBPPD_ARMING_INC)
13331 					e = (val >= thres);
13332 				else
13333 					e = (val <= thres);
13334 				if (e)
13335 					break;
13336 			}
13337 			mtx_lock(&lun->lun_lock);
13338 			if (e) {
13339 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13340 				    (uint8_t *)page, lun->ua_tpt_info);
13341 				if (lun->lasttpt == 0 ||
13342 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13343 					lun->lasttpt = time_uptime;
13344 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13345 					set = 1;
13346 				} else
13347 					set = 0;
13348 			} else {
13349 				lun->lasttpt = 0;
13350 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13351 				set = -1;
13352 			}
13353 			mtx_unlock(&lun->lun_lock);
13354 			if (set != 0 &&
13355 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13356 				/* Send msg to other side. */
13357 				bzero(&msg.ua, sizeof(msg.ua));
13358 				msg.hdr.msg_type = CTL_MSG_UA;
13359 				msg.hdr.nexus.initid = -1;
13360 				msg.hdr.nexus.targ_port = -1;
13361 				msg.hdr.nexus.targ_lun = lun->lun;
13362 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13363 				msg.ua.ua_all = 1;
13364 				msg.ua.ua_set = (set > 0);
13365 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13366 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13367 				mtx_unlock(&softc->ctl_lock); // XXX
13368 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13369 				    sizeof(msg.ua), M_WAITOK);
13370 				mtx_lock(&softc->ctl_lock);
13371 			}
13372 		}
13373 		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13374 		    PDROP | PRIBIO, "-", CTL_LBP_PERIOD * hz);
13375 	}
13376 	softc->thresh_thread = NULL;
13377 	kthread_exit();
13378 }
13379 
13380 static void
13381 ctl_enqueue_incoming(union ctl_io *io)
13382 {
13383 	struct ctl_softc *softc = CTL_SOFTC(io);
13384 	struct ctl_thread *thr;
13385 	u_int idx;
13386 
13387 	idx = (io->io_hdr.nexus.targ_port * 127 +
13388 	       io->io_hdr.nexus.initid) % worker_threads;
13389 	thr = &softc->threads[idx];
13390 	mtx_lock(&thr->queue_lock);
13391 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13392 	mtx_unlock(&thr->queue_lock);
13393 	wakeup(thr);
13394 }
13395 
13396 static void
13397 ctl_enqueue_rtr(union ctl_io *io)
13398 {
13399 	struct ctl_softc *softc = CTL_SOFTC(io);
13400 	struct ctl_thread *thr;
13401 
13402 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13403 	mtx_lock(&thr->queue_lock);
13404 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13405 	mtx_unlock(&thr->queue_lock);
13406 	wakeup(thr);
13407 }
13408 
13409 static void
13410 ctl_enqueue_done(union ctl_io *io)
13411 {
13412 	struct ctl_softc *softc = CTL_SOFTC(io);
13413 	struct ctl_thread *thr;
13414 
13415 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13416 	mtx_lock(&thr->queue_lock);
13417 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13418 	mtx_unlock(&thr->queue_lock);
13419 	wakeup(thr);
13420 }
13421 
13422 static void
13423 ctl_enqueue_isc(union ctl_io *io)
13424 {
13425 	struct ctl_softc *softc = CTL_SOFTC(io);
13426 	struct ctl_thread *thr;
13427 
13428 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13429 	mtx_lock(&thr->queue_lock);
13430 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13431 	mtx_unlock(&thr->queue_lock);
13432 	wakeup(thr);
13433 }
13434 
13435 /*
13436  *  vim: ts=8
13437  */
13438