xref: /freebsd/sys/cam/ctl/ctl.c (revision 09606165a0ab82291c6443d5c82b205256c56458)
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * Copyright (c) 2014-2017 Alexander Motin <mav@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Portions of this software were developed by Edward Tomasz Napierala
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification.
16  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17  *    substantially similar to the "NO WARRANTY" disclaimer below
18  *    ("Disclaimer") and any redistribution must be conditioned upon
19  *    including a substantially similar Disclaimer requirement for further
20  *    binary redistribution.
21  *
22  * NO WARRANTY
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGES.
34  *
35  * $Id$
36  */
37 /*
38  * CAM Target Layer, a SCSI device emulation subsystem.
39  *
40  * Author: Ken Merry <ken@FreeBSD.org>
41  */
42 
43 #define _CTL_C
44 
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/ctype.h>
51 #include <sys/kernel.h>
52 #include <sys/types.h>
53 #include <sys/kthread.h>
54 #include <sys/bio.h>
55 #include <sys/fcntl.h>
56 #include <sys/lock.h>
57 #include <sys/module.h>
58 #include <sys/mutex.h>
59 #include <sys/condvar.h>
60 #include <sys/malloc.h>
61 #include <sys/conf.h>
62 #include <sys/ioccom.h>
63 #include <sys/queue.h>
64 #include <sys/sbuf.h>
65 #include <sys/smp.h>
66 #include <sys/endian.h>
67 #include <sys/sysctl.h>
68 #include <vm/uma.h>
69 
70 #include <cam/cam.h>
71 #include <cam/scsi/scsi_all.h>
72 #include <cam/scsi/scsi_cd.h>
73 #include <cam/scsi/scsi_da.h>
74 #include <cam/ctl/ctl_io.h>
75 #include <cam/ctl/ctl.h>
76 #include <cam/ctl/ctl_frontend.h>
77 #include <cam/ctl/ctl_util.h>
78 #include <cam/ctl/ctl_backend.h>
79 #include <cam/ctl/ctl_ioctl.h>
80 #include <cam/ctl/ctl_ha.h>
81 #include <cam/ctl/ctl_private.h>
82 #include <cam/ctl/ctl_debug.h>
83 #include <cam/ctl/ctl_scsi_all.h>
84 #include <cam/ctl/ctl_error.h>
85 
86 struct ctl_softc *control_softc = NULL;
87 
88 /*
89  * Template mode pages.
90  */
91 
92 /*
93  * Note that these are default values only.  The actual values will be
94  * filled in when the user does a mode sense.
95  */
96 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
97 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
98 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
99 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
100 	/*read_retry_count*/0,
101 	/*correction_span*/0,
102 	/*head_offset_count*/0,
103 	/*data_strobe_offset_cnt*/0,
104 	/*byte8*/SMS_RWER_LBPERE,
105 	/*write_retry_count*/0,
106 	/*reserved2*/0,
107 	/*recovery_time_limit*/{0, 0},
108 };
109 
110 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
111 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
112 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
113 	/*byte3*/SMS_RWER_PER,
114 	/*read_retry_count*/0,
115 	/*correction_span*/0,
116 	/*head_offset_count*/0,
117 	/*data_strobe_offset_cnt*/0,
118 	/*byte8*/SMS_RWER_LBPERE,
119 	/*write_retry_count*/0,
120 	/*reserved2*/0,
121 	/*recovery_time_limit*/{0, 0},
122 };
123 
124 const static struct scsi_format_page format_page_default = {
125 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
126 	/*page_length*/sizeof(struct scsi_format_page) - 2,
127 	/*tracks_per_zone*/ {0, 0},
128 	/*alt_sectors_per_zone*/ {0, 0},
129 	/*alt_tracks_per_zone*/ {0, 0},
130 	/*alt_tracks_per_lun*/ {0, 0},
131 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
132 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
133 	/*bytes_per_sector*/ {0, 0},
134 	/*interleave*/ {0, 0},
135 	/*track_skew*/ {0, 0},
136 	/*cylinder_skew*/ {0, 0},
137 	/*flags*/ SFP_HSEC,
138 	/*reserved*/ {0, 0, 0}
139 };
140 
141 const static struct scsi_format_page format_page_changeable = {
142 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
143 	/*page_length*/sizeof(struct scsi_format_page) - 2,
144 	/*tracks_per_zone*/ {0, 0},
145 	/*alt_sectors_per_zone*/ {0, 0},
146 	/*alt_tracks_per_zone*/ {0, 0},
147 	/*alt_tracks_per_lun*/ {0, 0},
148 	/*sectors_per_track*/ {0, 0},
149 	/*bytes_per_sector*/ {0, 0},
150 	/*interleave*/ {0, 0},
151 	/*track_skew*/ {0, 0},
152 	/*cylinder_skew*/ {0, 0},
153 	/*flags*/ 0,
154 	/*reserved*/ {0, 0, 0}
155 };
156 
157 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
158 	/*page_code*/SMS_RIGID_DISK_PAGE,
159 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
160 	/*cylinders*/ {0, 0, 0},
161 	/*heads*/ CTL_DEFAULT_HEADS,
162 	/*start_write_precomp*/ {0, 0, 0},
163 	/*start_reduced_current*/ {0, 0, 0},
164 	/*step_rate*/ {0, 0},
165 	/*landing_zone_cylinder*/ {0, 0, 0},
166 	/*rpl*/ SRDP_RPL_DISABLED,
167 	/*rotational_offset*/ 0,
168 	/*reserved1*/ 0,
169 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
170 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
171 	/*reserved2*/ {0, 0}
172 };
173 
174 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
175 	/*page_code*/SMS_RIGID_DISK_PAGE,
176 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
177 	/*cylinders*/ {0, 0, 0},
178 	/*heads*/ 0,
179 	/*start_write_precomp*/ {0, 0, 0},
180 	/*start_reduced_current*/ {0, 0, 0},
181 	/*step_rate*/ {0, 0},
182 	/*landing_zone_cylinder*/ {0, 0, 0},
183 	/*rpl*/ 0,
184 	/*rotational_offset*/ 0,
185 	/*reserved1*/ 0,
186 	/*rotation_rate*/ {0, 0},
187 	/*reserved2*/ {0, 0}
188 };
189 
190 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
191 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
192 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
193 	/*byte3*/0,
194 	/*read_retry_count*/0,
195 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
196 	/*recovery_time_limit*/{0, 0},
197 };
198 
199 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
200 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
201 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
202 	/*byte3*/SMS_VER_PER,
203 	/*read_retry_count*/0,
204 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
205 	/*recovery_time_limit*/{0, 0},
206 };
207 
208 const static struct scsi_caching_page caching_page_default = {
209 	/*page_code*/SMS_CACHING_PAGE,
210 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
211 	/*flags1*/ SCP_DISC | SCP_WCE,
212 	/*ret_priority*/ 0,
213 	/*disable_pf_transfer_len*/ {0xff, 0xff},
214 	/*min_prefetch*/ {0, 0},
215 	/*max_prefetch*/ {0xff, 0xff},
216 	/*max_pf_ceiling*/ {0xff, 0xff},
217 	/*flags2*/ 0,
218 	/*cache_segments*/ 0,
219 	/*cache_seg_size*/ {0, 0},
220 	/*reserved*/ 0,
221 	/*non_cache_seg_size*/ {0, 0, 0}
222 };
223 
224 const static struct scsi_caching_page caching_page_changeable = {
225 	/*page_code*/SMS_CACHING_PAGE,
226 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
227 	/*flags1*/ SCP_WCE | SCP_RCD,
228 	/*ret_priority*/ 0,
229 	/*disable_pf_transfer_len*/ {0, 0},
230 	/*min_prefetch*/ {0, 0},
231 	/*max_prefetch*/ {0, 0},
232 	/*max_pf_ceiling*/ {0, 0},
233 	/*flags2*/ 0,
234 	/*cache_segments*/ 0,
235 	/*cache_seg_size*/ {0, 0},
236 	/*reserved*/ 0,
237 	/*non_cache_seg_size*/ {0, 0, 0}
238 };
239 
240 const static struct scsi_control_page control_page_default = {
241 	/*page_code*/SMS_CONTROL_MODE_PAGE,
242 	/*page_length*/sizeof(struct scsi_control_page) - 2,
243 	/*rlec*/0,
244 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
245 	/*eca_and_aen*/0,
246 	/*flags4*/SCP_TAS,
247 	/*aen_holdoff_period*/{0, 0},
248 	/*busy_timeout_period*/{0, 0},
249 	/*extended_selftest_completion_time*/{0, 0}
250 };
251 
252 const static struct scsi_control_page control_page_changeable = {
253 	/*page_code*/SMS_CONTROL_MODE_PAGE,
254 	/*page_length*/sizeof(struct scsi_control_page) - 2,
255 	/*rlec*/SCP_DSENSE,
256 	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
257 	/*eca_and_aen*/SCP_SWP,
258 	/*flags4*/0,
259 	/*aen_holdoff_period*/{0, 0},
260 	/*busy_timeout_period*/{0, 0},
261 	/*extended_selftest_completion_time*/{0, 0}
262 };
263 
264 #define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
265 
266 const static struct scsi_control_ext_page control_ext_page_default = {
267 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
268 	/*subpage_code*/0x01,
269 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
270 	/*flags*/0,
271 	/*prio*/0,
272 	/*max_sense*/0
273 };
274 
275 const static struct scsi_control_ext_page control_ext_page_changeable = {
276 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
277 	/*subpage_code*/0x01,
278 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
279 	/*flags*/0,
280 	/*prio*/0,
281 	/*max_sense*/0xff
282 };
283 
284 const static struct scsi_info_exceptions_page ie_page_default = {
285 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
286 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
287 	/*info_flags*/SIEP_FLAGS_EWASC,
288 	/*mrie*/SIEP_MRIE_NO,
289 	/*interval_timer*/{0, 0, 0, 0},
290 	/*report_count*/{0, 0, 0, 1}
291 };
292 
293 const static struct scsi_info_exceptions_page ie_page_changeable = {
294 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
295 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
296 	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
297 	    SIEP_FLAGS_LOGERR,
298 	/*mrie*/0x0f,
299 	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
300 	/*report_count*/{0xff, 0xff, 0xff, 0xff}
301 };
302 
303 #define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
304 
305 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
306 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
307 	/*subpage_code*/0x02,
308 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
309 	/*flags*/0,
310 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
311 	/*descr*/{}},
312 	{{/*flags*/0,
313 	  /*resource*/0x01,
314 	  /*reserved*/{0, 0},
315 	  /*count*/{0, 0, 0, 0}},
316 	 {/*flags*/0,
317 	  /*resource*/0x02,
318 	  /*reserved*/{0, 0},
319 	  /*count*/{0, 0, 0, 0}},
320 	 {/*flags*/0,
321 	  /*resource*/0xf1,
322 	  /*reserved*/{0, 0},
323 	  /*count*/{0, 0, 0, 0}},
324 	 {/*flags*/0,
325 	  /*resource*/0xf2,
326 	  /*reserved*/{0, 0},
327 	  /*count*/{0, 0, 0, 0}}
328 	}
329 };
330 
331 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
332 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
333 	/*subpage_code*/0x02,
334 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
335 	/*flags*/SLBPP_SITUA,
336 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
337 	/*descr*/{}},
338 	{{/*flags*/0,
339 	  /*resource*/0,
340 	  /*reserved*/{0, 0},
341 	  /*count*/{0, 0, 0, 0}},
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 	}
355 };
356 
357 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
358 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
359 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
360 	/*caps1*/0x3f,
361 	/*caps2*/0x00,
362 	/*caps3*/0xf0,
363 	/*caps4*/0x00,
364 	/*caps5*/0x29,
365 	/*caps6*/0x00,
366 	/*obsolete*/{0, 0},
367 	/*nvol_levels*/{0, 0},
368 	/*buffer_size*/{8, 0},
369 	/*obsolete2*/{0, 0},
370 	/*reserved*/0,
371 	/*digital*/0,
372 	/*obsolete3*/0,
373 	/*copy_management*/0,
374 	/*reserved2*/0,
375 	/*rotation_control*/0,
376 	/*cur_write_speed*/0,
377 	/*num_speed_descr*/0,
378 };
379 
380 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
381 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
382 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
383 	/*caps1*/0,
384 	/*caps2*/0,
385 	/*caps3*/0,
386 	/*caps4*/0,
387 	/*caps5*/0,
388 	/*caps6*/0,
389 	/*obsolete*/{0, 0},
390 	/*nvol_levels*/{0, 0},
391 	/*buffer_size*/{0, 0},
392 	/*obsolete2*/{0, 0},
393 	/*reserved*/0,
394 	/*digital*/0,
395 	/*obsolete3*/0,
396 	/*copy_management*/0,
397 	/*reserved2*/0,
398 	/*rotation_control*/0,
399 	/*cur_write_speed*/0,
400 	/*num_speed_descr*/0,
401 };
402 
403 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
404 static int worker_threads = -1;
405 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
406     &worker_threads, 1, "Number of worker threads");
407 static int ctl_debug = CTL_DEBUG_NONE;
408 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
409     &ctl_debug, 0, "Enabled debug flags");
410 static int ctl_lun_map_size = 1024;
411 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
412     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
413 
414 /*
415  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
416  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
417  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
418  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
419  */
420 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
421 
422 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
423 				  int param);
424 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
425 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
426 static int ctl_init(void);
427 void ctl_shutdown(void);
428 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
429 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
430 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
431 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
432 			      struct ctl_ooa *ooa_hdr,
433 			      struct ctl_ooa_entry *kern_entries);
434 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
435 		     struct thread *td);
436 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
437 			 struct ctl_be_lun *be_lun);
438 static int ctl_free_lun(struct ctl_lun *lun);
439 static void ctl_create_lun(struct ctl_be_lun *be_lun);
440 
441 static int ctl_do_mode_select(union ctl_io *io);
442 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
443 			   uint64_t res_key, uint64_t sa_res_key,
444 			   uint8_t type, uint32_t residx,
445 			   struct ctl_scsiio *ctsio,
446 			   struct scsi_per_res_out *cdb,
447 			   struct scsi_per_res_out_parms* param);
448 static void ctl_pro_preempt_other(struct ctl_lun *lun,
449 				  union ctl_ha_msg *msg);
450 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
451 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
452 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
453 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
454 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
455 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
456 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
457 					 int alloc_len);
458 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
459 					 int alloc_len);
460 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
461 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
462 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
463 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
464 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
465 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
466     bool seq);
467 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
468 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
469     union ctl_io *pending_io, union ctl_io *ooa_io);
470 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
471 				union ctl_io *starting_io);
472 static int ctl_check_blocked(struct ctl_lun *lun);
473 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
474 				const struct ctl_cmd_entry *entry,
475 				struct ctl_scsiio *ctsio);
476 static void ctl_failover_lun(union ctl_io *io);
477 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
478 			       struct ctl_scsiio *ctsio);
479 static int ctl_scsiio(struct ctl_scsiio *ctsio);
480 
481 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
482 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
483 			    ctl_ua_type ua_type);
484 static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
485 			 ctl_ua_type ua_type);
486 static int ctl_lun_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
487 static int ctl_abort_task(union ctl_io *io);
488 static int ctl_abort_task_set(union ctl_io *io);
489 static int ctl_query_task(union ctl_io *io, int task_set);
490 static int ctl_i_t_nexus_reset(union ctl_io *io);
491 static int ctl_query_async_event(union ctl_io *io);
492 static void ctl_run_task(union ctl_io *io);
493 #ifdef CTL_IO_DELAY
494 static void ctl_datamove_timer_wakeup(void *arg);
495 static void ctl_done_timer_wakeup(void *arg);
496 #endif /* CTL_IO_DELAY */
497 
498 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
499 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
500 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
501 static void ctl_datamove_remote_write(union ctl_io *io);
502 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
503 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
504 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
505 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
506 				    ctl_ha_dt_cb callback);
507 static void ctl_datamove_remote_read(union ctl_io *io);
508 static void ctl_datamove_remote(union ctl_io *io);
509 static void ctl_process_done(union ctl_io *io);
510 static void ctl_lun_thread(void *arg);
511 static void ctl_thresh_thread(void *arg);
512 static void ctl_work_thread(void *arg);
513 static void ctl_enqueue_incoming(union ctl_io *io);
514 static void ctl_enqueue_rtr(union ctl_io *io);
515 static void ctl_enqueue_done(union ctl_io *io);
516 static void ctl_enqueue_isc(union ctl_io *io);
517 static const struct ctl_cmd_entry *
518     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
519 static const struct ctl_cmd_entry *
520     ctl_validate_command(struct ctl_scsiio *ctsio);
521 static int ctl_cmd_applicable(uint8_t lun_type,
522     const struct ctl_cmd_entry *entry);
523 
524 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
525 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
526 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
527 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
528 
529 /*
530  * Load the serialization table.  This isn't very pretty, but is probably
531  * the easiest way to do it.
532  */
533 #include "ctl_ser_table.c"
534 
535 /*
536  * We only need to define open, close and ioctl routines for this driver.
537  */
538 static struct cdevsw ctl_cdevsw = {
539 	.d_version =	D_VERSION,
540 	.d_flags =	0,
541 	.d_open =	ctl_open,
542 	.d_close =	ctl_close,
543 	.d_ioctl =	ctl_ioctl,
544 	.d_name =	"ctl",
545 };
546 
547 
548 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
549 
550 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
551 
552 static moduledata_t ctl_moduledata = {
553 	"ctl",
554 	ctl_module_event_handler,
555 	NULL
556 };
557 
558 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
559 MODULE_VERSION(ctl, 1);
560 
561 static struct ctl_frontend ha_frontend =
562 {
563 	.name = "ha",
564 };
565 
566 static void
567 ctl_ha_datamove(union ctl_io *io)
568 {
569 	struct ctl_lun *lun = CTL_LUN(io);
570 	struct ctl_sg_entry *sgl;
571 	union ctl_ha_msg msg;
572 	uint32_t sg_entries_sent;
573 	int do_sg_copy, i, j;
574 
575 	memset(&msg.dt, 0, sizeof(msg.dt));
576 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
577 	msg.hdr.original_sc = io->io_hdr.original_sc;
578 	msg.hdr.serializing_sc = io;
579 	msg.hdr.nexus = io->io_hdr.nexus;
580 	msg.hdr.status = io->io_hdr.status;
581 	msg.dt.flags = io->io_hdr.flags;
582 
583 	/*
584 	 * We convert everything into a S/G list here.  We can't
585 	 * pass by reference, only by value between controllers.
586 	 * So we can't pass a pointer to the S/G list, only as many
587 	 * S/G entries as we can fit in here.  If it's possible for
588 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
589 	 * then we need to break this up into multiple transfers.
590 	 */
591 	if (io->scsiio.kern_sg_entries == 0) {
592 		msg.dt.kern_sg_entries = 1;
593 #if 0
594 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
595 			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
596 		} else {
597 			/* XXX KDM use busdma here! */
598 			msg.dt.sg_list[0].addr =
599 			    (void *)vtophys(io->scsiio.kern_data_ptr);
600 		}
601 #else
602 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
603 		    ("HA does not support BUS_ADDR"));
604 		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
605 #endif
606 		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
607 		do_sg_copy = 0;
608 	} else {
609 		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
610 		do_sg_copy = 1;
611 	}
612 
613 	msg.dt.kern_data_len = io->scsiio.kern_data_len;
614 	msg.dt.kern_total_len = io->scsiio.kern_total_len;
615 	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
616 	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
617 	msg.dt.sg_sequence = 0;
618 
619 	/*
620 	 * Loop until we've sent all of the S/G entries.  On the
621 	 * other end, we'll recompose these S/G entries into one
622 	 * contiguous list before processing.
623 	 */
624 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
625 	    msg.dt.sg_sequence++) {
626 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
627 		    sizeof(msg.dt.sg_list[0])),
628 		    msg.dt.kern_sg_entries - sg_entries_sent);
629 		if (do_sg_copy != 0) {
630 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
631 			for (i = sg_entries_sent, j = 0;
632 			     i < msg.dt.cur_sg_entries; i++, j++) {
633 #if 0
634 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
635 					msg.dt.sg_list[j].addr = sgl[i].addr;
636 				} else {
637 					/* XXX KDM use busdma here! */
638 					msg.dt.sg_list[j].addr =
639 					    (void *)vtophys(sgl[i].addr);
640 				}
641 #else
642 				KASSERT((io->io_hdr.flags &
643 				    CTL_FLAG_BUS_ADDR) == 0,
644 				    ("HA does not support BUS_ADDR"));
645 				msg.dt.sg_list[j].addr = sgl[i].addr;
646 #endif
647 				msg.dt.sg_list[j].len = sgl[i].len;
648 			}
649 		}
650 
651 		sg_entries_sent += msg.dt.cur_sg_entries;
652 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
653 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
654 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
655 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
656 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
657 			io->io_hdr.port_status = 31341;
658 			io->scsiio.be_move_done(io);
659 			return;
660 		}
661 		msg.dt.sent_sg_entries = sg_entries_sent;
662 	}
663 
664 	/*
665 	 * Officially handover the request from us to peer.
666 	 * If failover has just happened, then we must return error.
667 	 * If failover happen just after, then it is not our problem.
668 	 */
669 	if (lun)
670 		mtx_lock(&lun->lun_lock);
671 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
672 		if (lun)
673 			mtx_unlock(&lun->lun_lock);
674 		io->io_hdr.port_status = 31342;
675 		io->scsiio.be_move_done(io);
676 		return;
677 	}
678 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
679 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
680 	if (lun)
681 		mtx_unlock(&lun->lun_lock);
682 }
683 
684 static void
685 ctl_ha_done(union ctl_io *io)
686 {
687 	union ctl_ha_msg msg;
688 
689 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
690 		memset(&msg, 0, sizeof(msg));
691 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
692 		msg.hdr.original_sc = io->io_hdr.original_sc;
693 		msg.hdr.nexus = io->io_hdr.nexus;
694 		msg.hdr.status = io->io_hdr.status;
695 		msg.scsi.scsi_status = io->scsiio.scsi_status;
696 		msg.scsi.tag_num = io->scsiio.tag_num;
697 		msg.scsi.tag_type = io->scsiio.tag_type;
698 		msg.scsi.sense_len = io->scsiio.sense_len;
699 		msg.scsi.sense_residual = io->scsiio.sense_residual;
700 		msg.scsi.residual = io->scsiio.residual;
701 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
702 		    io->scsiio.sense_len);
703 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
704 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
705 		    msg.scsi.sense_len, M_WAITOK);
706 	}
707 	ctl_free_io(io);
708 }
709 
710 static void
711 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
712 			    union ctl_ha_msg *msg_info)
713 {
714 	struct ctl_scsiio *ctsio;
715 
716 	if (msg_info->hdr.original_sc == NULL) {
717 		printf("%s: original_sc == NULL!\n", __func__);
718 		/* XXX KDM now what? */
719 		return;
720 	}
721 
722 	ctsio = &msg_info->hdr.original_sc->scsiio;
723 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
724 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
725 	ctsio->io_hdr.status = msg_info->hdr.status;
726 	ctsio->scsi_status = msg_info->scsi.scsi_status;
727 	ctsio->sense_len = msg_info->scsi.sense_len;
728 	ctsio->sense_residual = msg_info->scsi.sense_residual;
729 	ctsio->residual = msg_info->scsi.residual;
730 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
731 	       msg_info->scsi.sense_len);
732 	ctl_enqueue_isc((union ctl_io *)ctsio);
733 }
734 
735 static void
736 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
737 				union ctl_ha_msg *msg_info)
738 {
739 	struct ctl_scsiio *ctsio;
740 
741 	if (msg_info->hdr.serializing_sc == NULL) {
742 		printf("%s: serializing_sc == NULL!\n", __func__);
743 		/* XXX KDM now what? */
744 		return;
745 	}
746 
747 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
748 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
749 	ctl_enqueue_isc((union ctl_io *)ctsio);
750 }
751 
752 void
753 ctl_isc_announce_lun(struct ctl_lun *lun)
754 {
755 	struct ctl_softc *softc = lun->ctl_softc;
756 	union ctl_ha_msg *msg;
757 	struct ctl_ha_msg_lun_pr_key pr_key;
758 	int i, k;
759 
760 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
761 		return;
762 	mtx_lock(&lun->lun_lock);
763 	i = sizeof(msg->lun);
764 	if (lun->lun_devid)
765 		i += lun->lun_devid->len;
766 	i += sizeof(pr_key) * lun->pr_key_count;
767 alloc:
768 	mtx_unlock(&lun->lun_lock);
769 	msg = malloc(i, M_CTL, M_WAITOK);
770 	mtx_lock(&lun->lun_lock);
771 	k = sizeof(msg->lun);
772 	if (lun->lun_devid)
773 		k += lun->lun_devid->len;
774 	k += sizeof(pr_key) * lun->pr_key_count;
775 	if (i < k) {
776 		free(msg, M_CTL);
777 		i = k;
778 		goto alloc;
779 	}
780 	bzero(&msg->lun, sizeof(msg->lun));
781 	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
782 	msg->hdr.nexus.targ_lun = lun->lun;
783 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
784 	msg->lun.flags = lun->flags;
785 	msg->lun.pr_generation = lun->pr_generation;
786 	msg->lun.pr_res_idx = lun->pr_res_idx;
787 	msg->lun.pr_res_type = lun->pr_res_type;
788 	msg->lun.pr_key_count = lun->pr_key_count;
789 	i = 0;
790 	if (lun->lun_devid) {
791 		msg->lun.lun_devid_len = lun->lun_devid->len;
792 		memcpy(&msg->lun.data[i], lun->lun_devid->data,
793 		    msg->lun.lun_devid_len);
794 		i += msg->lun.lun_devid_len;
795 	}
796 	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
797 		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
798 			continue;
799 		pr_key.pr_iid = k;
800 		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
801 		i += sizeof(pr_key);
802 	}
803 	mtx_unlock(&lun->lun_lock);
804 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
805 	    M_WAITOK);
806 	free(msg, M_CTL);
807 
808 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
809 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
810 			ctl_isc_announce_mode(lun, -1,
811 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
812 			    lun->mode_pages.index[i].subpage);
813 		}
814 	}
815 }
816 
817 void
818 ctl_isc_announce_port(struct ctl_port *port)
819 {
820 	struct ctl_softc *softc = port->ctl_softc;
821 	union ctl_ha_msg *msg;
822 	int i;
823 
824 	if (port->targ_port < softc->port_min ||
825 	    port->targ_port >= softc->port_max ||
826 	    softc->ha_link != CTL_HA_LINK_ONLINE)
827 		return;
828 	i = sizeof(msg->port) + strlen(port->port_name) + 1;
829 	if (port->lun_map)
830 		i += port->lun_map_size * sizeof(uint32_t);
831 	if (port->port_devid)
832 		i += port->port_devid->len;
833 	if (port->target_devid)
834 		i += port->target_devid->len;
835 	if (port->init_devid)
836 		i += port->init_devid->len;
837 	msg = malloc(i, M_CTL, M_WAITOK);
838 	bzero(&msg->port, sizeof(msg->port));
839 	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
840 	msg->hdr.nexus.targ_port = port->targ_port;
841 	msg->port.port_type = port->port_type;
842 	msg->port.physical_port = port->physical_port;
843 	msg->port.virtual_port = port->virtual_port;
844 	msg->port.status = port->status;
845 	i = 0;
846 	msg->port.name_len = sprintf(&msg->port.data[i],
847 	    "%d:%s", softc->ha_id, port->port_name) + 1;
848 	i += msg->port.name_len;
849 	if (port->lun_map) {
850 		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
851 		memcpy(&msg->port.data[i], port->lun_map,
852 		    msg->port.lun_map_len);
853 		i += msg->port.lun_map_len;
854 	}
855 	if (port->port_devid) {
856 		msg->port.port_devid_len = port->port_devid->len;
857 		memcpy(&msg->port.data[i], port->port_devid->data,
858 		    msg->port.port_devid_len);
859 		i += msg->port.port_devid_len;
860 	}
861 	if (port->target_devid) {
862 		msg->port.target_devid_len = port->target_devid->len;
863 		memcpy(&msg->port.data[i], port->target_devid->data,
864 		    msg->port.target_devid_len);
865 		i += msg->port.target_devid_len;
866 	}
867 	if (port->init_devid) {
868 		msg->port.init_devid_len = port->init_devid->len;
869 		memcpy(&msg->port.data[i], port->init_devid->data,
870 		    msg->port.init_devid_len);
871 		i += msg->port.init_devid_len;
872 	}
873 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
874 	    M_WAITOK);
875 	free(msg, M_CTL);
876 }
877 
878 void
879 ctl_isc_announce_iid(struct ctl_port *port, int iid)
880 {
881 	struct ctl_softc *softc = port->ctl_softc;
882 	union ctl_ha_msg *msg;
883 	int i, l;
884 
885 	if (port->targ_port < softc->port_min ||
886 	    port->targ_port >= softc->port_max ||
887 	    softc->ha_link != CTL_HA_LINK_ONLINE)
888 		return;
889 	mtx_lock(&softc->ctl_lock);
890 	i = sizeof(msg->iid);
891 	l = 0;
892 	if (port->wwpn_iid[iid].name)
893 		l = strlen(port->wwpn_iid[iid].name) + 1;
894 	i += l;
895 	msg = malloc(i, M_CTL, M_NOWAIT);
896 	if (msg == NULL) {
897 		mtx_unlock(&softc->ctl_lock);
898 		return;
899 	}
900 	bzero(&msg->iid, sizeof(msg->iid));
901 	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
902 	msg->hdr.nexus.targ_port = port->targ_port;
903 	msg->hdr.nexus.initid = iid;
904 	msg->iid.in_use = port->wwpn_iid[iid].in_use;
905 	msg->iid.name_len = l;
906 	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
907 	if (port->wwpn_iid[iid].name)
908 		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
909 	mtx_unlock(&softc->ctl_lock);
910 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
911 	free(msg, M_CTL);
912 }
913 
914 void
915 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
916     uint8_t page, uint8_t subpage)
917 {
918 	struct ctl_softc *softc = lun->ctl_softc;
919 	union ctl_ha_msg msg;
920 	u_int i;
921 
922 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
923 		return;
924 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
925 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
926 		    page && lun->mode_pages.index[i].subpage == subpage)
927 			break;
928 	}
929 	if (i == CTL_NUM_MODE_PAGES)
930 		return;
931 
932 	/* Don't try to replicate pages not present on this device. */
933 	if (lun->mode_pages.index[i].page_data == NULL)
934 		return;
935 
936 	bzero(&msg.mode, sizeof(msg.mode));
937 	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
938 	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
939 	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
940 	msg.hdr.nexus.targ_lun = lun->lun;
941 	msg.hdr.nexus.targ_mapped_lun = lun->lun;
942 	msg.mode.page_code = page;
943 	msg.mode.subpage = subpage;
944 	msg.mode.page_len = lun->mode_pages.index[i].page_len;
945 	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
946 	    msg.mode.page_len);
947 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
948 	    M_WAITOK);
949 }
950 
951 static void
952 ctl_isc_ha_link_up(struct ctl_softc *softc)
953 {
954 	struct ctl_port *port;
955 	struct ctl_lun *lun;
956 	union ctl_ha_msg msg;
957 	int i;
958 
959 	/* Announce this node parameters to peer for validation. */
960 	msg.login.msg_type = CTL_MSG_LOGIN;
961 	msg.login.version = CTL_HA_VERSION;
962 	msg.login.ha_mode = softc->ha_mode;
963 	msg.login.ha_id = softc->ha_id;
964 	msg.login.max_luns = CTL_MAX_LUNS;
965 	msg.login.max_ports = CTL_MAX_PORTS;
966 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
967 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
968 	    M_WAITOK);
969 
970 	STAILQ_FOREACH(port, &softc->port_list, links) {
971 		ctl_isc_announce_port(port);
972 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
973 			if (port->wwpn_iid[i].in_use)
974 				ctl_isc_announce_iid(port, i);
975 		}
976 	}
977 	STAILQ_FOREACH(lun, &softc->lun_list, links)
978 		ctl_isc_announce_lun(lun);
979 }
980 
981 static void
982 ctl_isc_ha_link_down(struct ctl_softc *softc)
983 {
984 	struct ctl_port *port;
985 	struct ctl_lun *lun;
986 	union ctl_io *io;
987 	int i;
988 
989 	mtx_lock(&softc->ctl_lock);
990 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
991 		mtx_lock(&lun->lun_lock);
992 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
993 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
994 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
995 		}
996 		mtx_unlock(&lun->lun_lock);
997 
998 		mtx_unlock(&softc->ctl_lock);
999 		io = ctl_alloc_io(softc->othersc_pool);
1000 		mtx_lock(&softc->ctl_lock);
1001 		ctl_zero_io(io);
1002 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1003 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1004 		ctl_enqueue_isc(io);
1005 	}
1006 
1007 	STAILQ_FOREACH(port, &softc->port_list, links) {
1008 		if (port->targ_port >= softc->port_min &&
1009 		    port->targ_port < softc->port_max)
1010 			continue;
1011 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1012 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1013 			port->wwpn_iid[i].in_use = 0;
1014 			free(port->wwpn_iid[i].name, M_CTL);
1015 			port->wwpn_iid[i].name = NULL;
1016 		}
1017 	}
1018 	mtx_unlock(&softc->ctl_lock);
1019 }
1020 
1021 static void
1022 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1023 {
1024 	struct ctl_lun *lun;
1025 	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1026 
1027 	mtx_lock(&softc->ctl_lock);
1028 	if (msg->hdr.nexus.targ_mapped_lun >= CTL_MAX_LUNS ||
1029 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1030 		mtx_unlock(&softc->ctl_lock);
1031 		return;
1032 	}
1033 	mtx_lock(&lun->lun_lock);
1034 	mtx_unlock(&softc->ctl_lock);
1035 	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1036 		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1037 	if (msg->ua.ua_all) {
1038 		if (msg->ua.ua_set)
1039 			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1040 		else
1041 			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1042 	} else {
1043 		if (msg->ua.ua_set)
1044 			ctl_est_ua(lun, iid, msg->ua.ua_type);
1045 		else
1046 			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1047 	}
1048 	mtx_unlock(&lun->lun_lock);
1049 }
1050 
1051 static void
1052 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1053 {
1054 	struct ctl_lun *lun;
1055 	struct ctl_ha_msg_lun_pr_key pr_key;
1056 	int i, k;
1057 	ctl_lun_flags oflags;
1058 	uint32_t targ_lun;
1059 
1060 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1061 	mtx_lock(&softc->ctl_lock);
1062 	if (targ_lun >= CTL_MAX_LUNS ||
1063 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1064 		mtx_unlock(&softc->ctl_lock);
1065 		return;
1066 	}
1067 	mtx_lock(&lun->lun_lock);
1068 	mtx_unlock(&softc->ctl_lock);
1069 	if (lun->flags & CTL_LUN_DISABLED) {
1070 		mtx_unlock(&lun->lun_lock);
1071 		return;
1072 	}
1073 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1074 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1075 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1076 		mtx_unlock(&lun->lun_lock);
1077 		printf("%s: Received conflicting HA LUN %d\n",
1078 		    __func__, targ_lun);
1079 		return;
1080 	} else {
1081 		/* Record whether peer is primary. */
1082 		oflags = lun->flags;
1083 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1084 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1085 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1086 		else
1087 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1088 		if (oflags != lun->flags)
1089 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1090 
1091 		/* If peer is primary and we are not -- use data */
1092 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1093 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1094 			lun->pr_generation = msg->lun.pr_generation;
1095 			lun->pr_res_idx = msg->lun.pr_res_idx;
1096 			lun->pr_res_type = msg->lun.pr_res_type;
1097 			lun->pr_key_count = msg->lun.pr_key_count;
1098 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1099 				ctl_clr_prkey(lun, k);
1100 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1101 				memcpy(&pr_key, &msg->lun.data[i],
1102 				    sizeof(pr_key));
1103 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1104 				ctl_set_prkey(lun, pr_key.pr_iid,
1105 				    pr_key.pr_key);
1106 				i += sizeof(pr_key);
1107 			}
1108 		}
1109 
1110 		mtx_unlock(&lun->lun_lock);
1111 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1112 		    __func__, targ_lun,
1113 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1114 		    "primary" : "secondary"));
1115 
1116 		/* If we are primary but peer doesn't know -- notify */
1117 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1118 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1119 			ctl_isc_announce_lun(lun);
1120 	}
1121 }
1122 
1123 static void
1124 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1125 {
1126 	struct ctl_port *port;
1127 	struct ctl_lun *lun;
1128 	int i, new;
1129 
1130 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1131 	if (port == NULL) {
1132 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1133 		    msg->hdr.nexus.targ_port));
1134 		new = 1;
1135 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1136 		port->frontend = &ha_frontend;
1137 		port->targ_port = msg->hdr.nexus.targ_port;
1138 		port->fe_datamove = ctl_ha_datamove;
1139 		port->fe_done = ctl_ha_done;
1140 	} else if (port->frontend == &ha_frontend) {
1141 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1142 		    msg->hdr.nexus.targ_port));
1143 		new = 0;
1144 	} else {
1145 		printf("%s: Received conflicting HA port %d\n",
1146 		    __func__, msg->hdr.nexus.targ_port);
1147 		return;
1148 	}
1149 	port->port_type = msg->port.port_type;
1150 	port->physical_port = msg->port.physical_port;
1151 	port->virtual_port = msg->port.virtual_port;
1152 	port->status = msg->port.status;
1153 	i = 0;
1154 	free(port->port_name, M_CTL);
1155 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1156 	    M_CTL);
1157 	i += msg->port.name_len;
1158 	if (msg->port.lun_map_len != 0) {
1159 		if (port->lun_map == NULL ||
1160 		    port->lun_map_size * sizeof(uint32_t) <
1161 		    msg->port.lun_map_len) {
1162 			port->lun_map_size = 0;
1163 			free(port->lun_map, M_CTL);
1164 			port->lun_map = malloc(msg->port.lun_map_len,
1165 			    M_CTL, M_WAITOK);
1166 		}
1167 		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1168 		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1169 		i += msg->port.lun_map_len;
1170 	} else {
1171 		port->lun_map_size = 0;
1172 		free(port->lun_map, M_CTL);
1173 		port->lun_map = NULL;
1174 	}
1175 	if (msg->port.port_devid_len != 0) {
1176 		if (port->port_devid == NULL ||
1177 		    port->port_devid->len < msg->port.port_devid_len) {
1178 			free(port->port_devid, M_CTL);
1179 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1180 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1181 		}
1182 		memcpy(port->port_devid->data, &msg->port.data[i],
1183 		    msg->port.port_devid_len);
1184 		port->port_devid->len = msg->port.port_devid_len;
1185 		i += msg->port.port_devid_len;
1186 	} else {
1187 		free(port->port_devid, M_CTL);
1188 		port->port_devid = NULL;
1189 	}
1190 	if (msg->port.target_devid_len != 0) {
1191 		if (port->target_devid == NULL ||
1192 		    port->target_devid->len < msg->port.target_devid_len) {
1193 			free(port->target_devid, M_CTL);
1194 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1195 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1196 		}
1197 		memcpy(port->target_devid->data, &msg->port.data[i],
1198 		    msg->port.target_devid_len);
1199 		port->target_devid->len = msg->port.target_devid_len;
1200 		i += msg->port.target_devid_len;
1201 	} else {
1202 		free(port->target_devid, M_CTL);
1203 		port->target_devid = NULL;
1204 	}
1205 	if (msg->port.init_devid_len != 0) {
1206 		if (port->init_devid == NULL ||
1207 		    port->init_devid->len < msg->port.init_devid_len) {
1208 			free(port->init_devid, M_CTL);
1209 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1210 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1211 		}
1212 		memcpy(port->init_devid->data, &msg->port.data[i],
1213 		    msg->port.init_devid_len);
1214 		port->init_devid->len = msg->port.init_devid_len;
1215 		i += msg->port.init_devid_len;
1216 	} else {
1217 		free(port->init_devid, M_CTL);
1218 		port->init_devid = NULL;
1219 	}
1220 	if (new) {
1221 		if (ctl_port_register(port) != 0) {
1222 			printf("%s: ctl_port_register() failed with error\n",
1223 			    __func__);
1224 		}
1225 	}
1226 	mtx_lock(&softc->ctl_lock);
1227 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1228 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1229 			continue;
1230 		mtx_lock(&lun->lun_lock);
1231 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1232 		mtx_unlock(&lun->lun_lock);
1233 	}
1234 	mtx_unlock(&softc->ctl_lock);
1235 }
1236 
1237 static void
1238 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1239 {
1240 	struct ctl_port *port;
1241 	int iid;
1242 
1243 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1244 	if (port == NULL) {
1245 		printf("%s: Received IID for unknown port %d\n",
1246 		    __func__, msg->hdr.nexus.targ_port);
1247 		return;
1248 	}
1249 	iid = msg->hdr.nexus.initid;
1250 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1251 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1252 	free(port->wwpn_iid[iid].name, M_CTL);
1253 	if (msg->iid.name_len) {
1254 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1255 		    msg->iid.name_len, M_CTL);
1256 	} else
1257 		port->wwpn_iid[iid].name = NULL;
1258 }
1259 
1260 static void
1261 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1262 {
1263 
1264 	if (msg->login.version != CTL_HA_VERSION) {
1265 		printf("CTL HA peers have different versions %d != %d\n",
1266 		    msg->login.version, CTL_HA_VERSION);
1267 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1268 		return;
1269 	}
1270 	if (msg->login.ha_mode != softc->ha_mode) {
1271 		printf("CTL HA peers have different ha_mode %d != %d\n",
1272 		    msg->login.ha_mode, softc->ha_mode);
1273 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1274 		return;
1275 	}
1276 	if (msg->login.ha_id == softc->ha_id) {
1277 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1278 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1279 		return;
1280 	}
1281 	if (msg->login.max_luns != CTL_MAX_LUNS ||
1282 	    msg->login.max_ports != CTL_MAX_PORTS ||
1283 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1284 		printf("CTL HA peers have different limits\n");
1285 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1286 		return;
1287 	}
1288 }
1289 
1290 static void
1291 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1292 {
1293 	struct ctl_lun *lun;
1294 	u_int i;
1295 	uint32_t initidx, targ_lun;
1296 
1297 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1298 	mtx_lock(&softc->ctl_lock);
1299 	if (targ_lun >= CTL_MAX_LUNS ||
1300 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1301 		mtx_unlock(&softc->ctl_lock);
1302 		return;
1303 	}
1304 	mtx_lock(&lun->lun_lock);
1305 	mtx_unlock(&softc->ctl_lock);
1306 	if (lun->flags & CTL_LUN_DISABLED) {
1307 		mtx_unlock(&lun->lun_lock);
1308 		return;
1309 	}
1310 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1311 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1312 		    msg->mode.page_code &&
1313 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1314 			break;
1315 	}
1316 	if (i == CTL_NUM_MODE_PAGES) {
1317 		mtx_unlock(&lun->lun_lock);
1318 		return;
1319 	}
1320 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1321 	    lun->mode_pages.index[i].page_len);
1322 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1323 	if (initidx != -1)
1324 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1325 	mtx_unlock(&lun->lun_lock);
1326 }
1327 
1328 /*
1329  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1330  * subsystem come in here.
1331  */
1332 static void
1333 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1334 {
1335 	struct ctl_softc *softc = control_softc;
1336 	union ctl_io *io;
1337 	struct ctl_prio *presio;
1338 	ctl_ha_status isc_status;
1339 
1340 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1341 	if (event == CTL_HA_EVT_MSG_RECV) {
1342 		union ctl_ha_msg *msg, msgbuf;
1343 
1344 		if (param > sizeof(msgbuf))
1345 			msg = malloc(param, M_CTL, M_WAITOK);
1346 		else
1347 			msg = &msgbuf;
1348 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1349 		    M_WAITOK);
1350 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1351 			printf("%s: Error receiving message: %d\n",
1352 			    __func__, isc_status);
1353 			if (msg != &msgbuf)
1354 				free(msg, M_CTL);
1355 			return;
1356 		}
1357 
1358 		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1359 		switch (msg->hdr.msg_type) {
1360 		case CTL_MSG_SERIALIZE:
1361 			io = ctl_alloc_io(softc->othersc_pool);
1362 			ctl_zero_io(io);
1363 			// populate ctsio from msg
1364 			io->io_hdr.io_type = CTL_IO_SCSI;
1365 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1366 			io->io_hdr.original_sc = msg->hdr.original_sc;
1367 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1368 					    CTL_FLAG_IO_ACTIVE;
1369 			/*
1370 			 * If we're in serialization-only mode, we don't
1371 			 * want to go through full done processing.  Thus
1372 			 * the COPY flag.
1373 			 *
1374 			 * XXX KDM add another flag that is more specific.
1375 			 */
1376 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1377 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1378 			io->io_hdr.nexus = msg->hdr.nexus;
1379 #if 0
1380 			printf("port %u, iid %u, lun %u\n",
1381 			       io->io_hdr.nexus.targ_port,
1382 			       io->io_hdr.nexus.initid,
1383 			       io->io_hdr.nexus.targ_lun);
1384 #endif
1385 			io->scsiio.tag_num = msg->scsi.tag_num;
1386 			io->scsiio.tag_type = msg->scsi.tag_type;
1387 #ifdef CTL_TIME_IO
1388 			io->io_hdr.start_time = time_uptime;
1389 			getbinuptime(&io->io_hdr.start_bt);
1390 #endif /* CTL_TIME_IO */
1391 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1392 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1393 			       CTL_MAX_CDBLEN);
1394 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1395 				const struct ctl_cmd_entry *entry;
1396 
1397 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1398 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1399 				io->io_hdr.flags |=
1400 					entry->flags & CTL_FLAG_DATA_MASK;
1401 			}
1402 			ctl_enqueue_isc(io);
1403 			break;
1404 
1405 		/* Performed on the Originating SC, XFER mode only */
1406 		case CTL_MSG_DATAMOVE: {
1407 			struct ctl_sg_entry *sgl;
1408 			int i, j;
1409 
1410 			io = msg->hdr.original_sc;
1411 			if (io == NULL) {
1412 				printf("%s: original_sc == NULL!\n", __func__);
1413 				/* XXX KDM do something here */
1414 				break;
1415 			}
1416 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1417 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1418 			/*
1419 			 * Keep track of this, we need to send it back over
1420 			 * when the datamove is complete.
1421 			 */
1422 			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1423 			if (msg->hdr.status == CTL_SUCCESS)
1424 				io->io_hdr.status = msg->hdr.status;
1425 
1426 			if (msg->dt.sg_sequence == 0) {
1427 #ifdef CTL_TIME_IO
1428 				getbinuptime(&io->io_hdr.dma_start_bt);
1429 #endif
1430 				i = msg->dt.kern_sg_entries +
1431 				    msg->dt.kern_data_len /
1432 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1433 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1434 				    M_WAITOK | M_ZERO);
1435 				io->io_hdr.remote_sglist = sgl;
1436 				io->io_hdr.local_sglist =
1437 				    &sgl[msg->dt.kern_sg_entries];
1438 
1439 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1440 
1441 				io->scsiio.kern_sg_entries =
1442 					msg->dt.kern_sg_entries;
1443 				io->scsiio.rem_sg_entries =
1444 					msg->dt.kern_sg_entries;
1445 				io->scsiio.kern_data_len =
1446 					msg->dt.kern_data_len;
1447 				io->scsiio.kern_total_len =
1448 					msg->dt.kern_total_len;
1449 				io->scsiio.kern_data_resid =
1450 					msg->dt.kern_data_resid;
1451 				io->scsiio.kern_rel_offset =
1452 					msg->dt.kern_rel_offset;
1453 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1454 				io->io_hdr.flags |= msg->dt.flags &
1455 				    CTL_FLAG_BUS_ADDR;
1456 			} else
1457 				sgl = (struct ctl_sg_entry *)
1458 					io->scsiio.kern_data_ptr;
1459 
1460 			for (i = msg->dt.sent_sg_entries, j = 0;
1461 			     i < (msg->dt.sent_sg_entries +
1462 			     msg->dt.cur_sg_entries); i++, j++) {
1463 				sgl[i].addr = msg->dt.sg_list[j].addr;
1464 				sgl[i].len = msg->dt.sg_list[j].len;
1465 
1466 #if 0
1467 				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1468 				    __func__, sgl[i].addr, sgl[i].len, j, i);
1469 #endif
1470 			}
1471 
1472 			/*
1473 			 * If this is the last piece of the I/O, we've got
1474 			 * the full S/G list.  Queue processing in the thread.
1475 			 * Otherwise wait for the next piece.
1476 			 */
1477 			if (msg->dt.sg_last != 0)
1478 				ctl_enqueue_isc(io);
1479 			break;
1480 		}
1481 		/* Performed on the Serializing (primary) SC, XFER mode only */
1482 		case CTL_MSG_DATAMOVE_DONE: {
1483 			if (msg->hdr.serializing_sc == NULL) {
1484 				printf("%s: serializing_sc == NULL!\n",
1485 				       __func__);
1486 				/* XXX KDM now what? */
1487 				break;
1488 			}
1489 			/*
1490 			 * We grab the sense information here in case
1491 			 * there was a failure, so we can return status
1492 			 * back to the initiator.
1493 			 */
1494 			io = msg->hdr.serializing_sc;
1495 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1496 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1497 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1498 			io->io_hdr.port_status = msg->scsi.fetd_status;
1499 			io->scsiio.residual = msg->scsi.residual;
1500 			if (msg->hdr.status != CTL_STATUS_NONE) {
1501 				io->io_hdr.status = msg->hdr.status;
1502 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1503 				io->scsiio.sense_len = msg->scsi.sense_len;
1504 				io->scsiio.sense_residual =msg->scsi.sense_residual;
1505 				memcpy(&io->scsiio.sense_data,
1506 				    &msg->scsi.sense_data,
1507 				    msg->scsi.sense_len);
1508 				if (msg->hdr.status == CTL_SUCCESS)
1509 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1510 			}
1511 			ctl_enqueue_isc(io);
1512 			break;
1513 		}
1514 
1515 		/* Preformed on Originating SC, SER_ONLY mode */
1516 		case CTL_MSG_R2R:
1517 			io = msg->hdr.original_sc;
1518 			if (io == NULL) {
1519 				printf("%s: original_sc == NULL!\n",
1520 				    __func__);
1521 				break;
1522 			}
1523 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1524 			io->io_hdr.msg_type = CTL_MSG_R2R;
1525 			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1526 			ctl_enqueue_isc(io);
1527 			break;
1528 
1529 		/*
1530 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1531 		 * mode.
1532 		 * Performed on the Originating (i.e. secondary) SC in XFER
1533 		 * mode
1534 		 */
1535 		case CTL_MSG_FINISH_IO:
1536 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1537 				ctl_isc_handler_finish_xfer(softc, msg);
1538 			else
1539 				ctl_isc_handler_finish_ser_only(softc, msg);
1540 			break;
1541 
1542 		/* Preformed on Originating SC */
1543 		case CTL_MSG_BAD_JUJU:
1544 			io = msg->hdr.original_sc;
1545 			if (io == NULL) {
1546 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1547 				       __func__);
1548 				break;
1549 			}
1550 			ctl_copy_sense_data(msg, io);
1551 			/*
1552 			 * IO should have already been cleaned up on other
1553 			 * SC so clear this flag so we won't send a message
1554 			 * back to finish the IO there.
1555 			 */
1556 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1557 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1558 
1559 			/* io = msg->hdr.serializing_sc; */
1560 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1561 			ctl_enqueue_isc(io);
1562 			break;
1563 
1564 		/* Handle resets sent from the other side */
1565 		case CTL_MSG_MANAGE_TASKS: {
1566 			struct ctl_taskio *taskio;
1567 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1568 			    softc->othersc_pool);
1569 			ctl_zero_io((union ctl_io *)taskio);
1570 			taskio->io_hdr.io_type = CTL_IO_TASK;
1571 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1572 			taskio->io_hdr.nexus = msg->hdr.nexus;
1573 			taskio->task_action = msg->task.task_action;
1574 			taskio->tag_num = msg->task.tag_num;
1575 			taskio->tag_type = msg->task.tag_type;
1576 #ifdef CTL_TIME_IO
1577 			taskio->io_hdr.start_time = time_uptime;
1578 			getbinuptime(&taskio->io_hdr.start_bt);
1579 #endif /* CTL_TIME_IO */
1580 			ctl_run_task((union ctl_io *)taskio);
1581 			break;
1582 		}
1583 		/* Persistent Reserve action which needs attention */
1584 		case CTL_MSG_PERS_ACTION:
1585 			presio = (struct ctl_prio *)ctl_alloc_io(
1586 			    softc->othersc_pool);
1587 			ctl_zero_io((union ctl_io *)presio);
1588 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1589 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1590 			presio->io_hdr.nexus = msg->hdr.nexus;
1591 			presio->pr_msg = msg->pr;
1592 			ctl_enqueue_isc((union ctl_io *)presio);
1593 			break;
1594 		case CTL_MSG_UA:
1595 			ctl_isc_ua(softc, msg, param);
1596 			break;
1597 		case CTL_MSG_PORT_SYNC:
1598 			ctl_isc_port_sync(softc, msg, param);
1599 			break;
1600 		case CTL_MSG_LUN_SYNC:
1601 			ctl_isc_lun_sync(softc, msg, param);
1602 			break;
1603 		case CTL_MSG_IID_SYNC:
1604 			ctl_isc_iid_sync(softc, msg, param);
1605 			break;
1606 		case CTL_MSG_LOGIN:
1607 			ctl_isc_login(softc, msg, param);
1608 			break;
1609 		case CTL_MSG_MODE_SYNC:
1610 			ctl_isc_mode_sync(softc, msg, param);
1611 			break;
1612 		default:
1613 			printf("Received HA message of unknown type %d\n",
1614 			    msg->hdr.msg_type);
1615 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1616 			break;
1617 		}
1618 		if (msg != &msgbuf)
1619 			free(msg, M_CTL);
1620 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1621 		printf("CTL: HA link status changed from %d to %d\n",
1622 		    softc->ha_link, param);
1623 		if (param == softc->ha_link)
1624 			return;
1625 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1626 			softc->ha_link = param;
1627 			ctl_isc_ha_link_down(softc);
1628 		} else {
1629 			softc->ha_link = param;
1630 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1631 				ctl_isc_ha_link_up(softc);
1632 		}
1633 		return;
1634 	} else {
1635 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1636 		return;
1637 	}
1638 }
1639 
1640 static void
1641 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1642 {
1643 
1644 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1645 	    src->scsi.sense_len);
1646 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1647 	dest->scsiio.sense_len = src->scsi.sense_len;
1648 	dest->io_hdr.status = src->hdr.status;
1649 }
1650 
1651 static void
1652 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1653 {
1654 
1655 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1656 	    src->scsiio.sense_len);
1657 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1658 	dest->scsi.sense_len = src->scsiio.sense_len;
1659 	dest->hdr.status = src->io_hdr.status;
1660 }
1661 
1662 void
1663 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1664 {
1665 	struct ctl_softc *softc = lun->ctl_softc;
1666 	ctl_ua_type *pu;
1667 
1668 	if (initidx < softc->init_min || initidx >= softc->init_max)
1669 		return;
1670 	mtx_assert(&lun->lun_lock, MA_OWNED);
1671 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1672 	if (pu == NULL)
1673 		return;
1674 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1675 }
1676 
1677 void
1678 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1679 {
1680 	int i;
1681 
1682 	mtx_assert(&lun->lun_lock, MA_OWNED);
1683 	if (lun->pending_ua[port] == NULL)
1684 		return;
1685 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1686 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1687 			continue;
1688 		lun->pending_ua[port][i] |= ua;
1689 	}
1690 }
1691 
1692 void
1693 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1694 {
1695 	struct ctl_softc *softc = lun->ctl_softc;
1696 	int i;
1697 
1698 	mtx_assert(&lun->lun_lock, MA_OWNED);
1699 	for (i = softc->port_min; i < softc->port_max; i++)
1700 		ctl_est_ua_port(lun, i, except, ua);
1701 }
1702 
1703 void
1704 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1705 {
1706 	struct ctl_softc *softc = lun->ctl_softc;
1707 	ctl_ua_type *pu;
1708 
1709 	if (initidx < softc->init_min || initidx >= softc->init_max)
1710 		return;
1711 	mtx_assert(&lun->lun_lock, MA_OWNED);
1712 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1713 	if (pu == NULL)
1714 		return;
1715 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1716 }
1717 
1718 void
1719 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1720 {
1721 	struct ctl_softc *softc = lun->ctl_softc;
1722 	int i, j;
1723 
1724 	mtx_assert(&lun->lun_lock, MA_OWNED);
1725 	for (i = softc->port_min; i < softc->port_max; i++) {
1726 		if (lun->pending_ua[i] == NULL)
1727 			continue;
1728 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1729 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1730 				continue;
1731 			lun->pending_ua[i][j] &= ~ua;
1732 		}
1733 	}
1734 }
1735 
1736 void
1737 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1738     ctl_ua_type ua_type)
1739 {
1740 	struct ctl_lun *lun;
1741 
1742 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1743 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1744 		mtx_lock(&lun->lun_lock);
1745 		ctl_clr_ua(lun, initidx, ua_type);
1746 		mtx_unlock(&lun->lun_lock);
1747 	}
1748 }
1749 
1750 static int
1751 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1752 {
1753 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1754 	struct ctl_lun *lun;
1755 	struct ctl_lun_req ireq;
1756 	int error, value;
1757 
1758 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1759 	error = sysctl_handle_int(oidp, &value, 0, req);
1760 	if ((error != 0) || (req->newptr == NULL))
1761 		return (error);
1762 
1763 	mtx_lock(&softc->ctl_lock);
1764 	if (value == 0)
1765 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1766 	else
1767 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1768 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1769 		mtx_unlock(&softc->ctl_lock);
1770 		bzero(&ireq, sizeof(ireq));
1771 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1772 		ireq.reqdata.modify.lun_id = lun->lun;
1773 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1774 		    curthread);
1775 		if (ireq.status != CTL_LUN_OK) {
1776 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1777 			    __func__, ireq.status, ireq.error_str);
1778 		}
1779 		mtx_lock(&softc->ctl_lock);
1780 	}
1781 	mtx_unlock(&softc->ctl_lock);
1782 	return (0);
1783 }
1784 
1785 static int
1786 ctl_init(void)
1787 {
1788 	struct make_dev_args args;
1789 	struct ctl_softc *softc;
1790 	void *other_pool;
1791 	int i, error;
1792 
1793 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1794 			       M_WAITOK | M_ZERO);
1795 
1796 	make_dev_args_init(&args);
1797 	args.mda_devsw = &ctl_cdevsw;
1798 	args.mda_uid = UID_ROOT;
1799 	args.mda_gid = GID_OPERATOR;
1800 	args.mda_mode = 0600;
1801 	args.mda_si_drv1 = softc;
1802 	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1803 	if (error != 0) {
1804 		free(softc, M_DEVBUF);
1805 		control_softc = NULL;
1806 		return (error);
1807 	}
1808 
1809 	sysctl_ctx_init(&softc->sysctl_ctx);
1810 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1811 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1812 		CTLFLAG_RD, 0, "CAM Target Layer");
1813 
1814 	if (softc->sysctl_tree == NULL) {
1815 		printf("%s: unable to allocate sysctl tree\n", __func__);
1816 		destroy_dev(softc->dev);
1817 		free(softc, M_DEVBUF);
1818 		control_softc = NULL;
1819 		return (ENOMEM);
1820 	}
1821 
1822 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1823 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1824 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1825 	softc->flags = 0;
1826 
1827 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1828 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1829 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1830 
1831 	/*
1832 	 * In Copan's HA scheme, the "master" and "slave" roles are
1833 	 * figured out through the slot the controller is in.  Although it
1834 	 * is an active/active system, someone has to be in charge.
1835 	 */
1836 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1837 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1838 	    "HA head ID (0 - no HA)");
1839 	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1840 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1841 		softc->is_single = 1;
1842 		softc->port_cnt = CTL_MAX_PORTS;
1843 		softc->port_min = 0;
1844 	} else {
1845 		softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1846 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1847 	}
1848 	softc->port_max = softc->port_min + softc->port_cnt;
1849 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1850 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1851 
1852 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1853 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1854 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1855 
1856 	STAILQ_INIT(&softc->lun_list);
1857 	STAILQ_INIT(&softc->pending_lun_queue);
1858 	STAILQ_INIT(&softc->fe_list);
1859 	STAILQ_INIT(&softc->port_list);
1860 	STAILQ_INIT(&softc->be_list);
1861 	ctl_tpc_init(softc);
1862 
1863 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1864 	                    &other_pool) != 0)
1865 	{
1866 		printf("ctl: can't allocate %d entry other SC pool, "
1867 		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1868 		return (ENOMEM);
1869 	}
1870 	softc->othersc_pool = other_pool;
1871 
1872 	if (worker_threads <= 0)
1873 		worker_threads = max(1, mp_ncpus / 4);
1874 	if (worker_threads > CTL_MAX_THREADS)
1875 		worker_threads = CTL_MAX_THREADS;
1876 
1877 	for (i = 0; i < worker_threads; i++) {
1878 		struct ctl_thread *thr = &softc->threads[i];
1879 
1880 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1881 		thr->ctl_softc = softc;
1882 		STAILQ_INIT(&thr->incoming_queue);
1883 		STAILQ_INIT(&thr->rtr_queue);
1884 		STAILQ_INIT(&thr->done_queue);
1885 		STAILQ_INIT(&thr->isc_queue);
1886 
1887 		error = kproc_kthread_add(ctl_work_thread, thr,
1888 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1889 		if (error != 0) {
1890 			printf("error creating CTL work thread!\n");
1891 			ctl_pool_free(other_pool);
1892 			return (error);
1893 		}
1894 	}
1895 	error = kproc_kthread_add(ctl_lun_thread, softc,
1896 	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1897 	if (error != 0) {
1898 		printf("error creating CTL lun thread!\n");
1899 		ctl_pool_free(other_pool);
1900 		return (error);
1901 	}
1902 	error = kproc_kthread_add(ctl_thresh_thread, softc,
1903 	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1904 	if (error != 0) {
1905 		printf("error creating CTL threshold thread!\n");
1906 		ctl_pool_free(other_pool);
1907 		return (error);
1908 	}
1909 
1910 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1911 	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1912 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1913 
1914 	if (softc->is_single == 0) {
1915 		ctl_frontend_register(&ha_frontend);
1916 		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1917 			printf("ctl_init: ctl_ha_msg_init failed.\n");
1918 			softc->is_single = 1;
1919 		} else
1920 		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1921 		    != CTL_HA_STATUS_SUCCESS) {
1922 			printf("ctl_init: ctl_ha_msg_register failed.\n");
1923 			softc->is_single = 1;
1924 		}
1925 	}
1926 	return (0);
1927 }
1928 
1929 void
1930 ctl_shutdown(void)
1931 {
1932 	struct ctl_softc *softc = control_softc;
1933 	struct ctl_lun *lun, *next_lun;
1934 
1935 	if (softc->is_single == 0) {
1936 		ctl_ha_msg_shutdown(softc);
1937 		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1938 		    != CTL_HA_STATUS_SUCCESS)
1939 			printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1940 		if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1941 			printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1942 		ctl_frontend_deregister(&ha_frontend);
1943 	}
1944 
1945 	mtx_lock(&softc->ctl_lock);
1946 
1947 	STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1948 		ctl_free_lun(lun);
1949 
1950 	mtx_unlock(&softc->ctl_lock);
1951 
1952 #if 0
1953 	ctl_shutdown_thread(softc->work_thread);
1954 	mtx_destroy(&softc->queue_lock);
1955 #endif
1956 
1957 	ctl_tpc_shutdown(softc);
1958 	uma_zdestroy(softc->io_zone);
1959 	mtx_destroy(&softc->ctl_lock);
1960 
1961 	destroy_dev(softc->dev);
1962 
1963 	sysctl_ctx_free(&softc->sysctl_ctx);
1964 
1965 	free(softc, M_DEVBUF);
1966 	control_softc = NULL;
1967 }
1968 
1969 static int
1970 ctl_module_event_handler(module_t mod, int what, void *arg)
1971 {
1972 
1973 	switch (what) {
1974 	case MOD_LOAD:
1975 		return (ctl_init());
1976 	case MOD_UNLOAD:
1977 		return (EBUSY);
1978 	default:
1979 		return (EOPNOTSUPP);
1980 	}
1981 }
1982 
1983 /*
1984  * XXX KDM should we do some access checks here?  Bump a reference count to
1985  * prevent a CTL module from being unloaded while someone has it open?
1986  */
1987 static int
1988 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1989 {
1990 	return (0);
1991 }
1992 
1993 static int
1994 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1995 {
1996 	return (0);
1997 }
1998 
1999 /*
2000  * Remove an initiator by port number and initiator ID.
2001  * Returns 0 for success, -1 for failure.
2002  */
2003 int
2004 ctl_remove_initiator(struct ctl_port *port, int iid)
2005 {
2006 	struct ctl_softc *softc = port->ctl_softc;
2007 
2008 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2009 
2010 	if (iid > CTL_MAX_INIT_PER_PORT) {
2011 		printf("%s: initiator ID %u > maximun %u!\n",
2012 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2013 		return (-1);
2014 	}
2015 
2016 	mtx_lock(&softc->ctl_lock);
2017 	port->wwpn_iid[iid].in_use--;
2018 	port->wwpn_iid[iid].last_use = time_uptime;
2019 	mtx_unlock(&softc->ctl_lock);
2020 	ctl_isc_announce_iid(port, iid);
2021 
2022 	return (0);
2023 }
2024 
2025 /*
2026  * Add an initiator to the initiator map.
2027  * Returns iid for success, < 0 for failure.
2028  */
2029 int
2030 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2031 {
2032 	struct ctl_softc *softc = port->ctl_softc;
2033 	time_t best_time;
2034 	int i, best;
2035 
2036 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2037 
2038 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2039 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2040 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2041 		free(name, M_CTL);
2042 		return (-1);
2043 	}
2044 
2045 	mtx_lock(&softc->ctl_lock);
2046 
2047 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2048 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2049 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2050 				iid = i;
2051 				break;
2052 			}
2053 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2054 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2055 				iid = i;
2056 				break;
2057 			}
2058 		}
2059 	}
2060 
2061 	if (iid < 0) {
2062 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2063 			if (port->wwpn_iid[i].in_use == 0 &&
2064 			    port->wwpn_iid[i].wwpn == 0 &&
2065 			    port->wwpn_iid[i].name == NULL) {
2066 				iid = i;
2067 				break;
2068 			}
2069 		}
2070 	}
2071 
2072 	if (iid < 0) {
2073 		best = -1;
2074 		best_time = INT32_MAX;
2075 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2076 			if (port->wwpn_iid[i].in_use == 0) {
2077 				if (port->wwpn_iid[i].last_use < best_time) {
2078 					best = i;
2079 					best_time = port->wwpn_iid[i].last_use;
2080 				}
2081 			}
2082 		}
2083 		iid = best;
2084 	}
2085 
2086 	if (iid < 0) {
2087 		mtx_unlock(&softc->ctl_lock);
2088 		free(name, M_CTL);
2089 		return (-2);
2090 	}
2091 
2092 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2093 		/*
2094 		 * This is not an error yet.
2095 		 */
2096 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2097 #if 0
2098 			printf("%s: port %d iid %u WWPN %#jx arrived"
2099 			    " again\n", __func__, port->targ_port,
2100 			    iid, (uintmax_t)wwpn);
2101 #endif
2102 			goto take;
2103 		}
2104 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2105 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2106 #if 0
2107 			printf("%s: port %d iid %u name '%s' arrived"
2108 			    " again\n", __func__, port->targ_port,
2109 			    iid, name);
2110 #endif
2111 			goto take;
2112 		}
2113 
2114 		/*
2115 		 * This is an error, but what do we do about it?  The
2116 		 * driver is telling us we have a new WWPN for this
2117 		 * initiator ID, so we pretty much need to use it.
2118 		 */
2119 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2120 		    " but WWPN %#jx '%s' is still at that address\n",
2121 		    __func__, port->targ_port, iid, wwpn, name,
2122 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2123 		    port->wwpn_iid[iid].name);
2124 
2125 		/*
2126 		 * XXX KDM clear have_ca and ua_pending on each LUN for
2127 		 * this initiator.
2128 		 */
2129 	}
2130 take:
2131 	free(port->wwpn_iid[iid].name, M_CTL);
2132 	port->wwpn_iid[iid].name = name;
2133 	port->wwpn_iid[iid].wwpn = wwpn;
2134 	port->wwpn_iid[iid].in_use++;
2135 	mtx_unlock(&softc->ctl_lock);
2136 	ctl_isc_announce_iid(port, iid);
2137 
2138 	return (iid);
2139 }
2140 
2141 static int
2142 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2143 {
2144 	int len;
2145 
2146 	switch (port->port_type) {
2147 	case CTL_PORT_FC:
2148 	{
2149 		struct scsi_transportid_fcp *id =
2150 		    (struct scsi_transportid_fcp *)buf;
2151 		if (port->wwpn_iid[iid].wwpn == 0)
2152 			return (0);
2153 		memset(id, 0, sizeof(*id));
2154 		id->format_protocol = SCSI_PROTO_FC;
2155 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2156 		return (sizeof(*id));
2157 	}
2158 	case CTL_PORT_ISCSI:
2159 	{
2160 		struct scsi_transportid_iscsi_port *id =
2161 		    (struct scsi_transportid_iscsi_port *)buf;
2162 		if (port->wwpn_iid[iid].name == NULL)
2163 			return (0);
2164 		memset(id, 0, 256);
2165 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2166 		    SCSI_PROTO_ISCSI;
2167 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2168 		len = roundup2(min(len, 252), 4);
2169 		scsi_ulto2b(len, id->additional_length);
2170 		return (sizeof(*id) + len);
2171 	}
2172 	case CTL_PORT_SAS:
2173 	{
2174 		struct scsi_transportid_sas *id =
2175 		    (struct scsi_transportid_sas *)buf;
2176 		if (port->wwpn_iid[iid].wwpn == 0)
2177 			return (0);
2178 		memset(id, 0, sizeof(*id));
2179 		id->format_protocol = SCSI_PROTO_SAS;
2180 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2181 		return (sizeof(*id));
2182 	}
2183 	default:
2184 	{
2185 		struct scsi_transportid_spi *id =
2186 		    (struct scsi_transportid_spi *)buf;
2187 		memset(id, 0, sizeof(*id));
2188 		id->format_protocol = SCSI_PROTO_SPI;
2189 		scsi_ulto2b(iid, id->scsi_addr);
2190 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2191 		return (sizeof(*id));
2192 	}
2193 	}
2194 }
2195 
2196 /*
2197  * Serialize a command that went down the "wrong" side, and so was sent to
2198  * this controller for execution.  The logic is a little different than the
2199  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2200  * sent back to the other side, but in the success case, we execute the
2201  * command on this side (XFER mode) or tell the other side to execute it
2202  * (SER_ONLY mode).
2203  */
2204 static void
2205 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2206 {
2207 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2208 	struct ctl_port *port = CTL_PORT(ctsio);
2209 	union ctl_ha_msg msg_info;
2210 	struct ctl_lun *lun;
2211 	const struct ctl_cmd_entry *entry;
2212 	uint32_t targ_lun;
2213 
2214 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2215 
2216 	/* Make sure that we know about this port. */
2217 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2218 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2219 					 /*retry_count*/ 1);
2220 		goto badjuju;
2221 	}
2222 
2223 	/* Make sure that we know about this LUN. */
2224 	mtx_lock(&softc->ctl_lock);
2225 	if (targ_lun >= CTL_MAX_LUNS ||
2226 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2227 		mtx_unlock(&softc->ctl_lock);
2228 
2229 		/*
2230 		 * The other node would not send this request to us unless
2231 		 * received announce that we are primary node for this LUN.
2232 		 * If this LUN does not exist now, it is probably result of
2233 		 * a race, so respond to initiator in the most opaque way.
2234 		 */
2235 		ctl_set_busy(ctsio);
2236 		goto badjuju;
2237 	}
2238 	mtx_lock(&lun->lun_lock);
2239 	mtx_unlock(&softc->ctl_lock);
2240 
2241 	/*
2242 	 * If the LUN is invalid, pretend that it doesn't exist.
2243 	 * It will go away as soon as all pending I/Os completed.
2244 	 */
2245 	if (lun->flags & CTL_LUN_DISABLED) {
2246 		mtx_unlock(&lun->lun_lock);
2247 		ctl_set_busy(ctsio);
2248 		goto badjuju;
2249 	}
2250 
2251 	entry = ctl_get_cmd_entry(ctsio, NULL);
2252 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2253 		mtx_unlock(&lun->lun_lock);
2254 		goto badjuju;
2255 	}
2256 
2257 	CTL_LUN(ctsio) = lun;
2258 	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2259 
2260 	/*
2261 	 * Every I/O goes into the OOA queue for a
2262 	 * particular LUN, and stays there until completion.
2263 	 */
2264 #ifdef CTL_TIME_IO
2265 	if (TAILQ_EMPTY(&lun->ooa_queue))
2266 		lun->idle_time += getsbinuptime() - lun->last_busy;
2267 #endif
2268 	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2269 
2270 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2271 		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2272 		 ooa_links))) {
2273 	case CTL_ACTION_BLOCK:
2274 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2275 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2276 				  blocked_links);
2277 		mtx_unlock(&lun->lun_lock);
2278 		break;
2279 	case CTL_ACTION_PASS:
2280 	case CTL_ACTION_SKIP:
2281 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2282 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2283 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2284 			mtx_unlock(&lun->lun_lock);
2285 		} else {
2286 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2287 			mtx_unlock(&lun->lun_lock);
2288 
2289 			/* send msg back to other side */
2290 			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2291 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2292 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2293 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2294 			    sizeof(msg_info.hdr), M_WAITOK);
2295 		}
2296 		break;
2297 	case CTL_ACTION_OVERLAP:
2298 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2299 		mtx_unlock(&lun->lun_lock);
2300 		ctl_set_overlapped_cmd(ctsio);
2301 		goto badjuju;
2302 	case CTL_ACTION_OVERLAP_TAG:
2303 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2304 		mtx_unlock(&lun->lun_lock);
2305 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2306 		goto badjuju;
2307 	case CTL_ACTION_ERROR:
2308 	default:
2309 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2310 		mtx_unlock(&lun->lun_lock);
2311 
2312 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2313 					 /*retry_count*/ 0);
2314 badjuju:
2315 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2316 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2317 		msg_info.hdr.serializing_sc = NULL;
2318 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2319 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2320 		    sizeof(msg_info.scsi), M_WAITOK);
2321 		ctl_free_io((union ctl_io *)ctsio);
2322 		break;
2323 	}
2324 }
2325 
2326 /*
2327  * Returns 0 for success, errno for failure.
2328  */
2329 static void
2330 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2331 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2332 {
2333 	union ctl_io *io;
2334 
2335 	mtx_lock(&lun->lun_lock);
2336 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2337 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2338 	     ooa_links)) {
2339 		struct ctl_ooa_entry *entry;
2340 
2341 		/*
2342 		 * If we've got more than we can fit, just count the
2343 		 * remaining entries.
2344 		 */
2345 		if (*cur_fill_num >= ooa_hdr->alloc_num)
2346 			continue;
2347 
2348 		entry = &kern_entries[*cur_fill_num];
2349 
2350 		entry->tag_num = io->scsiio.tag_num;
2351 		entry->lun_num = lun->lun;
2352 #ifdef CTL_TIME_IO
2353 		entry->start_bt = io->io_hdr.start_bt;
2354 #endif
2355 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2356 		entry->cdb_len = io->scsiio.cdb_len;
2357 		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2358 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2359 
2360 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2361 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2362 
2363 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2364 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2365 
2366 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2367 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2368 
2369 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2370 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2371 	}
2372 	mtx_unlock(&lun->lun_lock);
2373 }
2374 
2375 static void *
2376 ctl_copyin_alloc(void *user_addr, unsigned int len, char *error_str,
2377 		 size_t error_str_len)
2378 {
2379 	void *kptr;
2380 
2381 	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2382 
2383 	if (copyin(user_addr, kptr, len) != 0) {
2384 		snprintf(error_str, error_str_len, "Error copying %d bytes "
2385 			 "from user address %p to kernel address %p", len,
2386 			 user_addr, kptr);
2387 		free(kptr, M_CTL);
2388 		return (NULL);
2389 	}
2390 
2391 	return (kptr);
2392 }
2393 
2394 static void
2395 ctl_free_args(int num_args, struct ctl_be_arg *args)
2396 {
2397 	int i;
2398 
2399 	if (args == NULL)
2400 		return;
2401 
2402 	for (i = 0; i < num_args; i++) {
2403 		free(args[i].kname, M_CTL);
2404 		free(args[i].kvalue, M_CTL);
2405 	}
2406 
2407 	free(args, M_CTL);
2408 }
2409 
2410 static struct ctl_be_arg *
2411 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2412 		char *error_str, size_t error_str_len)
2413 {
2414 	struct ctl_be_arg *args;
2415 	int i;
2416 
2417 	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2418 				error_str, error_str_len);
2419 
2420 	if (args == NULL)
2421 		goto bailout;
2422 
2423 	for (i = 0; i < num_args; i++) {
2424 		args[i].kname = NULL;
2425 		args[i].kvalue = NULL;
2426 	}
2427 
2428 	for (i = 0; i < num_args; i++) {
2429 		uint8_t *tmpptr;
2430 
2431 		if (args[i].namelen == 0) {
2432 			snprintf(error_str, error_str_len, "Argument %d "
2433 				 "name length is zero", i);
2434 			goto bailout;
2435 		}
2436 
2437 		args[i].kname = ctl_copyin_alloc(args[i].name,
2438 			args[i].namelen, error_str, error_str_len);
2439 		if (args[i].kname == NULL)
2440 			goto bailout;
2441 
2442 		if (args[i].kname[args[i].namelen - 1] != '\0') {
2443 			snprintf(error_str, error_str_len, "Argument %d "
2444 				 "name is not NUL-terminated", i);
2445 			goto bailout;
2446 		}
2447 
2448 		if (args[i].flags & CTL_BEARG_RD) {
2449 			if (args[i].vallen == 0) {
2450 				snprintf(error_str, error_str_len, "Argument %d "
2451 					 "value length is zero", i);
2452 				goto bailout;
2453 			}
2454 
2455 			tmpptr = ctl_copyin_alloc(args[i].value,
2456 				args[i].vallen, error_str, error_str_len);
2457 			if (tmpptr == NULL)
2458 				goto bailout;
2459 
2460 			if ((args[i].flags & CTL_BEARG_ASCII)
2461 			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2462 				snprintf(error_str, error_str_len, "Argument "
2463 				    "%d value is not NUL-terminated", i);
2464 				free(tmpptr, M_CTL);
2465 				goto bailout;
2466 			}
2467 			args[i].kvalue = tmpptr;
2468 		} else {
2469 			args[i].kvalue = malloc(args[i].vallen,
2470 			    M_CTL, M_WAITOK | M_ZERO);
2471 		}
2472 	}
2473 
2474 	return (args);
2475 bailout:
2476 
2477 	ctl_free_args(num_args, args);
2478 
2479 	return (NULL);
2480 }
2481 
2482 static void
2483 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2484 {
2485 	int i;
2486 
2487 	for (i = 0; i < num_args; i++) {
2488 		if (args[i].flags & CTL_BEARG_WR)
2489 			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2490 	}
2491 }
2492 
2493 /*
2494  * Escape characters that are illegal or not recommended in XML.
2495  */
2496 int
2497 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2498 {
2499 	char *end = str + size;
2500 	int retval;
2501 
2502 	retval = 0;
2503 
2504 	for (; *str && str < end; str++) {
2505 		switch (*str) {
2506 		case '&':
2507 			retval = sbuf_printf(sb, "&amp;");
2508 			break;
2509 		case '>':
2510 			retval = sbuf_printf(sb, "&gt;");
2511 			break;
2512 		case '<':
2513 			retval = sbuf_printf(sb, "&lt;");
2514 			break;
2515 		default:
2516 			retval = sbuf_putc(sb, *str);
2517 			break;
2518 		}
2519 
2520 		if (retval != 0)
2521 			break;
2522 
2523 	}
2524 
2525 	return (retval);
2526 }
2527 
2528 static void
2529 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2530 {
2531 	struct scsi_vpd_id_descriptor *desc;
2532 	int i;
2533 
2534 	if (id == NULL || id->len < 4)
2535 		return;
2536 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2537 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2538 	case SVPD_ID_TYPE_T10:
2539 		sbuf_printf(sb, "t10.");
2540 		break;
2541 	case SVPD_ID_TYPE_EUI64:
2542 		sbuf_printf(sb, "eui.");
2543 		break;
2544 	case SVPD_ID_TYPE_NAA:
2545 		sbuf_printf(sb, "naa.");
2546 		break;
2547 	case SVPD_ID_TYPE_SCSI_NAME:
2548 		break;
2549 	}
2550 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2551 	case SVPD_ID_CODESET_BINARY:
2552 		for (i = 0; i < desc->length; i++)
2553 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2554 		break;
2555 	case SVPD_ID_CODESET_ASCII:
2556 		sbuf_printf(sb, "%.*s", (int)desc->length,
2557 		    (char *)desc->identifier);
2558 		break;
2559 	case SVPD_ID_CODESET_UTF8:
2560 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2561 		break;
2562 	}
2563 }
2564 
2565 static int
2566 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2567 	  struct thread *td)
2568 {
2569 	struct ctl_softc *softc = dev->si_drv1;
2570 	struct ctl_port *port;
2571 	struct ctl_lun *lun;
2572 	int retval;
2573 
2574 	retval = 0;
2575 
2576 	switch (cmd) {
2577 	case CTL_IO:
2578 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2579 		break;
2580 	case CTL_ENABLE_PORT:
2581 	case CTL_DISABLE_PORT:
2582 	case CTL_SET_PORT_WWNS: {
2583 		struct ctl_port *port;
2584 		struct ctl_port_entry *entry;
2585 
2586 		entry = (struct ctl_port_entry *)addr;
2587 
2588 		mtx_lock(&softc->ctl_lock);
2589 		STAILQ_FOREACH(port, &softc->port_list, links) {
2590 			int action, done;
2591 
2592 			if (port->targ_port < softc->port_min ||
2593 			    port->targ_port >= softc->port_max)
2594 				continue;
2595 
2596 			action = 0;
2597 			done = 0;
2598 			if ((entry->port_type == CTL_PORT_NONE)
2599 			 && (entry->targ_port == port->targ_port)) {
2600 				/*
2601 				 * If the user only wants to enable or
2602 				 * disable or set WWNs on a specific port,
2603 				 * do the operation and we're done.
2604 				 */
2605 				action = 1;
2606 				done = 1;
2607 			} else if (entry->port_type & port->port_type) {
2608 				/*
2609 				 * Compare the user's type mask with the
2610 				 * particular frontend type to see if we
2611 				 * have a match.
2612 				 */
2613 				action = 1;
2614 				done = 0;
2615 
2616 				/*
2617 				 * Make sure the user isn't trying to set
2618 				 * WWNs on multiple ports at the same time.
2619 				 */
2620 				if (cmd == CTL_SET_PORT_WWNS) {
2621 					printf("%s: Can't set WWNs on "
2622 					       "multiple ports\n", __func__);
2623 					retval = EINVAL;
2624 					break;
2625 				}
2626 			}
2627 			if (action == 0)
2628 				continue;
2629 
2630 			/*
2631 			 * XXX KDM we have to drop the lock here, because
2632 			 * the online/offline operations can potentially
2633 			 * block.  We need to reference count the frontends
2634 			 * so they can't go away,
2635 			 */
2636 			if (cmd == CTL_ENABLE_PORT) {
2637 				mtx_unlock(&softc->ctl_lock);
2638 				ctl_port_online(port);
2639 				mtx_lock(&softc->ctl_lock);
2640 			} else if (cmd == CTL_DISABLE_PORT) {
2641 				mtx_unlock(&softc->ctl_lock);
2642 				ctl_port_offline(port);
2643 				mtx_lock(&softc->ctl_lock);
2644 			} else if (cmd == CTL_SET_PORT_WWNS) {
2645 				ctl_port_set_wwns(port,
2646 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2647 				    1 : 0, entry->wwnn,
2648 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2649 				    1 : 0, entry->wwpn);
2650 			}
2651 			if (done != 0)
2652 				break;
2653 		}
2654 		mtx_unlock(&softc->ctl_lock);
2655 		break;
2656 	}
2657 	case CTL_GET_OOA: {
2658 		struct ctl_ooa *ooa_hdr;
2659 		struct ctl_ooa_entry *entries;
2660 		uint32_t cur_fill_num;
2661 
2662 		ooa_hdr = (struct ctl_ooa *)addr;
2663 
2664 		if ((ooa_hdr->alloc_len == 0)
2665 		 || (ooa_hdr->alloc_num == 0)) {
2666 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2667 			       "must be non-zero\n", __func__,
2668 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2669 			retval = EINVAL;
2670 			break;
2671 		}
2672 
2673 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2674 		    sizeof(struct ctl_ooa_entry))) {
2675 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2676 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2677 			       __func__, ooa_hdr->alloc_len,
2678 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2679 			retval = EINVAL;
2680 			break;
2681 		}
2682 
2683 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2684 		if (entries == NULL) {
2685 			printf("%s: could not allocate %d bytes for OOA "
2686 			       "dump\n", __func__, ooa_hdr->alloc_len);
2687 			retval = ENOMEM;
2688 			break;
2689 		}
2690 
2691 		mtx_lock(&softc->ctl_lock);
2692 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2693 		    (ooa_hdr->lun_num >= CTL_MAX_LUNS ||
2694 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2695 			mtx_unlock(&softc->ctl_lock);
2696 			free(entries, M_CTL);
2697 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2698 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2699 			retval = EINVAL;
2700 			break;
2701 		}
2702 
2703 		cur_fill_num = 0;
2704 
2705 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2706 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2707 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2708 				    ooa_hdr, entries);
2709 			}
2710 		} else {
2711 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2712 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2713 			    entries);
2714 		}
2715 		mtx_unlock(&softc->ctl_lock);
2716 
2717 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2718 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2719 			sizeof(struct ctl_ooa_entry);
2720 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2721 		if (retval != 0) {
2722 			printf("%s: error copying out %d bytes for OOA dump\n",
2723 			       __func__, ooa_hdr->fill_len);
2724 		}
2725 
2726 		getbinuptime(&ooa_hdr->cur_bt);
2727 
2728 		if (cur_fill_num > ooa_hdr->alloc_num) {
2729 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2730 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2731 		} else {
2732 			ooa_hdr->dropped_num = 0;
2733 			ooa_hdr->status = CTL_OOA_OK;
2734 		}
2735 
2736 		free(entries, M_CTL);
2737 		break;
2738 	}
2739 	case CTL_DELAY_IO: {
2740 		struct ctl_io_delay_info *delay_info;
2741 
2742 		delay_info = (struct ctl_io_delay_info *)addr;
2743 
2744 #ifdef CTL_IO_DELAY
2745 		mtx_lock(&softc->ctl_lock);
2746 		if (delay_info->lun_id >= CTL_MAX_LUNS ||
2747 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2748 			mtx_unlock(&softc->ctl_lock);
2749 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2750 			break;
2751 		}
2752 		mtx_lock(&lun->lun_lock);
2753 		mtx_unlock(&softc->ctl_lock);
2754 		delay_info->status = CTL_DELAY_STATUS_OK;
2755 		switch (delay_info->delay_type) {
2756 		case CTL_DELAY_TYPE_CONT:
2757 		case CTL_DELAY_TYPE_ONESHOT:
2758 			break;
2759 		default:
2760 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2761 			break;
2762 		}
2763 		switch (delay_info->delay_loc) {
2764 		case CTL_DELAY_LOC_DATAMOVE:
2765 			lun->delay_info.datamove_type = delay_info->delay_type;
2766 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2767 			break;
2768 		case CTL_DELAY_LOC_DONE:
2769 			lun->delay_info.done_type = delay_info->delay_type;
2770 			lun->delay_info.done_delay = delay_info->delay_secs;
2771 			break;
2772 		default:
2773 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2774 			break;
2775 		}
2776 		mtx_unlock(&lun->lun_lock);
2777 #else
2778 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2779 #endif /* CTL_IO_DELAY */
2780 		break;
2781 	}
2782 #ifdef CTL_LEGACY_STATS
2783 	case CTL_GETSTATS: {
2784 		struct ctl_stats *stats = (struct ctl_stats *)addr;
2785 		int i;
2786 
2787 		/*
2788 		 * XXX KDM no locking here.  If the LUN list changes,
2789 		 * things can blow up.
2790 		 */
2791 		i = 0;
2792 		stats->status = CTL_SS_OK;
2793 		stats->fill_len = 0;
2794 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2795 			if (stats->fill_len + sizeof(lun->legacy_stats) >
2796 			    stats->alloc_len) {
2797 				stats->status = CTL_SS_NEED_MORE_SPACE;
2798 				break;
2799 			}
2800 			retval = copyout(&lun->legacy_stats, &stats->lun_stats[i++],
2801 					 sizeof(lun->legacy_stats));
2802 			if (retval != 0)
2803 				break;
2804 			stats->fill_len += sizeof(lun->legacy_stats);
2805 		}
2806 		stats->num_luns = softc->num_luns;
2807 		stats->flags = CTL_STATS_FLAG_NONE;
2808 #ifdef CTL_TIME_IO
2809 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
2810 #endif
2811 		getnanouptime(&stats->timestamp);
2812 		break;
2813 	}
2814 #endif /* CTL_LEGACY_STATS */
2815 	case CTL_ERROR_INJECT: {
2816 		struct ctl_error_desc *err_desc, *new_err_desc;
2817 
2818 		err_desc = (struct ctl_error_desc *)addr;
2819 
2820 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2821 				      M_WAITOK | M_ZERO);
2822 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2823 
2824 		mtx_lock(&softc->ctl_lock);
2825 		if (err_desc->lun_id >= CTL_MAX_LUNS ||
2826 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2827 			mtx_unlock(&softc->ctl_lock);
2828 			free(new_err_desc, M_CTL);
2829 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2830 			       __func__, (uintmax_t)err_desc->lun_id);
2831 			retval = EINVAL;
2832 			break;
2833 		}
2834 		mtx_lock(&lun->lun_lock);
2835 		mtx_unlock(&softc->ctl_lock);
2836 
2837 		/*
2838 		 * We could do some checking here to verify the validity
2839 		 * of the request, but given the complexity of error
2840 		 * injection requests, the checking logic would be fairly
2841 		 * complex.
2842 		 *
2843 		 * For now, if the request is invalid, it just won't get
2844 		 * executed and might get deleted.
2845 		 */
2846 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2847 
2848 		/*
2849 		 * XXX KDM check to make sure the serial number is unique,
2850 		 * in case we somehow manage to wrap.  That shouldn't
2851 		 * happen for a very long time, but it's the right thing to
2852 		 * do.
2853 		 */
2854 		new_err_desc->serial = lun->error_serial;
2855 		err_desc->serial = lun->error_serial;
2856 		lun->error_serial++;
2857 
2858 		mtx_unlock(&lun->lun_lock);
2859 		break;
2860 	}
2861 	case CTL_ERROR_INJECT_DELETE: {
2862 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2863 		int delete_done;
2864 
2865 		delete_desc = (struct ctl_error_desc *)addr;
2866 		delete_done = 0;
2867 
2868 		mtx_lock(&softc->ctl_lock);
2869 		if (delete_desc->lun_id >= CTL_MAX_LUNS ||
2870 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2871 			mtx_unlock(&softc->ctl_lock);
2872 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2873 			       __func__, (uintmax_t)delete_desc->lun_id);
2874 			retval = EINVAL;
2875 			break;
2876 		}
2877 		mtx_lock(&lun->lun_lock);
2878 		mtx_unlock(&softc->ctl_lock);
2879 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2880 			if (desc->serial != delete_desc->serial)
2881 				continue;
2882 
2883 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2884 				      links);
2885 			free(desc, M_CTL);
2886 			delete_done = 1;
2887 		}
2888 		mtx_unlock(&lun->lun_lock);
2889 		if (delete_done == 0) {
2890 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2891 			       "error serial %ju on LUN %u\n", __func__,
2892 			       delete_desc->serial, delete_desc->lun_id);
2893 			retval = EINVAL;
2894 			break;
2895 		}
2896 		break;
2897 	}
2898 	case CTL_DUMP_STRUCTS: {
2899 		int j, k;
2900 		struct ctl_port *port;
2901 		struct ctl_frontend *fe;
2902 
2903 		mtx_lock(&softc->ctl_lock);
2904 		printf("CTL Persistent Reservation information start:\n");
2905 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2906 			mtx_lock(&lun->lun_lock);
2907 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2908 				mtx_unlock(&lun->lun_lock);
2909 				continue;
2910 			}
2911 
2912 			for (j = 0; j < CTL_MAX_PORTS; j++) {
2913 				if (lun->pr_keys[j] == NULL)
2914 					continue;
2915 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2916 					if (lun->pr_keys[j][k] == 0)
2917 						continue;
2918 					printf("  LUN %ju port %d iid %d key "
2919 					       "%#jx\n", lun->lun, j, k,
2920 					       (uintmax_t)lun->pr_keys[j][k]);
2921 				}
2922 			}
2923 			mtx_unlock(&lun->lun_lock);
2924 		}
2925 		printf("CTL Persistent Reservation information end\n");
2926 		printf("CTL Ports:\n");
2927 		STAILQ_FOREACH(port, &softc->port_list, links) {
2928 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2929 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2930 			       port->frontend->name, port->port_type,
2931 			       port->physical_port, port->virtual_port,
2932 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2933 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2934 				if (port->wwpn_iid[j].in_use == 0 &&
2935 				    port->wwpn_iid[j].wwpn == 0 &&
2936 				    port->wwpn_iid[j].name == NULL)
2937 					continue;
2938 
2939 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2940 				    j, port->wwpn_iid[j].in_use,
2941 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2942 				    port->wwpn_iid[j].name);
2943 			}
2944 		}
2945 		printf("CTL Port information end\n");
2946 		mtx_unlock(&softc->ctl_lock);
2947 		/*
2948 		 * XXX KDM calling this without a lock.  We'd likely want
2949 		 * to drop the lock before calling the frontend's dump
2950 		 * routine anyway.
2951 		 */
2952 		printf("CTL Frontends:\n");
2953 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2954 			printf("  Frontend '%s'\n", fe->name);
2955 			if (fe->fe_dump != NULL)
2956 				fe->fe_dump();
2957 		}
2958 		printf("CTL Frontend information end\n");
2959 		break;
2960 	}
2961 	case CTL_LUN_REQ: {
2962 		struct ctl_lun_req *lun_req;
2963 		struct ctl_backend_driver *backend;
2964 
2965 		lun_req = (struct ctl_lun_req *)addr;
2966 
2967 		backend = ctl_backend_find(lun_req->backend);
2968 		if (backend == NULL) {
2969 			lun_req->status = CTL_LUN_ERROR;
2970 			snprintf(lun_req->error_str,
2971 				 sizeof(lun_req->error_str),
2972 				 "Backend \"%s\" not found.",
2973 				 lun_req->backend);
2974 			break;
2975 		}
2976 		if (lun_req->num_be_args > 0) {
2977 			lun_req->kern_be_args = ctl_copyin_args(
2978 				lun_req->num_be_args,
2979 				lun_req->be_args,
2980 				lun_req->error_str,
2981 				sizeof(lun_req->error_str));
2982 			if (lun_req->kern_be_args == NULL) {
2983 				lun_req->status = CTL_LUN_ERROR;
2984 				break;
2985 			}
2986 		}
2987 
2988 		retval = backend->ioctl(dev, cmd, addr, flag, td);
2989 
2990 		if (lun_req->num_be_args > 0) {
2991 			ctl_copyout_args(lun_req->num_be_args,
2992 				      lun_req->kern_be_args);
2993 			ctl_free_args(lun_req->num_be_args,
2994 				      lun_req->kern_be_args);
2995 		}
2996 		break;
2997 	}
2998 	case CTL_LUN_LIST: {
2999 		struct sbuf *sb;
3000 		struct ctl_lun_list *list;
3001 		struct ctl_option *opt;
3002 
3003 		list = (struct ctl_lun_list *)addr;
3004 
3005 		/*
3006 		 * Allocate a fixed length sbuf here, based on the length
3007 		 * of the user's buffer.  We could allocate an auto-extending
3008 		 * buffer, and then tell the user how much larger our
3009 		 * amount of data is than his buffer, but that presents
3010 		 * some problems:
3011 		 *
3012 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3013 		 *     we can't hold a lock while calling them with an
3014 		 *     auto-extending buffer.
3015  		 *
3016 		 * 2.  There is not currently a LUN reference counting
3017 		 *     mechanism, outside of outstanding transactions on
3018 		 *     the LUN's OOA queue.  So a LUN could go away on us
3019 		 *     while we're getting the LUN number, backend-specific
3020 		 *     information, etc.  Thus, given the way things
3021 		 *     currently work, we need to hold the CTL lock while
3022 		 *     grabbing LUN information.
3023 		 *
3024 		 * So, from the user's standpoint, the best thing to do is
3025 		 * allocate what he thinks is a reasonable buffer length,
3026 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3027 		 * double the buffer length and try again.  (And repeat
3028 		 * that until he succeeds.)
3029 		 */
3030 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3031 		if (sb == NULL) {
3032 			list->status = CTL_LUN_LIST_ERROR;
3033 			snprintf(list->error_str, sizeof(list->error_str),
3034 				 "Unable to allocate %d bytes for LUN list",
3035 				 list->alloc_len);
3036 			break;
3037 		}
3038 
3039 		sbuf_printf(sb, "<ctllunlist>\n");
3040 
3041 		mtx_lock(&softc->ctl_lock);
3042 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3043 			mtx_lock(&lun->lun_lock);
3044 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3045 					     (uintmax_t)lun->lun);
3046 
3047 			/*
3048 			 * Bail out as soon as we see that we've overfilled
3049 			 * the buffer.
3050 			 */
3051 			if (retval != 0)
3052 				break;
3053 
3054 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3055 					     "</backend_type>\n",
3056 					     (lun->backend == NULL) ?  "none" :
3057 					     lun->backend->name);
3058 
3059 			if (retval != 0)
3060 				break;
3061 
3062 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3063 					     lun->be_lun->lun_type);
3064 
3065 			if (retval != 0)
3066 				break;
3067 
3068 			if (lun->backend == NULL) {
3069 				retval = sbuf_printf(sb, "</lun>\n");
3070 				if (retval != 0)
3071 					break;
3072 				continue;
3073 			}
3074 
3075 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3076 					     (lun->be_lun->maxlba > 0) ?
3077 					     lun->be_lun->maxlba + 1 : 0);
3078 
3079 			if (retval != 0)
3080 				break;
3081 
3082 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3083 					     lun->be_lun->blocksize);
3084 
3085 			if (retval != 0)
3086 				break;
3087 
3088 			retval = sbuf_printf(sb, "\t<serial_number>");
3089 
3090 			if (retval != 0)
3091 				break;
3092 
3093 			retval = ctl_sbuf_printf_esc(sb,
3094 			    lun->be_lun->serial_num,
3095 			    sizeof(lun->be_lun->serial_num));
3096 
3097 			if (retval != 0)
3098 				break;
3099 
3100 			retval = sbuf_printf(sb, "</serial_number>\n");
3101 
3102 			if (retval != 0)
3103 				break;
3104 
3105 			retval = sbuf_printf(sb, "\t<device_id>");
3106 
3107 			if (retval != 0)
3108 				break;
3109 
3110 			retval = ctl_sbuf_printf_esc(sb,
3111 			    lun->be_lun->device_id,
3112 			    sizeof(lun->be_lun->device_id));
3113 
3114 			if (retval != 0)
3115 				break;
3116 
3117 			retval = sbuf_printf(sb, "</device_id>\n");
3118 
3119 			if (retval != 0)
3120 				break;
3121 
3122 			if (lun->backend->lun_info != NULL) {
3123 				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3124 				if (retval != 0)
3125 					break;
3126 			}
3127 			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3128 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3129 				    opt->name, opt->value, opt->name);
3130 				if (retval != 0)
3131 					break;
3132 			}
3133 
3134 			retval = sbuf_printf(sb, "</lun>\n");
3135 
3136 			if (retval != 0)
3137 				break;
3138 			mtx_unlock(&lun->lun_lock);
3139 		}
3140 		if (lun != NULL)
3141 			mtx_unlock(&lun->lun_lock);
3142 		mtx_unlock(&softc->ctl_lock);
3143 
3144 		if ((retval != 0)
3145 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3146 			retval = 0;
3147 			sbuf_delete(sb);
3148 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3149 			snprintf(list->error_str, sizeof(list->error_str),
3150 				 "Out of space, %d bytes is too small",
3151 				 list->alloc_len);
3152 			break;
3153 		}
3154 
3155 		sbuf_finish(sb);
3156 
3157 		retval = copyout(sbuf_data(sb), list->lun_xml,
3158 				 sbuf_len(sb) + 1);
3159 
3160 		list->fill_len = sbuf_len(sb) + 1;
3161 		list->status = CTL_LUN_LIST_OK;
3162 		sbuf_delete(sb);
3163 		break;
3164 	}
3165 	case CTL_ISCSI: {
3166 		struct ctl_iscsi *ci;
3167 		struct ctl_frontend *fe;
3168 
3169 		ci = (struct ctl_iscsi *)addr;
3170 
3171 		fe = ctl_frontend_find("iscsi");
3172 		if (fe == NULL) {
3173 			ci->status = CTL_ISCSI_ERROR;
3174 			snprintf(ci->error_str, sizeof(ci->error_str),
3175 			    "Frontend \"iscsi\" not found.");
3176 			break;
3177 		}
3178 
3179 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3180 		break;
3181 	}
3182 	case CTL_PORT_REQ: {
3183 		struct ctl_req *req;
3184 		struct ctl_frontend *fe;
3185 
3186 		req = (struct ctl_req *)addr;
3187 
3188 		fe = ctl_frontend_find(req->driver);
3189 		if (fe == NULL) {
3190 			req->status = CTL_LUN_ERROR;
3191 			snprintf(req->error_str, sizeof(req->error_str),
3192 			    "Frontend \"%s\" not found.", req->driver);
3193 			break;
3194 		}
3195 		if (req->num_args > 0) {
3196 			req->kern_args = ctl_copyin_args(req->num_args,
3197 			    req->args, req->error_str, sizeof(req->error_str));
3198 			if (req->kern_args == NULL) {
3199 				req->status = CTL_LUN_ERROR;
3200 				break;
3201 			}
3202 		}
3203 
3204 		if (fe->ioctl)
3205 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3206 		else
3207 			retval = ENODEV;
3208 
3209 		if (req->num_args > 0) {
3210 			ctl_copyout_args(req->num_args, req->kern_args);
3211 			ctl_free_args(req->num_args, req->kern_args);
3212 		}
3213 		break;
3214 	}
3215 	case CTL_PORT_LIST: {
3216 		struct sbuf *sb;
3217 		struct ctl_port *port;
3218 		struct ctl_lun_list *list;
3219 		struct ctl_option *opt;
3220 		int j;
3221 		uint32_t plun;
3222 
3223 		list = (struct ctl_lun_list *)addr;
3224 
3225 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3226 		if (sb == NULL) {
3227 			list->status = CTL_LUN_LIST_ERROR;
3228 			snprintf(list->error_str, sizeof(list->error_str),
3229 				 "Unable to allocate %d bytes for LUN list",
3230 				 list->alloc_len);
3231 			break;
3232 		}
3233 
3234 		sbuf_printf(sb, "<ctlportlist>\n");
3235 
3236 		mtx_lock(&softc->ctl_lock);
3237 		STAILQ_FOREACH(port, &softc->port_list, links) {
3238 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3239 					     (uintmax_t)port->targ_port);
3240 
3241 			/*
3242 			 * Bail out as soon as we see that we've overfilled
3243 			 * the buffer.
3244 			 */
3245 			if (retval != 0)
3246 				break;
3247 
3248 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3249 			    "</frontend_type>\n", port->frontend->name);
3250 			if (retval != 0)
3251 				break;
3252 
3253 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3254 					     port->port_type);
3255 			if (retval != 0)
3256 				break;
3257 
3258 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3259 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3260 			if (retval != 0)
3261 				break;
3262 
3263 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3264 			    port->port_name);
3265 			if (retval != 0)
3266 				break;
3267 
3268 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3269 			    port->physical_port);
3270 			if (retval != 0)
3271 				break;
3272 
3273 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3274 			    port->virtual_port);
3275 			if (retval != 0)
3276 				break;
3277 
3278 			if (port->target_devid != NULL) {
3279 				sbuf_printf(sb, "\t<target>");
3280 				ctl_id_sbuf(port->target_devid, sb);
3281 				sbuf_printf(sb, "</target>\n");
3282 			}
3283 
3284 			if (port->port_devid != NULL) {
3285 				sbuf_printf(sb, "\t<port>");
3286 				ctl_id_sbuf(port->port_devid, sb);
3287 				sbuf_printf(sb, "</port>\n");
3288 			}
3289 
3290 			if (port->port_info != NULL) {
3291 				retval = port->port_info(port->onoff_arg, sb);
3292 				if (retval != 0)
3293 					break;
3294 			}
3295 			STAILQ_FOREACH(opt, &port->options, links) {
3296 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3297 				    opt->name, opt->value, opt->name);
3298 				if (retval != 0)
3299 					break;
3300 			}
3301 
3302 			if (port->lun_map != NULL) {
3303 				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3304 				for (j = 0; j < port->lun_map_size; j++) {
3305 					plun = ctl_lun_map_from_port(port, j);
3306 					if (plun == UINT32_MAX)
3307 						continue;
3308 					sbuf_printf(sb,
3309 					    "\t<lun id=\"%u\">%u</lun>\n",
3310 					    j, plun);
3311 				}
3312 			}
3313 
3314 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3315 				if (port->wwpn_iid[j].in_use == 0 ||
3316 				    (port->wwpn_iid[j].wwpn == 0 &&
3317 				     port->wwpn_iid[j].name == NULL))
3318 					continue;
3319 
3320 				if (port->wwpn_iid[j].name != NULL)
3321 					retval = sbuf_printf(sb,
3322 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3323 					    j, port->wwpn_iid[j].name);
3324 				else
3325 					retval = sbuf_printf(sb,
3326 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3327 					    j, port->wwpn_iid[j].wwpn);
3328 				if (retval != 0)
3329 					break;
3330 			}
3331 			if (retval != 0)
3332 				break;
3333 
3334 			retval = sbuf_printf(sb, "</targ_port>\n");
3335 			if (retval != 0)
3336 				break;
3337 		}
3338 		mtx_unlock(&softc->ctl_lock);
3339 
3340 		if ((retval != 0)
3341 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3342 			retval = 0;
3343 			sbuf_delete(sb);
3344 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3345 			snprintf(list->error_str, sizeof(list->error_str),
3346 				 "Out of space, %d bytes is too small",
3347 				 list->alloc_len);
3348 			break;
3349 		}
3350 
3351 		sbuf_finish(sb);
3352 
3353 		retval = copyout(sbuf_data(sb), list->lun_xml,
3354 				 sbuf_len(sb) + 1);
3355 
3356 		list->fill_len = sbuf_len(sb) + 1;
3357 		list->status = CTL_LUN_LIST_OK;
3358 		sbuf_delete(sb);
3359 		break;
3360 	}
3361 	case CTL_LUN_MAP: {
3362 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3363 		struct ctl_port *port;
3364 
3365 		mtx_lock(&softc->ctl_lock);
3366 		if (lm->port < softc->port_min ||
3367 		    lm->port >= softc->port_max ||
3368 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3369 			mtx_unlock(&softc->ctl_lock);
3370 			return (ENXIO);
3371 		}
3372 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3373 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3374 				if (ctl_lun_map_to_port(port, lun->lun) ==
3375 				    UINT32_MAX)
3376 					continue;
3377 				mtx_lock(&lun->lun_lock);
3378 				ctl_est_ua_port(lun, lm->port, -1,
3379 				    CTL_UA_LUN_CHANGE);
3380 				mtx_unlock(&lun->lun_lock);
3381 			}
3382 		}
3383 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3384 		if (lm->plun != UINT32_MAX) {
3385 			if (lm->lun == UINT32_MAX)
3386 				retval = ctl_lun_map_unset(port, lm->plun);
3387 			else if (lm->lun < CTL_MAX_LUNS &&
3388 			    softc->ctl_luns[lm->lun] != NULL)
3389 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3390 			else
3391 				return (ENXIO);
3392 		} else {
3393 			if (lm->lun == UINT32_MAX)
3394 				retval = ctl_lun_map_deinit(port);
3395 			else
3396 				retval = ctl_lun_map_init(port);
3397 		}
3398 		if (port->status & CTL_PORT_STATUS_ONLINE)
3399 			ctl_isc_announce_port(port);
3400 		break;
3401 	}
3402 	case CTL_GET_LUN_STATS: {
3403 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3404 		int i;
3405 
3406 		/*
3407 		 * XXX KDM no locking here.  If the LUN list changes,
3408 		 * things can blow up.
3409 		 */
3410 		i = 0;
3411 		stats->status = CTL_SS_OK;
3412 		stats->fill_len = 0;
3413 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3414 			if (lun->lun < stats->first_item)
3415 				continue;
3416 			if (stats->fill_len + sizeof(lun->stats) >
3417 			    stats->alloc_len) {
3418 				stats->status = CTL_SS_NEED_MORE_SPACE;
3419 				break;
3420 			}
3421 			retval = copyout(&lun->stats, &stats->stats[i++],
3422 					 sizeof(lun->stats));
3423 			if (retval != 0)
3424 				break;
3425 			stats->fill_len += sizeof(lun->stats);
3426 		}
3427 		stats->num_items = softc->num_luns;
3428 		stats->flags = CTL_STATS_FLAG_NONE;
3429 #ifdef CTL_TIME_IO
3430 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3431 #endif
3432 		getnanouptime(&stats->timestamp);
3433 		break;
3434 	}
3435 	case CTL_GET_PORT_STATS: {
3436 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3437 		int i;
3438 
3439 		/*
3440 		 * XXX KDM no locking here.  If the LUN list changes,
3441 		 * things can blow up.
3442 		 */
3443 		i = 0;
3444 		stats->status = CTL_SS_OK;
3445 		stats->fill_len = 0;
3446 		STAILQ_FOREACH(port, &softc->port_list, links) {
3447 			if (port->targ_port < stats->first_item)
3448 				continue;
3449 			if (stats->fill_len + sizeof(port->stats) >
3450 			    stats->alloc_len) {
3451 				stats->status = CTL_SS_NEED_MORE_SPACE;
3452 				break;
3453 			}
3454 			retval = copyout(&port->stats, &stats->stats[i++],
3455 					 sizeof(port->stats));
3456 			if (retval != 0)
3457 				break;
3458 			stats->fill_len += sizeof(port->stats);
3459 		}
3460 		stats->num_items = softc->num_ports;
3461 		stats->flags = CTL_STATS_FLAG_NONE;
3462 #ifdef CTL_TIME_IO
3463 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3464 #endif
3465 		getnanouptime(&stats->timestamp);
3466 		break;
3467 	}
3468 	default: {
3469 		/* XXX KDM should we fix this? */
3470 #if 0
3471 		struct ctl_backend_driver *backend;
3472 		unsigned int type;
3473 		int found;
3474 
3475 		found = 0;
3476 
3477 		/*
3478 		 * We encode the backend type as the ioctl type for backend
3479 		 * ioctls.  So parse it out here, and then search for a
3480 		 * backend of this type.
3481 		 */
3482 		type = _IOC_TYPE(cmd);
3483 
3484 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3485 			if (backend->type == type) {
3486 				found = 1;
3487 				break;
3488 			}
3489 		}
3490 		if (found == 0) {
3491 			printf("ctl: unknown ioctl command %#lx or backend "
3492 			       "%d\n", cmd, type);
3493 			retval = EINVAL;
3494 			break;
3495 		}
3496 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3497 #endif
3498 		retval = ENOTTY;
3499 		break;
3500 	}
3501 	}
3502 	return (retval);
3503 }
3504 
3505 uint32_t
3506 ctl_get_initindex(struct ctl_nexus *nexus)
3507 {
3508 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3509 }
3510 
3511 int
3512 ctl_lun_map_init(struct ctl_port *port)
3513 {
3514 	struct ctl_softc *softc = port->ctl_softc;
3515 	struct ctl_lun *lun;
3516 	int size = ctl_lun_map_size;
3517 	uint32_t i;
3518 
3519 	if (port->lun_map == NULL || port->lun_map_size < size) {
3520 		port->lun_map_size = 0;
3521 		free(port->lun_map, M_CTL);
3522 		port->lun_map = malloc(size * sizeof(uint32_t),
3523 		    M_CTL, M_NOWAIT);
3524 	}
3525 	if (port->lun_map == NULL)
3526 		return (ENOMEM);
3527 	for (i = 0; i < size; i++)
3528 		port->lun_map[i] = UINT32_MAX;
3529 	port->lun_map_size = size;
3530 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3531 		if (port->lun_disable != NULL) {
3532 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3533 				port->lun_disable(port->targ_lun_arg, lun->lun);
3534 		}
3535 		ctl_isc_announce_port(port);
3536 	}
3537 	return (0);
3538 }
3539 
3540 int
3541 ctl_lun_map_deinit(struct ctl_port *port)
3542 {
3543 	struct ctl_softc *softc = port->ctl_softc;
3544 	struct ctl_lun *lun;
3545 
3546 	if (port->lun_map == NULL)
3547 		return (0);
3548 	port->lun_map_size = 0;
3549 	free(port->lun_map, M_CTL);
3550 	port->lun_map = NULL;
3551 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3552 		if (port->lun_enable != NULL) {
3553 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3554 				port->lun_enable(port->targ_lun_arg, lun->lun);
3555 		}
3556 		ctl_isc_announce_port(port);
3557 	}
3558 	return (0);
3559 }
3560 
3561 int
3562 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3563 {
3564 	int status;
3565 	uint32_t old;
3566 
3567 	if (port->lun_map == NULL) {
3568 		status = ctl_lun_map_init(port);
3569 		if (status != 0)
3570 			return (status);
3571 	}
3572 	if (plun >= port->lun_map_size)
3573 		return (EINVAL);
3574 	old = port->lun_map[plun];
3575 	port->lun_map[plun] = glun;
3576 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3577 		if (port->lun_enable != NULL)
3578 			port->lun_enable(port->targ_lun_arg, plun);
3579 		ctl_isc_announce_port(port);
3580 	}
3581 	return (0);
3582 }
3583 
3584 int
3585 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3586 {
3587 	uint32_t old;
3588 
3589 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3590 		return (0);
3591 	old = port->lun_map[plun];
3592 	port->lun_map[plun] = UINT32_MAX;
3593 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3594 		if (port->lun_disable != NULL)
3595 			port->lun_disable(port->targ_lun_arg, plun);
3596 		ctl_isc_announce_port(port);
3597 	}
3598 	return (0);
3599 }
3600 
3601 uint32_t
3602 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3603 {
3604 
3605 	if (port == NULL)
3606 		return (UINT32_MAX);
3607 	if (port->lun_map == NULL)
3608 		return (lun_id);
3609 	if (lun_id > port->lun_map_size)
3610 		return (UINT32_MAX);
3611 	return (port->lun_map[lun_id]);
3612 }
3613 
3614 uint32_t
3615 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3616 {
3617 	uint32_t i;
3618 
3619 	if (port == NULL)
3620 		return (UINT32_MAX);
3621 	if (port->lun_map == NULL)
3622 		return (lun_id);
3623 	for (i = 0; i < port->lun_map_size; i++) {
3624 		if (port->lun_map[i] == lun_id)
3625 			return (i);
3626 	}
3627 	return (UINT32_MAX);
3628 }
3629 
3630 uint32_t
3631 ctl_decode_lun(uint64_t encoded)
3632 {
3633 	uint8_t lun[8];
3634 	uint32_t result = 0xffffffff;
3635 
3636 	be64enc(lun, encoded);
3637 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3638 	case RPL_LUNDATA_ATYP_PERIPH:
3639 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3640 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3641 			result = lun[1];
3642 		break;
3643 	case RPL_LUNDATA_ATYP_FLAT:
3644 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3645 		    lun[6] == 0 && lun[7] == 0)
3646 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3647 		break;
3648 	case RPL_LUNDATA_ATYP_EXTLUN:
3649 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3650 		case 0x02:
3651 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3652 			case 0x00:
3653 				result = lun[1];
3654 				break;
3655 			case 0x10:
3656 				result = (lun[1] << 16) + (lun[2] << 8) +
3657 				    lun[3];
3658 				break;
3659 			case 0x20:
3660 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3661 					result = (lun[2] << 24) +
3662 					    (lun[3] << 16) + (lun[4] << 8) +
3663 					    lun[5];
3664 				break;
3665 			}
3666 			break;
3667 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3668 			result = 0xffffffff;
3669 			break;
3670 		}
3671 		break;
3672 	}
3673 	return (result);
3674 }
3675 
3676 uint64_t
3677 ctl_encode_lun(uint32_t decoded)
3678 {
3679 	uint64_t l = decoded;
3680 
3681 	if (l <= 0xff)
3682 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3683 	if (l <= 0x3fff)
3684 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3685 	if (l <= 0xffffff)
3686 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3687 		    (l << 32));
3688 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3689 }
3690 
3691 int
3692 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3693 {
3694 	int i;
3695 
3696 	for (i = first; i < last; i++) {
3697 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3698 			return (i);
3699 	}
3700 	return (-1);
3701 }
3702 
3703 int
3704 ctl_set_mask(uint32_t *mask, uint32_t bit)
3705 {
3706 	uint32_t chunk, piece;
3707 
3708 	chunk = bit >> 5;
3709 	piece = bit % (sizeof(uint32_t) * 8);
3710 
3711 	if ((mask[chunk] & (1 << piece)) != 0)
3712 		return (-1);
3713 	else
3714 		mask[chunk] |= (1 << piece);
3715 
3716 	return (0);
3717 }
3718 
3719 int
3720 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3721 {
3722 	uint32_t chunk, piece;
3723 
3724 	chunk = bit >> 5;
3725 	piece = bit % (sizeof(uint32_t) * 8);
3726 
3727 	if ((mask[chunk] & (1 << piece)) == 0)
3728 		return (-1);
3729 	else
3730 		mask[chunk] &= ~(1 << piece);
3731 
3732 	return (0);
3733 }
3734 
3735 int
3736 ctl_is_set(uint32_t *mask, uint32_t bit)
3737 {
3738 	uint32_t chunk, piece;
3739 
3740 	chunk = bit >> 5;
3741 	piece = bit % (sizeof(uint32_t) * 8);
3742 
3743 	if ((mask[chunk] & (1 << piece)) == 0)
3744 		return (0);
3745 	else
3746 		return (1);
3747 }
3748 
3749 static uint64_t
3750 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3751 {
3752 	uint64_t *t;
3753 
3754 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3755 	if (t == NULL)
3756 		return (0);
3757 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3758 }
3759 
3760 static void
3761 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3762 {
3763 	uint64_t *t;
3764 
3765 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3766 	if (t == NULL)
3767 		return;
3768 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3769 }
3770 
3771 static void
3772 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3773 {
3774 	uint64_t *p;
3775 	u_int i;
3776 
3777 	i = residx/CTL_MAX_INIT_PER_PORT;
3778 	if (lun->pr_keys[i] != NULL)
3779 		return;
3780 	mtx_unlock(&lun->lun_lock);
3781 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3782 	    M_WAITOK | M_ZERO);
3783 	mtx_lock(&lun->lun_lock);
3784 	if (lun->pr_keys[i] == NULL)
3785 		lun->pr_keys[i] = p;
3786 	else
3787 		free(p, M_CTL);
3788 }
3789 
3790 static void
3791 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3792 {
3793 	uint64_t *t;
3794 
3795 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3796 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3797 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3798 }
3799 
3800 /*
3801  * ctl_softc, pool_name, total_ctl_io are passed in.
3802  * npool is passed out.
3803  */
3804 int
3805 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3806 		uint32_t total_ctl_io, void **npool)
3807 {
3808 	struct ctl_io_pool *pool;
3809 
3810 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3811 					    M_NOWAIT | M_ZERO);
3812 	if (pool == NULL)
3813 		return (ENOMEM);
3814 
3815 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3816 	pool->ctl_softc = ctl_softc;
3817 #ifdef IO_POOLS
3818 	pool->zone = uma_zsecond_create(pool->name, NULL,
3819 	    NULL, NULL, NULL, ctl_softc->io_zone);
3820 	/* uma_prealloc(pool->zone, total_ctl_io); */
3821 #else
3822 	pool->zone = ctl_softc->io_zone;
3823 #endif
3824 
3825 	*npool = pool;
3826 	return (0);
3827 }
3828 
3829 void
3830 ctl_pool_free(struct ctl_io_pool *pool)
3831 {
3832 
3833 	if (pool == NULL)
3834 		return;
3835 
3836 #ifdef IO_POOLS
3837 	uma_zdestroy(pool->zone);
3838 #endif
3839 	free(pool, M_CTL);
3840 }
3841 
3842 union ctl_io *
3843 ctl_alloc_io(void *pool_ref)
3844 {
3845 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3846 	union ctl_io *io;
3847 
3848 	io = uma_zalloc(pool->zone, M_WAITOK);
3849 	if (io != NULL) {
3850 		io->io_hdr.pool = pool_ref;
3851 		CTL_SOFTC(io) = pool->ctl_softc;
3852 	}
3853 	return (io);
3854 }
3855 
3856 union ctl_io *
3857 ctl_alloc_io_nowait(void *pool_ref)
3858 {
3859 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3860 	union ctl_io *io;
3861 
3862 	io = uma_zalloc(pool->zone, M_NOWAIT);
3863 	if (io != NULL) {
3864 		io->io_hdr.pool = pool_ref;
3865 		CTL_SOFTC(io) = pool->ctl_softc;
3866 	}
3867 	return (io);
3868 }
3869 
3870 void
3871 ctl_free_io(union ctl_io *io)
3872 {
3873 	struct ctl_io_pool *pool;
3874 
3875 	if (io == NULL)
3876 		return;
3877 
3878 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3879 	uma_zfree(pool->zone, io);
3880 }
3881 
3882 void
3883 ctl_zero_io(union ctl_io *io)
3884 {
3885 	struct ctl_io_pool *pool;
3886 
3887 	if (io == NULL)
3888 		return;
3889 
3890 	/*
3891 	 * May need to preserve linked list pointers at some point too.
3892 	 */
3893 	pool = io->io_hdr.pool;
3894 	memset(io, 0, sizeof(*io));
3895 	io->io_hdr.pool = pool;
3896 	CTL_SOFTC(io) = pool->ctl_softc;
3897 }
3898 
3899 int
3900 ctl_expand_number(const char *buf, uint64_t *num)
3901 {
3902 	char *endptr;
3903 	uint64_t number;
3904 	unsigned shift;
3905 
3906 	number = strtoq(buf, &endptr, 0);
3907 
3908 	switch (tolower((unsigned char)*endptr)) {
3909 	case 'e':
3910 		shift = 60;
3911 		break;
3912 	case 'p':
3913 		shift = 50;
3914 		break;
3915 	case 't':
3916 		shift = 40;
3917 		break;
3918 	case 'g':
3919 		shift = 30;
3920 		break;
3921 	case 'm':
3922 		shift = 20;
3923 		break;
3924 	case 'k':
3925 		shift = 10;
3926 		break;
3927 	case 'b':
3928 	case '\0': /* No unit. */
3929 		*num = number;
3930 		return (0);
3931 	default:
3932 		/* Unrecognized unit. */
3933 		return (-1);
3934 	}
3935 
3936 	if ((number << shift) >> shift != number) {
3937 		/* Overflow */
3938 		return (-1);
3939 	}
3940 	*num = number << shift;
3941 	return (0);
3942 }
3943 
3944 
3945 /*
3946  * This routine could be used in the future to load default and/or saved
3947  * mode page parameters for a particuar lun.
3948  */
3949 static int
3950 ctl_init_page_index(struct ctl_lun *lun)
3951 {
3952 	int i, page_code;
3953 	struct ctl_page_index *page_index;
3954 	const char *value;
3955 	uint64_t ival;
3956 
3957 	memcpy(&lun->mode_pages.index, page_index_template,
3958 	       sizeof(page_index_template));
3959 
3960 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3961 
3962 		page_index = &lun->mode_pages.index[i];
3963 		if (lun->be_lun->lun_type == T_DIRECT &&
3964 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3965 			continue;
3966 		if (lun->be_lun->lun_type == T_PROCESSOR &&
3967 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3968 			continue;
3969 		if (lun->be_lun->lun_type == T_CDROM &&
3970 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3971 			continue;
3972 
3973 		page_code = page_index->page_code & SMPH_PC_MASK;
3974 		switch (page_code) {
3975 		case SMS_RW_ERROR_RECOVERY_PAGE: {
3976 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3977 			    ("subpage %#x for page %#x is incorrect!",
3978 			    page_index->subpage, page_code));
3979 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3980 			       &rw_er_page_default,
3981 			       sizeof(rw_er_page_default));
3982 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3983 			       &rw_er_page_changeable,
3984 			       sizeof(rw_er_page_changeable));
3985 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3986 			       &rw_er_page_default,
3987 			       sizeof(rw_er_page_default));
3988 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3989 			       &rw_er_page_default,
3990 			       sizeof(rw_er_page_default));
3991 			page_index->page_data =
3992 				(uint8_t *)lun->mode_pages.rw_er_page;
3993 			break;
3994 		}
3995 		case SMS_FORMAT_DEVICE_PAGE: {
3996 			struct scsi_format_page *format_page;
3997 
3998 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3999 			    ("subpage %#x for page %#x is incorrect!",
4000 			    page_index->subpage, page_code));
4001 
4002 			/*
4003 			 * Sectors per track are set above.  Bytes per
4004 			 * sector need to be set here on a per-LUN basis.
4005 			 */
4006 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4007 			       &format_page_default,
4008 			       sizeof(format_page_default));
4009 			memcpy(&lun->mode_pages.format_page[
4010 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4011 			       sizeof(format_page_changeable));
4012 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4013 			       &format_page_default,
4014 			       sizeof(format_page_default));
4015 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4016 			       &format_page_default,
4017 			       sizeof(format_page_default));
4018 
4019 			format_page = &lun->mode_pages.format_page[
4020 				CTL_PAGE_CURRENT];
4021 			scsi_ulto2b(lun->be_lun->blocksize,
4022 				    format_page->bytes_per_sector);
4023 
4024 			format_page = &lun->mode_pages.format_page[
4025 				CTL_PAGE_DEFAULT];
4026 			scsi_ulto2b(lun->be_lun->blocksize,
4027 				    format_page->bytes_per_sector);
4028 
4029 			format_page = &lun->mode_pages.format_page[
4030 				CTL_PAGE_SAVED];
4031 			scsi_ulto2b(lun->be_lun->blocksize,
4032 				    format_page->bytes_per_sector);
4033 
4034 			page_index->page_data =
4035 				(uint8_t *)lun->mode_pages.format_page;
4036 			break;
4037 		}
4038 		case SMS_RIGID_DISK_PAGE: {
4039 			struct scsi_rigid_disk_page *rigid_disk_page;
4040 			uint32_t sectors_per_cylinder;
4041 			uint64_t cylinders;
4042 #ifndef	__XSCALE__
4043 			int shift;
4044 #endif /* !__XSCALE__ */
4045 
4046 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4047 			    ("subpage %#x for page %#x is incorrect!",
4048 			    page_index->subpage, page_code));
4049 
4050 			/*
4051 			 * Rotation rate and sectors per track are set
4052 			 * above.  We calculate the cylinders here based on
4053 			 * capacity.  Due to the number of heads and
4054 			 * sectors per track we're using, smaller arrays
4055 			 * may turn out to have 0 cylinders.  Linux and
4056 			 * FreeBSD don't pay attention to these mode pages
4057 			 * to figure out capacity, but Solaris does.  It
4058 			 * seems to deal with 0 cylinders just fine, and
4059 			 * works out a fake geometry based on the capacity.
4060 			 */
4061 			memcpy(&lun->mode_pages.rigid_disk_page[
4062 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4063 			       sizeof(rigid_disk_page_default));
4064 			memcpy(&lun->mode_pages.rigid_disk_page[
4065 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4066 			       sizeof(rigid_disk_page_changeable));
4067 
4068 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4069 				CTL_DEFAULT_HEADS;
4070 
4071 			/*
4072 			 * The divide method here will be more accurate,
4073 			 * probably, but results in floating point being
4074 			 * used in the kernel on i386 (__udivdi3()).  On the
4075 			 * XScale, though, __udivdi3() is implemented in
4076 			 * software.
4077 			 *
4078 			 * The shift method for cylinder calculation is
4079 			 * accurate if sectors_per_cylinder is a power of
4080 			 * 2.  Otherwise it might be slightly off -- you
4081 			 * might have a bit of a truncation problem.
4082 			 */
4083 #ifdef	__XSCALE__
4084 			cylinders = (lun->be_lun->maxlba + 1) /
4085 				sectors_per_cylinder;
4086 #else
4087 			for (shift = 31; shift > 0; shift--) {
4088 				if (sectors_per_cylinder & (1 << shift))
4089 					break;
4090 			}
4091 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4092 #endif
4093 
4094 			/*
4095 			 * We've basically got 3 bytes, or 24 bits for the
4096 			 * cylinder size in the mode page.  If we're over,
4097 			 * just round down to 2^24.
4098 			 */
4099 			if (cylinders > 0xffffff)
4100 				cylinders = 0xffffff;
4101 
4102 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4103 				CTL_PAGE_DEFAULT];
4104 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4105 
4106 			if ((value = ctl_get_opt(&lun->be_lun->options,
4107 			    "rpm")) != NULL) {
4108 				scsi_ulto2b(strtol(value, NULL, 0),
4109 				     rigid_disk_page->rotation_rate);
4110 			}
4111 
4112 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4113 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4114 			       sizeof(rigid_disk_page_default));
4115 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4116 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4117 			       sizeof(rigid_disk_page_default));
4118 
4119 			page_index->page_data =
4120 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4121 			break;
4122 		}
4123 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4124 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4125 			    ("subpage %#x for page %#x is incorrect!",
4126 			    page_index->subpage, page_code));
4127 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4128 			       &verify_er_page_default,
4129 			       sizeof(verify_er_page_default));
4130 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4131 			       &verify_er_page_changeable,
4132 			       sizeof(verify_er_page_changeable));
4133 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4134 			       &verify_er_page_default,
4135 			       sizeof(verify_er_page_default));
4136 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4137 			       &verify_er_page_default,
4138 			       sizeof(verify_er_page_default));
4139 			page_index->page_data =
4140 				(uint8_t *)lun->mode_pages.verify_er_page;
4141 			break;
4142 		}
4143 		case SMS_CACHING_PAGE: {
4144 			struct scsi_caching_page *caching_page;
4145 
4146 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4147 			    ("subpage %#x for page %#x is incorrect!",
4148 			    page_index->subpage, page_code));
4149 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4150 			       &caching_page_default,
4151 			       sizeof(caching_page_default));
4152 			memcpy(&lun->mode_pages.caching_page[
4153 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4154 			       sizeof(caching_page_changeable));
4155 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4156 			       &caching_page_default,
4157 			       sizeof(caching_page_default));
4158 			caching_page = &lun->mode_pages.caching_page[
4159 			    CTL_PAGE_SAVED];
4160 			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4161 			if (value != NULL && strcmp(value, "off") == 0)
4162 				caching_page->flags1 &= ~SCP_WCE;
4163 			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4164 			if (value != NULL && strcmp(value, "off") == 0)
4165 				caching_page->flags1 |= SCP_RCD;
4166 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4167 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4168 			       sizeof(caching_page_default));
4169 			page_index->page_data =
4170 				(uint8_t *)lun->mode_pages.caching_page;
4171 			break;
4172 		}
4173 		case SMS_CONTROL_MODE_PAGE: {
4174 			switch (page_index->subpage) {
4175 			case SMS_SUBPAGE_PAGE_0: {
4176 				struct scsi_control_page *control_page;
4177 
4178 				memcpy(&lun->mode_pages.control_page[
4179 				    CTL_PAGE_DEFAULT],
4180 				       &control_page_default,
4181 				       sizeof(control_page_default));
4182 				memcpy(&lun->mode_pages.control_page[
4183 				    CTL_PAGE_CHANGEABLE],
4184 				       &control_page_changeable,
4185 				       sizeof(control_page_changeable));
4186 				memcpy(&lun->mode_pages.control_page[
4187 				    CTL_PAGE_SAVED],
4188 				       &control_page_default,
4189 				       sizeof(control_page_default));
4190 				control_page = &lun->mode_pages.control_page[
4191 				    CTL_PAGE_SAVED];
4192 				value = ctl_get_opt(&lun->be_lun->options,
4193 				    "reordering");
4194 				if (value != NULL &&
4195 				    strcmp(value, "unrestricted") == 0) {
4196 					control_page->queue_flags &=
4197 					    ~SCP_QUEUE_ALG_MASK;
4198 					control_page->queue_flags |=
4199 					    SCP_QUEUE_ALG_UNRESTRICTED;
4200 				}
4201 				memcpy(&lun->mode_pages.control_page[
4202 				    CTL_PAGE_CURRENT],
4203 				       &lun->mode_pages.control_page[
4204 				    CTL_PAGE_SAVED],
4205 				       sizeof(control_page_default));
4206 				page_index->page_data =
4207 				    (uint8_t *)lun->mode_pages.control_page;
4208 				break;
4209 			}
4210 			case 0x01:
4211 				memcpy(&lun->mode_pages.control_ext_page[
4212 				    CTL_PAGE_DEFAULT],
4213 				       &control_ext_page_default,
4214 				       sizeof(control_ext_page_default));
4215 				memcpy(&lun->mode_pages.control_ext_page[
4216 				    CTL_PAGE_CHANGEABLE],
4217 				       &control_ext_page_changeable,
4218 				       sizeof(control_ext_page_changeable));
4219 				memcpy(&lun->mode_pages.control_ext_page[
4220 				    CTL_PAGE_SAVED],
4221 				       &control_ext_page_default,
4222 				       sizeof(control_ext_page_default));
4223 				memcpy(&lun->mode_pages.control_ext_page[
4224 				    CTL_PAGE_CURRENT],
4225 				       &lun->mode_pages.control_ext_page[
4226 				    CTL_PAGE_SAVED],
4227 				       sizeof(control_ext_page_default));
4228 				page_index->page_data =
4229 				    (uint8_t *)lun->mode_pages.control_ext_page;
4230 				break;
4231 			default:
4232 				panic("subpage %#x for page %#x is incorrect!",
4233 				      page_index->subpage, page_code);
4234 			}
4235 			break;
4236 		}
4237 		case SMS_INFO_EXCEPTIONS_PAGE: {
4238 			switch (page_index->subpage) {
4239 			case SMS_SUBPAGE_PAGE_0:
4240 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4241 				       &ie_page_default,
4242 				       sizeof(ie_page_default));
4243 				memcpy(&lun->mode_pages.ie_page[
4244 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4245 				       sizeof(ie_page_changeable));
4246 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4247 				       &ie_page_default,
4248 				       sizeof(ie_page_default));
4249 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4250 				       &ie_page_default,
4251 				       sizeof(ie_page_default));
4252 				page_index->page_data =
4253 					(uint8_t *)lun->mode_pages.ie_page;
4254 				break;
4255 			case 0x02: {
4256 				struct ctl_logical_block_provisioning_page *page;
4257 
4258 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4259 				       &lbp_page_default,
4260 				       sizeof(lbp_page_default));
4261 				memcpy(&lun->mode_pages.lbp_page[
4262 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4263 				       sizeof(lbp_page_changeable));
4264 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4265 				       &lbp_page_default,
4266 				       sizeof(lbp_page_default));
4267 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4268 				value = ctl_get_opt(&lun->be_lun->options,
4269 				    "avail-threshold");
4270 				if (value != NULL &&
4271 				    ctl_expand_number(value, &ival) == 0) {
4272 					page->descr[0].flags |= SLBPPD_ENABLED |
4273 					    SLBPPD_ARMING_DEC;
4274 					if (lun->be_lun->blocksize)
4275 						ival /= lun->be_lun->blocksize;
4276 					else
4277 						ival /= 512;
4278 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4279 					    page->descr[0].count);
4280 				}
4281 				value = ctl_get_opt(&lun->be_lun->options,
4282 				    "used-threshold");
4283 				if (value != NULL &&
4284 				    ctl_expand_number(value, &ival) == 0) {
4285 					page->descr[1].flags |= SLBPPD_ENABLED |
4286 					    SLBPPD_ARMING_INC;
4287 					if (lun->be_lun->blocksize)
4288 						ival /= lun->be_lun->blocksize;
4289 					else
4290 						ival /= 512;
4291 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4292 					    page->descr[1].count);
4293 				}
4294 				value = ctl_get_opt(&lun->be_lun->options,
4295 				    "pool-avail-threshold");
4296 				if (value != NULL &&
4297 				    ctl_expand_number(value, &ival) == 0) {
4298 					page->descr[2].flags |= SLBPPD_ENABLED |
4299 					    SLBPPD_ARMING_DEC;
4300 					if (lun->be_lun->blocksize)
4301 						ival /= lun->be_lun->blocksize;
4302 					else
4303 						ival /= 512;
4304 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4305 					    page->descr[2].count);
4306 				}
4307 				value = ctl_get_opt(&lun->be_lun->options,
4308 				    "pool-used-threshold");
4309 				if (value != NULL &&
4310 				    ctl_expand_number(value, &ival) == 0) {
4311 					page->descr[3].flags |= SLBPPD_ENABLED |
4312 					    SLBPPD_ARMING_INC;
4313 					if (lun->be_lun->blocksize)
4314 						ival /= lun->be_lun->blocksize;
4315 					else
4316 						ival /= 512;
4317 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4318 					    page->descr[3].count);
4319 				}
4320 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4321 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4322 				       sizeof(lbp_page_default));
4323 				page_index->page_data =
4324 					(uint8_t *)lun->mode_pages.lbp_page;
4325 				break;
4326 			}
4327 			default:
4328 				panic("subpage %#x for page %#x is incorrect!",
4329 				      page_index->subpage, page_code);
4330 			}
4331 			break;
4332 		}
4333 		case SMS_CDDVD_CAPS_PAGE:{
4334 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4335 			    ("subpage %#x for page %#x is incorrect!",
4336 			    page_index->subpage, page_code));
4337 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4338 			       &cddvd_page_default,
4339 			       sizeof(cddvd_page_default));
4340 			memcpy(&lun->mode_pages.cddvd_page[
4341 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4342 			       sizeof(cddvd_page_changeable));
4343 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4344 			       &cddvd_page_default,
4345 			       sizeof(cddvd_page_default));
4346 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4347 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4348 			       sizeof(cddvd_page_default));
4349 			page_index->page_data =
4350 				(uint8_t *)lun->mode_pages.cddvd_page;
4351 			break;
4352 		}
4353 		default:
4354 			panic("invalid page code value %#x", page_code);
4355 		}
4356 	}
4357 
4358 	return (CTL_RETVAL_COMPLETE);
4359 }
4360 
4361 static int
4362 ctl_init_log_page_index(struct ctl_lun *lun)
4363 {
4364 	struct ctl_page_index *page_index;
4365 	int i, j, k, prev;
4366 
4367 	memcpy(&lun->log_pages.index, log_page_index_template,
4368 	       sizeof(log_page_index_template));
4369 
4370 	prev = -1;
4371 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4372 
4373 		page_index = &lun->log_pages.index[i];
4374 		if (lun->be_lun->lun_type == T_DIRECT &&
4375 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4376 			continue;
4377 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4378 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4379 			continue;
4380 		if (lun->be_lun->lun_type == T_CDROM &&
4381 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4382 			continue;
4383 
4384 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4385 		    lun->backend->lun_attr == NULL)
4386 			continue;
4387 
4388 		if (page_index->page_code != prev) {
4389 			lun->log_pages.pages_page[j] = page_index->page_code;
4390 			prev = page_index->page_code;
4391 			j++;
4392 		}
4393 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4394 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4395 		k++;
4396 	}
4397 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4398 	lun->log_pages.index[0].page_len = j;
4399 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4400 	lun->log_pages.index[1].page_len = k * 2;
4401 	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4402 	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4403 	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4404 	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4405 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4406 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4407 
4408 	return (CTL_RETVAL_COMPLETE);
4409 }
4410 
4411 static int
4412 hex2bin(const char *str, uint8_t *buf, int buf_size)
4413 {
4414 	int i;
4415 	u_char c;
4416 
4417 	memset(buf, 0, buf_size);
4418 	while (isspace(str[0]))
4419 		str++;
4420 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4421 		str += 2;
4422 	buf_size *= 2;
4423 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4424 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4425 			str++;
4426 		c = str[i];
4427 		if (isdigit(c))
4428 			c -= '0';
4429 		else if (isalpha(c))
4430 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4431 		else
4432 			break;
4433 		if (c >= 16)
4434 			break;
4435 		if ((i & 1) == 0)
4436 			buf[i / 2] |= (c << 4);
4437 		else
4438 			buf[i / 2] |= c;
4439 	}
4440 	return ((i + 1) / 2);
4441 }
4442 
4443 /*
4444  * LUN allocation.
4445  *
4446  * Requirements:
4447  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4448  *   wants us to allocate the LUN and he can block.
4449  * - ctl_softc is always set
4450  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4451  *
4452  * Returns 0 for success, non-zero (errno) for failure.
4453  */
4454 static int
4455 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4456 	      struct ctl_be_lun *const be_lun)
4457 {
4458 	struct ctl_lun *nlun, *lun;
4459 	struct scsi_vpd_id_descriptor *desc;
4460 	struct scsi_vpd_id_t10 *t10id;
4461 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4462 	int lun_number, lun_malloced;
4463 	int devidlen, idlen1, idlen2 = 0, len;
4464 
4465 	if (be_lun == NULL)
4466 		return (EINVAL);
4467 
4468 	/*
4469 	 * We currently only support Direct Access or Processor LUN types.
4470 	 */
4471 	switch (be_lun->lun_type) {
4472 	case T_DIRECT:
4473 	case T_PROCESSOR:
4474 	case T_CDROM:
4475 		break;
4476 	case T_SEQUENTIAL:
4477 	case T_CHANGER:
4478 	default:
4479 		be_lun->lun_config_status(be_lun->be_lun,
4480 					  CTL_LUN_CONFIG_FAILURE);
4481 		break;
4482 	}
4483 	if (ctl_lun == NULL) {
4484 		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4485 		lun_malloced = 1;
4486 	} else {
4487 		lun_malloced = 0;
4488 		lun = ctl_lun;
4489 	}
4490 
4491 	memset(lun, 0, sizeof(*lun));
4492 	if (lun_malloced)
4493 		lun->flags = CTL_LUN_MALLOCED;
4494 
4495 	/* Generate LUN ID. */
4496 	devidlen = max(CTL_DEVID_MIN_LEN,
4497 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4498 	idlen1 = sizeof(*t10id) + devidlen;
4499 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4500 	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4501 	if (scsiname != NULL) {
4502 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4503 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4504 	}
4505 	eui = ctl_get_opt(&be_lun->options, "eui");
4506 	if (eui != NULL) {
4507 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4508 	}
4509 	naa = ctl_get_opt(&be_lun->options, "naa");
4510 	if (naa != NULL) {
4511 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4512 	}
4513 	uuid = ctl_get_opt(&be_lun->options, "uuid");
4514 	if (uuid != NULL) {
4515 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4516 	}
4517 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4518 	    M_CTL, M_WAITOK | M_ZERO);
4519 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4520 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4521 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4522 	desc->length = idlen1;
4523 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4524 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4525 	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4526 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4527 	} else {
4528 		strncpy(t10id->vendor, vendor,
4529 		    min(sizeof(t10id->vendor), strlen(vendor)));
4530 	}
4531 	strncpy((char *)t10id->vendor_spec_id,
4532 	    (char *)be_lun->device_id, devidlen);
4533 	if (scsiname != NULL) {
4534 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4535 		    desc->length);
4536 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4537 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4538 		    SVPD_ID_TYPE_SCSI_NAME;
4539 		desc->length = idlen2;
4540 		strlcpy(desc->identifier, scsiname, idlen2);
4541 	}
4542 	if (eui != NULL) {
4543 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4544 		    desc->length);
4545 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4546 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4547 		    SVPD_ID_TYPE_EUI64;
4548 		desc->length = hex2bin(eui, desc->identifier, 16);
4549 		desc->length = desc->length > 12 ? 16 :
4550 		    (desc->length > 8 ? 12 : 8);
4551 		len -= 16 - desc->length;
4552 	}
4553 	if (naa != NULL) {
4554 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4555 		    desc->length);
4556 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4557 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4558 		    SVPD_ID_TYPE_NAA;
4559 		desc->length = hex2bin(naa, desc->identifier, 16);
4560 		desc->length = desc->length > 8 ? 16 : 8;
4561 		len -= 16 - desc->length;
4562 	}
4563 	if (uuid != NULL) {
4564 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4565 		    desc->length);
4566 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4567 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4568 		    SVPD_ID_TYPE_UUID;
4569 		desc->identifier[0] = 0x10;
4570 		hex2bin(uuid, &desc->identifier[2], 16);
4571 		desc->length = 18;
4572 	}
4573 	lun->lun_devid->len = len;
4574 
4575 	mtx_lock(&ctl_softc->ctl_lock);
4576 	/*
4577 	 * See if the caller requested a particular LUN number.  If so, see
4578 	 * if it is available.  Otherwise, allocate the first available LUN.
4579 	 */
4580 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4581 		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4582 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4583 			mtx_unlock(&ctl_softc->ctl_lock);
4584 			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4585 				printf("ctl: requested LUN ID %d is higher "
4586 				       "than CTL_MAX_LUNS - 1 (%d)\n",
4587 				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4588 			} else {
4589 				/*
4590 				 * XXX KDM return an error, or just assign
4591 				 * another LUN ID in this case??
4592 				 */
4593 				printf("ctl: requested LUN ID %d is already "
4594 				       "in use\n", be_lun->req_lun_id);
4595 			}
4596 fail:
4597 			free(lun->lun_devid, M_CTL);
4598 			if (lun->flags & CTL_LUN_MALLOCED)
4599 				free(lun, M_CTL);
4600 			be_lun->lun_config_status(be_lun->be_lun,
4601 						  CTL_LUN_CONFIG_FAILURE);
4602 			return (ENOSPC);
4603 		}
4604 		lun_number = be_lun->req_lun_id;
4605 	} else {
4606 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4607 		if (lun_number == -1) {
4608 			mtx_unlock(&ctl_softc->ctl_lock);
4609 			printf("ctl: can't allocate LUN, out of LUNs\n");
4610 			goto fail;
4611 		}
4612 	}
4613 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4614 	mtx_unlock(&ctl_softc->ctl_lock);
4615 
4616 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4617 	lun->lun = lun_number;
4618 	lun->be_lun = be_lun;
4619 	/*
4620 	 * The processor LUN is always enabled.  Disk LUNs come on line
4621 	 * disabled, and must be enabled by the backend.
4622 	 */
4623 	lun->flags |= CTL_LUN_DISABLED;
4624 	lun->backend = be_lun->be;
4625 	be_lun->ctl_lun = lun;
4626 	be_lun->lun_id = lun_number;
4627 	atomic_add_int(&be_lun->be->num_luns, 1);
4628 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4629 		lun->flags |= CTL_LUN_EJECTED;
4630 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4631 		lun->flags |= CTL_LUN_NO_MEDIA;
4632 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4633 		lun->flags |= CTL_LUN_STOPPED;
4634 
4635 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4636 		lun->flags |= CTL_LUN_PRIMARY_SC;
4637 
4638 	value = ctl_get_opt(&be_lun->options, "removable");
4639 	if (value != NULL) {
4640 		if (strcmp(value, "on") == 0)
4641 			lun->flags |= CTL_LUN_REMOVABLE;
4642 	} else if (be_lun->lun_type == T_CDROM)
4643 		lun->flags |= CTL_LUN_REMOVABLE;
4644 
4645 	lun->ctl_softc = ctl_softc;
4646 #ifdef CTL_TIME_IO
4647 	lun->last_busy = getsbinuptime();
4648 #endif
4649 	TAILQ_INIT(&lun->ooa_queue);
4650 	TAILQ_INIT(&lun->blocked_queue);
4651 	STAILQ_INIT(&lun->error_list);
4652 	lun->ie_reported = 1;
4653 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4654 	ctl_tpc_lun_init(lun);
4655 	if (lun->flags & CTL_LUN_REMOVABLE) {
4656 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4657 		    M_CTL, M_WAITOK);
4658 	}
4659 
4660 	/*
4661 	 * Initialize the mode and log page index.
4662 	 */
4663 	ctl_init_page_index(lun);
4664 	ctl_init_log_page_index(lun);
4665 
4666 	/* Setup statistics gathering */
4667 #ifdef CTL_LEGACY_STATS
4668 	lun->legacy_stats.device_type = be_lun->lun_type;
4669 	lun->legacy_stats.lun_number = lun_number;
4670 	lun->legacy_stats.blocksize = be_lun->blocksize;
4671 	if (be_lun->blocksize == 0)
4672 		lun->legacy_stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4673 	for (len = 0; len < CTL_MAX_PORTS; len++)
4674 		lun->legacy_stats.ports[len].targ_port = len;
4675 #endif /* CTL_LEGACY_STATS */
4676 	lun->stats.item = lun_number;
4677 
4678 	/*
4679 	 * Now, before we insert this lun on the lun list, set the lun
4680 	 * inventory changed UA for all other luns.
4681 	 */
4682 	mtx_lock(&ctl_softc->ctl_lock);
4683 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4684 		mtx_lock(&nlun->lun_lock);
4685 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4686 		mtx_unlock(&nlun->lun_lock);
4687 	}
4688 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4689 	ctl_softc->ctl_luns[lun_number] = lun;
4690 	ctl_softc->num_luns++;
4691 	mtx_unlock(&ctl_softc->ctl_lock);
4692 
4693 	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4694 	return (0);
4695 }
4696 
4697 /*
4698  * Delete a LUN.
4699  * Assumptions:
4700  * - LUN has already been marked invalid and any pending I/O has been taken
4701  *   care of.
4702  */
4703 static int
4704 ctl_free_lun(struct ctl_lun *lun)
4705 {
4706 	struct ctl_softc *softc = lun->ctl_softc;
4707 	struct ctl_lun *nlun;
4708 	int i;
4709 
4710 	mtx_assert(&softc->ctl_lock, MA_OWNED);
4711 
4712 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4713 
4714 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4715 
4716 	softc->ctl_luns[lun->lun] = NULL;
4717 
4718 	if (!TAILQ_EMPTY(&lun->ooa_queue))
4719 		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4720 
4721 	softc->num_luns--;
4722 
4723 	/*
4724 	 * Tell the backend to free resources, if this LUN has a backend.
4725 	 */
4726 	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4727 	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4728 
4729 	lun->ie_reportcnt = UINT32_MAX;
4730 	callout_drain(&lun->ie_callout);
4731 
4732 	ctl_tpc_lun_shutdown(lun);
4733 	mtx_destroy(&lun->lun_lock);
4734 	free(lun->lun_devid, M_CTL);
4735 	for (i = 0; i < CTL_MAX_PORTS; i++)
4736 		free(lun->pending_ua[i], M_CTL);
4737 	for (i = 0; i < CTL_MAX_PORTS; i++)
4738 		free(lun->pr_keys[i], M_CTL);
4739 	free(lun->write_buffer, M_CTL);
4740 	free(lun->prevent, M_CTL);
4741 	if (lun->flags & CTL_LUN_MALLOCED)
4742 		free(lun, M_CTL);
4743 
4744 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4745 		mtx_lock(&nlun->lun_lock);
4746 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4747 		mtx_unlock(&nlun->lun_lock);
4748 	}
4749 
4750 	return (0);
4751 }
4752 
4753 static void
4754 ctl_create_lun(struct ctl_be_lun *be_lun)
4755 {
4756 
4757 	/*
4758 	 * ctl_alloc_lun() should handle all potential failure cases.
4759 	 */
4760 	ctl_alloc_lun(control_softc, NULL, be_lun);
4761 }
4762 
4763 int
4764 ctl_add_lun(struct ctl_be_lun *be_lun)
4765 {
4766 	struct ctl_softc *softc = control_softc;
4767 
4768 	mtx_lock(&softc->ctl_lock);
4769 	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4770 	mtx_unlock(&softc->ctl_lock);
4771 	wakeup(&softc->pending_lun_queue);
4772 
4773 	return (0);
4774 }
4775 
4776 int
4777 ctl_enable_lun(struct ctl_be_lun *be_lun)
4778 {
4779 	struct ctl_softc *softc;
4780 	struct ctl_port *port, *nport;
4781 	struct ctl_lun *lun;
4782 	int retval;
4783 
4784 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4785 	softc = lun->ctl_softc;
4786 
4787 	mtx_lock(&softc->ctl_lock);
4788 	mtx_lock(&lun->lun_lock);
4789 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4790 		/*
4791 		 * eh?  Why did we get called if the LUN is already
4792 		 * enabled?
4793 		 */
4794 		mtx_unlock(&lun->lun_lock);
4795 		mtx_unlock(&softc->ctl_lock);
4796 		return (0);
4797 	}
4798 	lun->flags &= ~CTL_LUN_DISABLED;
4799 	mtx_unlock(&lun->lun_lock);
4800 
4801 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4802 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4803 		    port->lun_map != NULL || port->lun_enable == NULL)
4804 			continue;
4805 
4806 		/*
4807 		 * Drop the lock while we call the FETD's enable routine.
4808 		 * This can lead to a callback into CTL (at least in the
4809 		 * case of the internal initiator frontend.
4810 		 */
4811 		mtx_unlock(&softc->ctl_lock);
4812 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4813 		mtx_lock(&softc->ctl_lock);
4814 		if (retval != 0) {
4815 			printf("%s: FETD %s port %d returned error "
4816 			       "%d for lun_enable on lun %jd\n",
4817 			       __func__, port->port_name, port->targ_port,
4818 			       retval, (intmax_t)lun->lun);
4819 		}
4820 	}
4821 
4822 	mtx_unlock(&softc->ctl_lock);
4823 	ctl_isc_announce_lun(lun);
4824 
4825 	return (0);
4826 }
4827 
4828 int
4829 ctl_disable_lun(struct ctl_be_lun *be_lun)
4830 {
4831 	struct ctl_softc *softc;
4832 	struct ctl_port *port;
4833 	struct ctl_lun *lun;
4834 	int retval;
4835 
4836 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4837 	softc = lun->ctl_softc;
4838 
4839 	mtx_lock(&softc->ctl_lock);
4840 	mtx_lock(&lun->lun_lock);
4841 	if (lun->flags & CTL_LUN_DISABLED) {
4842 		mtx_unlock(&lun->lun_lock);
4843 		mtx_unlock(&softc->ctl_lock);
4844 		return (0);
4845 	}
4846 	lun->flags |= CTL_LUN_DISABLED;
4847 	mtx_unlock(&lun->lun_lock);
4848 
4849 	STAILQ_FOREACH(port, &softc->port_list, links) {
4850 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4851 		    port->lun_map != NULL || port->lun_disable == NULL)
4852 			continue;
4853 
4854 		/*
4855 		 * Drop the lock before we call the frontend's disable
4856 		 * routine, to avoid lock order reversals.
4857 		 *
4858 		 * XXX KDM what happens if the frontend list changes while
4859 		 * we're traversing it?  It's unlikely, but should be handled.
4860 		 */
4861 		mtx_unlock(&softc->ctl_lock);
4862 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4863 		mtx_lock(&softc->ctl_lock);
4864 		if (retval != 0) {
4865 			printf("%s: FETD %s port %d returned error "
4866 			       "%d for lun_disable on lun %jd\n",
4867 			       __func__, port->port_name, port->targ_port,
4868 			       retval, (intmax_t)lun->lun);
4869 		}
4870 	}
4871 
4872 	mtx_unlock(&softc->ctl_lock);
4873 	ctl_isc_announce_lun(lun);
4874 
4875 	return (0);
4876 }
4877 
4878 int
4879 ctl_start_lun(struct ctl_be_lun *be_lun)
4880 {
4881 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4882 
4883 	mtx_lock(&lun->lun_lock);
4884 	lun->flags &= ~CTL_LUN_STOPPED;
4885 	mtx_unlock(&lun->lun_lock);
4886 	return (0);
4887 }
4888 
4889 int
4890 ctl_stop_lun(struct ctl_be_lun *be_lun)
4891 {
4892 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4893 
4894 	mtx_lock(&lun->lun_lock);
4895 	lun->flags |= CTL_LUN_STOPPED;
4896 	mtx_unlock(&lun->lun_lock);
4897 	return (0);
4898 }
4899 
4900 int
4901 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4902 {
4903 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4904 
4905 	mtx_lock(&lun->lun_lock);
4906 	lun->flags |= CTL_LUN_NO_MEDIA;
4907 	mtx_unlock(&lun->lun_lock);
4908 	return (0);
4909 }
4910 
4911 int
4912 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4913 {
4914 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4915 	union ctl_ha_msg msg;
4916 
4917 	mtx_lock(&lun->lun_lock);
4918 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4919 	if (lun->flags & CTL_LUN_REMOVABLE)
4920 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4921 	mtx_unlock(&lun->lun_lock);
4922 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4923 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4924 		bzero(&msg.ua, sizeof(msg.ua));
4925 		msg.hdr.msg_type = CTL_MSG_UA;
4926 		msg.hdr.nexus.initid = -1;
4927 		msg.hdr.nexus.targ_port = -1;
4928 		msg.hdr.nexus.targ_lun = lun->lun;
4929 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4930 		msg.ua.ua_all = 1;
4931 		msg.ua.ua_set = 1;
4932 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4933 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4934 		    M_WAITOK);
4935 	}
4936 	return (0);
4937 }
4938 
4939 int
4940 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4941 {
4942 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4943 
4944 	mtx_lock(&lun->lun_lock);
4945 	lun->flags |= CTL_LUN_EJECTED;
4946 	mtx_unlock(&lun->lun_lock);
4947 	return (0);
4948 }
4949 
4950 int
4951 ctl_lun_primary(struct ctl_be_lun *be_lun)
4952 {
4953 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4954 
4955 	mtx_lock(&lun->lun_lock);
4956 	lun->flags |= CTL_LUN_PRIMARY_SC;
4957 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4958 	mtx_unlock(&lun->lun_lock);
4959 	ctl_isc_announce_lun(lun);
4960 	return (0);
4961 }
4962 
4963 int
4964 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4965 {
4966 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4967 
4968 	mtx_lock(&lun->lun_lock);
4969 	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4970 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4971 	mtx_unlock(&lun->lun_lock);
4972 	ctl_isc_announce_lun(lun);
4973 	return (0);
4974 }
4975 
4976 int
4977 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4978 {
4979 	struct ctl_softc *softc;
4980 	struct ctl_lun *lun;
4981 
4982 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4983 	softc = lun->ctl_softc;
4984 
4985 	mtx_lock(&lun->lun_lock);
4986 
4987 	/*
4988 	 * The LUN needs to be disabled before it can be marked invalid.
4989 	 */
4990 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4991 		mtx_unlock(&lun->lun_lock);
4992 		return (-1);
4993 	}
4994 	/*
4995 	 * Mark the LUN invalid.
4996 	 */
4997 	lun->flags |= CTL_LUN_INVALID;
4998 
4999 	/*
5000 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5001 	 * If we have something in the OOA queue, we'll free it when the
5002 	 * last I/O completes.
5003 	 */
5004 	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5005 		mtx_unlock(&lun->lun_lock);
5006 		mtx_lock(&softc->ctl_lock);
5007 		ctl_free_lun(lun);
5008 		mtx_unlock(&softc->ctl_lock);
5009 	} else
5010 		mtx_unlock(&lun->lun_lock);
5011 
5012 	return (0);
5013 }
5014 
5015 void
5016 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5017 {
5018 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5019 	union ctl_ha_msg msg;
5020 
5021 	mtx_lock(&lun->lun_lock);
5022 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5023 	mtx_unlock(&lun->lun_lock);
5024 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5025 		/* Send msg to other side. */
5026 		bzero(&msg.ua, sizeof(msg.ua));
5027 		msg.hdr.msg_type = CTL_MSG_UA;
5028 		msg.hdr.nexus.initid = -1;
5029 		msg.hdr.nexus.targ_port = -1;
5030 		msg.hdr.nexus.targ_lun = lun->lun;
5031 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5032 		msg.ua.ua_all = 1;
5033 		msg.ua.ua_set = 1;
5034 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5035 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5036 		    M_WAITOK);
5037 	}
5038 }
5039 
5040 /*
5041  * Backend "memory move is complete" callback for requests that never
5042  * make it down to say RAIDCore's configuration code.
5043  */
5044 int
5045 ctl_config_move_done(union ctl_io *io)
5046 {
5047 	int retval;
5048 
5049 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5050 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5051 	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5052 
5053 	if ((io->io_hdr.port_status != 0) &&
5054 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5055 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5056 		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
5057 		    /*retry_count*/ io->io_hdr.port_status);
5058 	} else if (io->scsiio.kern_data_resid != 0 &&
5059 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
5060 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5061 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5062 		ctl_set_invalid_field_ciu(&io->scsiio);
5063 	}
5064 
5065 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5066 		ctl_data_print(io);
5067 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5068 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5069 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5070 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5071 		/*
5072 		 * XXX KDM just assuming a single pointer here, and not a
5073 		 * S/G list.  If we start using S/G lists for config data,
5074 		 * we'll need to know how to clean them up here as well.
5075 		 */
5076 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5077 			free(io->scsiio.kern_data_ptr, M_CTL);
5078 		ctl_done(io);
5079 		retval = CTL_RETVAL_COMPLETE;
5080 	} else {
5081 		/*
5082 		 * XXX KDM now we need to continue data movement.  Some
5083 		 * options:
5084 		 * - call ctl_scsiio() again?  We don't do this for data
5085 		 *   writes, because for those at least we know ahead of
5086 		 *   time where the write will go and how long it is.  For
5087 		 *   config writes, though, that information is largely
5088 		 *   contained within the write itself, thus we need to
5089 		 *   parse out the data again.
5090 		 *
5091 		 * - Call some other function once the data is in?
5092 		 */
5093 
5094 		/*
5095 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5096 		 * bits to see whether we're allocated or not.
5097 		 */
5098 		retval = ctl_scsiio(&io->scsiio);
5099 	}
5100 	return (retval);
5101 }
5102 
5103 /*
5104  * This gets called by a backend driver when it is done with a
5105  * data_submit method.
5106  */
5107 void
5108 ctl_data_submit_done(union ctl_io *io)
5109 {
5110 	/*
5111 	 * If the IO_CONT flag is set, we need to call the supplied
5112 	 * function to continue processing the I/O, instead of completing
5113 	 * the I/O just yet.
5114 	 *
5115 	 * If there is an error, though, we don't want to keep processing.
5116 	 * Instead, just send status back to the initiator.
5117 	 */
5118 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5119 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5120 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5121 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5122 		io->scsiio.io_cont(io);
5123 		return;
5124 	}
5125 	ctl_done(io);
5126 }
5127 
5128 /*
5129  * This gets called by a backend driver when it is done with a
5130  * configuration write.
5131  */
5132 void
5133 ctl_config_write_done(union ctl_io *io)
5134 {
5135 	uint8_t *buf;
5136 
5137 	/*
5138 	 * If the IO_CONT flag is set, we need to call the supplied
5139 	 * function to continue processing the I/O, instead of completing
5140 	 * the I/O just yet.
5141 	 *
5142 	 * If there is an error, though, we don't want to keep processing.
5143 	 * Instead, just send status back to the initiator.
5144 	 */
5145 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5146 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5147 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5148 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5149 		io->scsiio.io_cont(io);
5150 		return;
5151 	}
5152 	/*
5153 	 * Since a configuration write can be done for commands that actually
5154 	 * have data allocated, like write buffer, and commands that have
5155 	 * no data, like start/stop unit, we need to check here.
5156 	 */
5157 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5158 		buf = io->scsiio.kern_data_ptr;
5159 	else
5160 		buf = NULL;
5161 	ctl_done(io);
5162 	if (buf)
5163 		free(buf, M_CTL);
5164 }
5165 
5166 void
5167 ctl_config_read_done(union ctl_io *io)
5168 {
5169 	uint8_t *buf;
5170 
5171 	/*
5172 	 * If there is some error -- we are done, skip data transfer.
5173 	 */
5174 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5175 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5176 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5177 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5178 			buf = io->scsiio.kern_data_ptr;
5179 		else
5180 			buf = NULL;
5181 		ctl_done(io);
5182 		if (buf)
5183 			free(buf, M_CTL);
5184 		return;
5185 	}
5186 
5187 	/*
5188 	 * If the IO_CONT flag is set, we need to call the supplied
5189 	 * function to continue processing the I/O, instead of completing
5190 	 * the I/O just yet.
5191 	 */
5192 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5193 		io->scsiio.io_cont(io);
5194 		return;
5195 	}
5196 
5197 	ctl_datamove(io);
5198 }
5199 
5200 /*
5201  * SCSI release command.
5202  */
5203 int
5204 ctl_scsi_release(struct ctl_scsiio *ctsio)
5205 {
5206 	struct ctl_lun *lun = CTL_LUN(ctsio);
5207 	uint32_t residx;
5208 
5209 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5210 
5211 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5212 
5213 	/*
5214 	 * XXX KDM right now, we only support LUN reservation.  We don't
5215 	 * support 3rd party reservations, or extent reservations, which
5216 	 * might actually need the parameter list.  If we've gotten this
5217 	 * far, we've got a LUN reservation.  Anything else got kicked out
5218 	 * above.  So, according to SPC, ignore the length.
5219 	 */
5220 
5221 	mtx_lock(&lun->lun_lock);
5222 
5223 	/*
5224 	 * According to SPC, it is not an error for an intiator to attempt
5225 	 * to release a reservation on a LUN that isn't reserved, or that
5226 	 * is reserved by another initiator.  The reservation can only be
5227 	 * released, though, by the initiator who made it or by one of
5228 	 * several reset type events.
5229 	 */
5230 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5231 			lun->flags &= ~CTL_LUN_RESERVED;
5232 
5233 	mtx_unlock(&lun->lun_lock);
5234 
5235 	ctl_set_success(ctsio);
5236 	ctl_done((union ctl_io *)ctsio);
5237 	return (CTL_RETVAL_COMPLETE);
5238 }
5239 
5240 int
5241 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5242 {
5243 	struct ctl_lun *lun = CTL_LUN(ctsio);
5244 	uint32_t residx;
5245 
5246 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5247 
5248 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5249 
5250 	/*
5251 	 * XXX KDM right now, we only support LUN reservation.  We don't
5252 	 * support 3rd party reservations, or extent reservations, which
5253 	 * might actually need the parameter list.  If we've gotten this
5254 	 * far, we've got a LUN reservation.  Anything else got kicked out
5255 	 * above.  So, according to SPC, ignore the length.
5256 	 */
5257 
5258 	mtx_lock(&lun->lun_lock);
5259 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5260 		ctl_set_reservation_conflict(ctsio);
5261 		goto bailout;
5262 	}
5263 
5264 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5265 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5266 		ctl_set_success(ctsio);
5267 		goto bailout;
5268 	}
5269 
5270 	lun->flags |= CTL_LUN_RESERVED;
5271 	lun->res_idx = residx;
5272 	ctl_set_success(ctsio);
5273 
5274 bailout:
5275 	mtx_unlock(&lun->lun_lock);
5276 	ctl_done((union ctl_io *)ctsio);
5277 	return (CTL_RETVAL_COMPLETE);
5278 }
5279 
5280 int
5281 ctl_start_stop(struct ctl_scsiio *ctsio)
5282 {
5283 	struct ctl_lun *lun = CTL_LUN(ctsio);
5284 	struct scsi_start_stop_unit *cdb;
5285 	int retval;
5286 
5287 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5288 
5289 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5290 
5291 	if ((cdb->how & SSS_PC_MASK) == 0) {
5292 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5293 		    (cdb->how & SSS_START) == 0) {
5294 			uint32_t residx;
5295 
5296 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5297 			if (ctl_get_prkey(lun, residx) == 0 ||
5298 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5299 
5300 				ctl_set_reservation_conflict(ctsio);
5301 				ctl_done((union ctl_io *)ctsio);
5302 				return (CTL_RETVAL_COMPLETE);
5303 			}
5304 		}
5305 
5306 		if ((cdb->how & SSS_LOEJ) &&
5307 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5308 			ctl_set_invalid_field(ctsio,
5309 					      /*sks_valid*/ 1,
5310 					      /*command*/ 1,
5311 					      /*field*/ 4,
5312 					      /*bit_valid*/ 1,
5313 					      /*bit*/ 1);
5314 			ctl_done((union ctl_io *)ctsio);
5315 			return (CTL_RETVAL_COMPLETE);
5316 		}
5317 
5318 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5319 		    lun->prevent_count > 0) {
5320 			/* "Medium removal prevented" */
5321 			ctl_set_sense(ctsio, /*current_error*/ 1,
5322 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5323 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5324 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5325 			ctl_done((union ctl_io *)ctsio);
5326 			return (CTL_RETVAL_COMPLETE);
5327 		}
5328 	}
5329 
5330 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5331 	return (retval);
5332 }
5333 
5334 int
5335 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5336 {
5337 	struct ctl_lun *lun = CTL_LUN(ctsio);
5338 	struct scsi_prevent *cdb;
5339 	int retval;
5340 	uint32_t initidx;
5341 
5342 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5343 
5344 	cdb = (struct scsi_prevent *)ctsio->cdb;
5345 
5346 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5347 		ctl_set_invalid_opcode(ctsio);
5348 		ctl_done((union ctl_io *)ctsio);
5349 		return (CTL_RETVAL_COMPLETE);
5350 	}
5351 
5352 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5353 	mtx_lock(&lun->lun_lock);
5354 	if ((cdb->how & PR_PREVENT) &&
5355 	    ctl_is_set(lun->prevent, initidx) == 0) {
5356 		ctl_set_mask(lun->prevent, initidx);
5357 		lun->prevent_count++;
5358 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5359 	    ctl_is_set(lun->prevent, initidx)) {
5360 		ctl_clear_mask(lun->prevent, initidx);
5361 		lun->prevent_count--;
5362 	}
5363 	mtx_unlock(&lun->lun_lock);
5364 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5365 	return (retval);
5366 }
5367 
5368 /*
5369  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5370  * we don't really do anything with the LBA and length fields if the user
5371  * passes them in.  Instead we'll just flush out the cache for the entire
5372  * LUN.
5373  */
5374 int
5375 ctl_sync_cache(struct ctl_scsiio *ctsio)
5376 {
5377 	struct ctl_lun *lun = CTL_LUN(ctsio);
5378 	struct ctl_lba_len_flags *lbalen;
5379 	uint64_t starting_lba;
5380 	uint32_t block_count;
5381 	int retval;
5382 	uint8_t byte2;
5383 
5384 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5385 
5386 	retval = 0;
5387 
5388 	switch (ctsio->cdb[0]) {
5389 	case SYNCHRONIZE_CACHE: {
5390 		struct scsi_sync_cache *cdb;
5391 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5392 
5393 		starting_lba = scsi_4btoul(cdb->begin_lba);
5394 		block_count = scsi_2btoul(cdb->lb_count);
5395 		byte2 = cdb->byte2;
5396 		break;
5397 	}
5398 	case SYNCHRONIZE_CACHE_16: {
5399 		struct scsi_sync_cache_16 *cdb;
5400 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5401 
5402 		starting_lba = scsi_8btou64(cdb->begin_lba);
5403 		block_count = scsi_4btoul(cdb->lb_count);
5404 		byte2 = cdb->byte2;
5405 		break;
5406 	}
5407 	default:
5408 		ctl_set_invalid_opcode(ctsio);
5409 		ctl_done((union ctl_io *)ctsio);
5410 		goto bailout;
5411 		break; /* NOTREACHED */
5412 	}
5413 
5414 	/*
5415 	 * We check the LBA and length, but don't do anything with them.
5416 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5417 	 * get flushed.  This check will just help satisfy anyone who wants
5418 	 * to see an error for an out of range LBA.
5419 	 */
5420 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5421 		ctl_set_lba_out_of_range(ctsio,
5422 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5423 		ctl_done((union ctl_io *)ctsio);
5424 		goto bailout;
5425 	}
5426 
5427 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5428 	lbalen->lba = starting_lba;
5429 	lbalen->len = block_count;
5430 	lbalen->flags = byte2;
5431 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5432 
5433 bailout:
5434 	return (retval);
5435 }
5436 
5437 int
5438 ctl_format(struct ctl_scsiio *ctsio)
5439 {
5440 	struct scsi_format *cdb;
5441 	int length, defect_list_len;
5442 
5443 	CTL_DEBUG_PRINT(("ctl_format\n"));
5444 
5445 	cdb = (struct scsi_format *)ctsio->cdb;
5446 
5447 	length = 0;
5448 	if (cdb->byte2 & SF_FMTDATA) {
5449 		if (cdb->byte2 & SF_LONGLIST)
5450 			length = sizeof(struct scsi_format_header_long);
5451 		else
5452 			length = sizeof(struct scsi_format_header_short);
5453 	}
5454 
5455 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5456 	 && (length > 0)) {
5457 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5458 		ctsio->kern_data_len = length;
5459 		ctsio->kern_total_len = length;
5460 		ctsio->kern_rel_offset = 0;
5461 		ctsio->kern_sg_entries = 0;
5462 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5463 		ctsio->be_move_done = ctl_config_move_done;
5464 		ctl_datamove((union ctl_io *)ctsio);
5465 
5466 		return (CTL_RETVAL_COMPLETE);
5467 	}
5468 
5469 	defect_list_len = 0;
5470 
5471 	if (cdb->byte2 & SF_FMTDATA) {
5472 		if (cdb->byte2 & SF_LONGLIST) {
5473 			struct scsi_format_header_long *header;
5474 
5475 			header = (struct scsi_format_header_long *)
5476 				ctsio->kern_data_ptr;
5477 
5478 			defect_list_len = scsi_4btoul(header->defect_list_len);
5479 			if (defect_list_len != 0) {
5480 				ctl_set_invalid_field(ctsio,
5481 						      /*sks_valid*/ 1,
5482 						      /*command*/ 0,
5483 						      /*field*/ 2,
5484 						      /*bit_valid*/ 0,
5485 						      /*bit*/ 0);
5486 				goto bailout;
5487 			}
5488 		} else {
5489 			struct scsi_format_header_short *header;
5490 
5491 			header = (struct scsi_format_header_short *)
5492 				ctsio->kern_data_ptr;
5493 
5494 			defect_list_len = scsi_2btoul(header->defect_list_len);
5495 			if (defect_list_len != 0) {
5496 				ctl_set_invalid_field(ctsio,
5497 						      /*sks_valid*/ 1,
5498 						      /*command*/ 0,
5499 						      /*field*/ 2,
5500 						      /*bit_valid*/ 0,
5501 						      /*bit*/ 0);
5502 				goto bailout;
5503 			}
5504 		}
5505 	}
5506 
5507 	ctl_set_success(ctsio);
5508 bailout:
5509 
5510 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5511 		free(ctsio->kern_data_ptr, M_CTL);
5512 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5513 	}
5514 
5515 	ctl_done((union ctl_io *)ctsio);
5516 	return (CTL_RETVAL_COMPLETE);
5517 }
5518 
5519 int
5520 ctl_read_buffer(struct ctl_scsiio *ctsio)
5521 {
5522 	struct ctl_lun *lun = CTL_LUN(ctsio);
5523 	uint64_t buffer_offset;
5524 	uint32_t len;
5525 	uint8_t byte2;
5526 	static uint8_t descr[4];
5527 	static uint8_t echo_descr[4] = { 0 };
5528 
5529 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5530 
5531 	switch (ctsio->cdb[0]) {
5532 	case READ_BUFFER: {
5533 		struct scsi_read_buffer *cdb;
5534 
5535 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5536 		buffer_offset = scsi_3btoul(cdb->offset);
5537 		len = scsi_3btoul(cdb->length);
5538 		byte2 = cdb->byte2;
5539 		break;
5540 	}
5541 	case READ_BUFFER_16: {
5542 		struct scsi_read_buffer_16 *cdb;
5543 
5544 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5545 		buffer_offset = scsi_8btou64(cdb->offset);
5546 		len = scsi_4btoul(cdb->length);
5547 		byte2 = cdb->byte2;
5548 		break;
5549 	}
5550 	default: /* This shouldn't happen. */
5551 		ctl_set_invalid_opcode(ctsio);
5552 		ctl_done((union ctl_io *)ctsio);
5553 		return (CTL_RETVAL_COMPLETE);
5554 	}
5555 
5556 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5557 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5558 		ctl_set_invalid_field(ctsio,
5559 				      /*sks_valid*/ 1,
5560 				      /*command*/ 1,
5561 				      /*field*/ 6,
5562 				      /*bit_valid*/ 0,
5563 				      /*bit*/ 0);
5564 		ctl_done((union ctl_io *)ctsio);
5565 		return (CTL_RETVAL_COMPLETE);
5566 	}
5567 
5568 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5569 		descr[0] = 0;
5570 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5571 		ctsio->kern_data_ptr = descr;
5572 		len = min(len, sizeof(descr));
5573 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5574 		ctsio->kern_data_ptr = echo_descr;
5575 		len = min(len, sizeof(echo_descr));
5576 	} else {
5577 		if (lun->write_buffer == NULL) {
5578 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5579 			    M_CTL, M_WAITOK);
5580 		}
5581 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5582 	}
5583 	ctsio->kern_data_len = len;
5584 	ctsio->kern_total_len = len;
5585 	ctsio->kern_rel_offset = 0;
5586 	ctsio->kern_sg_entries = 0;
5587 	ctl_set_success(ctsio);
5588 	ctsio->be_move_done = ctl_config_move_done;
5589 	ctl_datamove((union ctl_io *)ctsio);
5590 	return (CTL_RETVAL_COMPLETE);
5591 }
5592 
5593 int
5594 ctl_write_buffer(struct ctl_scsiio *ctsio)
5595 {
5596 	struct ctl_lun *lun = CTL_LUN(ctsio);
5597 	struct scsi_write_buffer *cdb;
5598 	int buffer_offset, len;
5599 
5600 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5601 
5602 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5603 
5604 	len = scsi_3btoul(cdb->length);
5605 	buffer_offset = scsi_3btoul(cdb->offset);
5606 
5607 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5608 		ctl_set_invalid_field(ctsio,
5609 				      /*sks_valid*/ 1,
5610 				      /*command*/ 1,
5611 				      /*field*/ 6,
5612 				      /*bit_valid*/ 0,
5613 				      /*bit*/ 0);
5614 		ctl_done((union ctl_io *)ctsio);
5615 		return (CTL_RETVAL_COMPLETE);
5616 	}
5617 
5618 	/*
5619 	 * If we've got a kernel request that hasn't been malloced yet,
5620 	 * malloc it and tell the caller the data buffer is here.
5621 	 */
5622 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5623 		if (lun->write_buffer == NULL) {
5624 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5625 			    M_CTL, M_WAITOK);
5626 		}
5627 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5628 		ctsio->kern_data_len = len;
5629 		ctsio->kern_total_len = len;
5630 		ctsio->kern_rel_offset = 0;
5631 		ctsio->kern_sg_entries = 0;
5632 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5633 		ctsio->be_move_done = ctl_config_move_done;
5634 		ctl_datamove((union ctl_io *)ctsio);
5635 
5636 		return (CTL_RETVAL_COMPLETE);
5637 	}
5638 
5639 	ctl_set_success(ctsio);
5640 	ctl_done((union ctl_io *)ctsio);
5641 	return (CTL_RETVAL_COMPLETE);
5642 }
5643 
5644 int
5645 ctl_write_same(struct ctl_scsiio *ctsio)
5646 {
5647 	struct ctl_lun *lun = CTL_LUN(ctsio);
5648 	struct ctl_lba_len_flags *lbalen;
5649 	uint64_t lba;
5650 	uint32_t num_blocks;
5651 	int len, retval;
5652 	uint8_t byte2;
5653 
5654 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5655 
5656 	switch (ctsio->cdb[0]) {
5657 	case WRITE_SAME_10: {
5658 		struct scsi_write_same_10 *cdb;
5659 
5660 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5661 
5662 		lba = scsi_4btoul(cdb->addr);
5663 		num_blocks = scsi_2btoul(cdb->length);
5664 		byte2 = cdb->byte2;
5665 		break;
5666 	}
5667 	case WRITE_SAME_16: {
5668 		struct scsi_write_same_16 *cdb;
5669 
5670 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5671 
5672 		lba = scsi_8btou64(cdb->addr);
5673 		num_blocks = scsi_4btoul(cdb->length);
5674 		byte2 = cdb->byte2;
5675 		break;
5676 	}
5677 	default:
5678 		/*
5679 		 * We got a command we don't support.  This shouldn't
5680 		 * happen, commands should be filtered out above us.
5681 		 */
5682 		ctl_set_invalid_opcode(ctsio);
5683 		ctl_done((union ctl_io *)ctsio);
5684 
5685 		return (CTL_RETVAL_COMPLETE);
5686 		break; /* NOTREACHED */
5687 	}
5688 
5689 	/* ANCHOR flag can be used only together with UNMAP */
5690 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5691 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5692 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5693 		ctl_done((union ctl_io *)ctsio);
5694 		return (CTL_RETVAL_COMPLETE);
5695 	}
5696 
5697 	/*
5698 	 * The first check is to make sure we're in bounds, the second
5699 	 * check is to catch wrap-around problems.  If the lba + num blocks
5700 	 * is less than the lba, then we've wrapped around and the block
5701 	 * range is invalid anyway.
5702 	 */
5703 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5704 	 || ((lba + num_blocks) < lba)) {
5705 		ctl_set_lba_out_of_range(ctsio,
5706 		    MAX(lba, lun->be_lun->maxlba + 1));
5707 		ctl_done((union ctl_io *)ctsio);
5708 		return (CTL_RETVAL_COMPLETE);
5709 	}
5710 
5711 	/* Zero number of blocks means "to the last logical block" */
5712 	if (num_blocks == 0) {
5713 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5714 			ctl_set_invalid_field(ctsio,
5715 					      /*sks_valid*/ 0,
5716 					      /*command*/ 1,
5717 					      /*field*/ 0,
5718 					      /*bit_valid*/ 0,
5719 					      /*bit*/ 0);
5720 			ctl_done((union ctl_io *)ctsio);
5721 			return (CTL_RETVAL_COMPLETE);
5722 		}
5723 		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5724 	}
5725 
5726 	len = lun->be_lun->blocksize;
5727 
5728 	/*
5729 	 * If we've got a kernel request that hasn't been malloced yet,
5730 	 * malloc it and tell the caller the data buffer is here.
5731 	 */
5732 	if ((byte2 & SWS_NDOB) == 0 &&
5733 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5734 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5735 		ctsio->kern_data_len = len;
5736 		ctsio->kern_total_len = len;
5737 		ctsio->kern_rel_offset = 0;
5738 		ctsio->kern_sg_entries = 0;
5739 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5740 		ctsio->be_move_done = ctl_config_move_done;
5741 		ctl_datamove((union ctl_io *)ctsio);
5742 
5743 		return (CTL_RETVAL_COMPLETE);
5744 	}
5745 
5746 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5747 	lbalen->lba = lba;
5748 	lbalen->len = num_blocks;
5749 	lbalen->flags = byte2;
5750 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5751 
5752 	return (retval);
5753 }
5754 
5755 int
5756 ctl_unmap(struct ctl_scsiio *ctsio)
5757 {
5758 	struct ctl_lun *lun = CTL_LUN(ctsio);
5759 	struct scsi_unmap *cdb;
5760 	struct ctl_ptr_len_flags *ptrlen;
5761 	struct scsi_unmap_header *hdr;
5762 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5763 	uint64_t lba;
5764 	uint32_t num_blocks;
5765 	int len, retval;
5766 	uint8_t byte2;
5767 
5768 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5769 
5770 	cdb = (struct scsi_unmap *)ctsio->cdb;
5771 	len = scsi_2btoul(cdb->length);
5772 	byte2 = cdb->byte2;
5773 
5774 	/*
5775 	 * If we've got a kernel request that hasn't been malloced yet,
5776 	 * malloc it and tell the caller the data buffer is here.
5777 	 */
5778 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5779 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5780 		ctsio->kern_data_len = len;
5781 		ctsio->kern_total_len = len;
5782 		ctsio->kern_rel_offset = 0;
5783 		ctsio->kern_sg_entries = 0;
5784 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5785 		ctsio->be_move_done = ctl_config_move_done;
5786 		ctl_datamove((union ctl_io *)ctsio);
5787 
5788 		return (CTL_RETVAL_COMPLETE);
5789 	}
5790 
5791 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5792 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5793 	if (len < sizeof (*hdr) ||
5794 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5795 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5796 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5797 		ctl_set_invalid_field(ctsio,
5798 				      /*sks_valid*/ 0,
5799 				      /*command*/ 0,
5800 				      /*field*/ 0,
5801 				      /*bit_valid*/ 0,
5802 				      /*bit*/ 0);
5803 		goto done;
5804 	}
5805 	len = scsi_2btoul(hdr->desc_length);
5806 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5807 	end = buf + len / sizeof(*buf);
5808 
5809 	endnz = buf;
5810 	for (range = buf; range < end; range++) {
5811 		lba = scsi_8btou64(range->lba);
5812 		num_blocks = scsi_4btoul(range->length);
5813 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5814 		 || ((lba + num_blocks) < lba)) {
5815 			ctl_set_lba_out_of_range(ctsio,
5816 			    MAX(lba, lun->be_lun->maxlba + 1));
5817 			ctl_done((union ctl_io *)ctsio);
5818 			return (CTL_RETVAL_COMPLETE);
5819 		}
5820 		if (num_blocks != 0)
5821 			endnz = range + 1;
5822 	}
5823 
5824 	/*
5825 	 * Block backend can not handle zero last range.
5826 	 * Filter it out and return if there is nothing left.
5827 	 */
5828 	len = (uint8_t *)endnz - (uint8_t *)buf;
5829 	if (len == 0) {
5830 		ctl_set_success(ctsio);
5831 		goto done;
5832 	}
5833 
5834 	mtx_lock(&lun->lun_lock);
5835 	ptrlen = (struct ctl_ptr_len_flags *)
5836 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5837 	ptrlen->ptr = (void *)buf;
5838 	ptrlen->len = len;
5839 	ptrlen->flags = byte2;
5840 	ctl_check_blocked(lun);
5841 	mtx_unlock(&lun->lun_lock);
5842 
5843 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5844 	return (retval);
5845 
5846 done:
5847 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5848 		free(ctsio->kern_data_ptr, M_CTL);
5849 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5850 	}
5851 	ctl_done((union ctl_io *)ctsio);
5852 	return (CTL_RETVAL_COMPLETE);
5853 }
5854 
5855 int
5856 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5857 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5858 {
5859 	struct ctl_lun *lun = CTL_LUN(ctsio);
5860 	uint8_t *current_cp;
5861 	int set_ua;
5862 	uint32_t initidx;
5863 
5864 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5865 	set_ua = 0;
5866 
5867 	current_cp = (page_index->page_data + (page_index->page_len *
5868 	    CTL_PAGE_CURRENT));
5869 
5870 	mtx_lock(&lun->lun_lock);
5871 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5872 		memcpy(current_cp, page_ptr, page_index->page_len);
5873 		set_ua = 1;
5874 	}
5875 	if (set_ua != 0)
5876 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5877 	mtx_unlock(&lun->lun_lock);
5878 	if (set_ua) {
5879 		ctl_isc_announce_mode(lun,
5880 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5881 		    page_index->page_code, page_index->subpage);
5882 	}
5883 	return (CTL_RETVAL_COMPLETE);
5884 }
5885 
5886 static void
5887 ctl_ie_timer(void *arg)
5888 {
5889 	struct ctl_lun *lun = arg;
5890 	uint64_t t;
5891 
5892 	if (lun->ie_asc == 0)
5893 		return;
5894 
5895 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5896 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5897 	else
5898 		lun->ie_reported = 0;
5899 
5900 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5901 		lun->ie_reportcnt++;
5902 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5903 		if (t == 0 || t == UINT32_MAX)
5904 			t = 3000;  /* 5 min */
5905 		callout_schedule(&lun->ie_callout, t * hz / 10);
5906 	}
5907 }
5908 
5909 int
5910 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5911 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5912 {
5913 	struct ctl_lun *lun = CTL_LUN(ctsio);
5914 	struct scsi_info_exceptions_page *pg;
5915 	uint64_t t;
5916 
5917 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5918 
5919 	pg = (struct scsi_info_exceptions_page *)page_ptr;
5920 	mtx_lock(&lun->lun_lock);
5921 	if (pg->info_flags & SIEP_FLAGS_TEST) {
5922 		lun->ie_asc = 0x5d;
5923 		lun->ie_ascq = 0xff;
5924 		if (pg->mrie == SIEP_MRIE_UA) {
5925 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5926 			lun->ie_reported = 1;
5927 		} else {
5928 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5929 			lun->ie_reported = -1;
5930 		}
5931 		lun->ie_reportcnt = 1;
5932 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5933 			lun->ie_reportcnt++;
5934 			t = scsi_4btoul(pg->interval_timer);
5935 			if (t == 0 || t == UINT32_MAX)
5936 				t = 3000;  /* 5 min */
5937 			callout_reset(&lun->ie_callout, t * hz / 10,
5938 			    ctl_ie_timer, lun);
5939 		}
5940 	} else {
5941 		lun->ie_asc = 0;
5942 		lun->ie_ascq = 0;
5943 		lun->ie_reported = 1;
5944 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5945 		lun->ie_reportcnt = UINT32_MAX;
5946 		callout_stop(&lun->ie_callout);
5947 	}
5948 	mtx_unlock(&lun->lun_lock);
5949 	return (CTL_RETVAL_COMPLETE);
5950 }
5951 
5952 static int
5953 ctl_do_mode_select(union ctl_io *io)
5954 {
5955 	struct ctl_lun *lun = CTL_LUN(io);
5956 	struct scsi_mode_page_header *page_header;
5957 	struct ctl_page_index *page_index;
5958 	struct ctl_scsiio *ctsio;
5959 	int page_len, page_len_offset, page_len_size;
5960 	union ctl_modepage_info *modepage_info;
5961 	uint16_t *len_left, *len_used;
5962 	int retval, i;
5963 
5964 	ctsio = &io->scsiio;
5965 	page_index = NULL;
5966 	page_len = 0;
5967 
5968 	modepage_info = (union ctl_modepage_info *)
5969 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5970 	len_left = &modepage_info->header.len_left;
5971 	len_used = &modepage_info->header.len_used;
5972 
5973 do_next_page:
5974 
5975 	page_header = (struct scsi_mode_page_header *)
5976 		(ctsio->kern_data_ptr + *len_used);
5977 
5978 	if (*len_left == 0) {
5979 		free(ctsio->kern_data_ptr, M_CTL);
5980 		ctl_set_success(ctsio);
5981 		ctl_done((union ctl_io *)ctsio);
5982 		return (CTL_RETVAL_COMPLETE);
5983 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5984 
5985 		free(ctsio->kern_data_ptr, M_CTL);
5986 		ctl_set_param_len_error(ctsio);
5987 		ctl_done((union ctl_io *)ctsio);
5988 		return (CTL_RETVAL_COMPLETE);
5989 
5990 	} else if ((page_header->page_code & SMPH_SPF)
5991 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5992 
5993 		free(ctsio->kern_data_ptr, M_CTL);
5994 		ctl_set_param_len_error(ctsio);
5995 		ctl_done((union ctl_io *)ctsio);
5996 		return (CTL_RETVAL_COMPLETE);
5997 	}
5998 
5999 
6000 	/*
6001 	 * XXX KDM should we do something with the block descriptor?
6002 	 */
6003 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6004 		page_index = &lun->mode_pages.index[i];
6005 		if (lun->be_lun->lun_type == T_DIRECT &&
6006 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6007 			continue;
6008 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6009 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6010 			continue;
6011 		if (lun->be_lun->lun_type == T_CDROM &&
6012 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6013 			continue;
6014 
6015 		if ((page_index->page_code & SMPH_PC_MASK) !=
6016 		    (page_header->page_code & SMPH_PC_MASK))
6017 			continue;
6018 
6019 		/*
6020 		 * If neither page has a subpage code, then we've got a
6021 		 * match.
6022 		 */
6023 		if (((page_index->page_code & SMPH_SPF) == 0)
6024 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6025 			page_len = page_header->page_length;
6026 			break;
6027 		}
6028 
6029 		/*
6030 		 * If both pages have subpages, then the subpage numbers
6031 		 * have to match.
6032 		 */
6033 		if ((page_index->page_code & SMPH_SPF)
6034 		  && (page_header->page_code & SMPH_SPF)) {
6035 			struct scsi_mode_page_header_sp *sph;
6036 
6037 			sph = (struct scsi_mode_page_header_sp *)page_header;
6038 			if (page_index->subpage == sph->subpage) {
6039 				page_len = scsi_2btoul(sph->page_length);
6040 				break;
6041 			}
6042 		}
6043 	}
6044 
6045 	/*
6046 	 * If we couldn't find the page, or if we don't have a mode select
6047 	 * handler for it, send back an error to the user.
6048 	 */
6049 	if ((i >= CTL_NUM_MODE_PAGES)
6050 	 || (page_index->select_handler == NULL)) {
6051 		ctl_set_invalid_field(ctsio,
6052 				      /*sks_valid*/ 1,
6053 				      /*command*/ 0,
6054 				      /*field*/ *len_used,
6055 				      /*bit_valid*/ 0,
6056 				      /*bit*/ 0);
6057 		free(ctsio->kern_data_ptr, M_CTL);
6058 		ctl_done((union ctl_io *)ctsio);
6059 		return (CTL_RETVAL_COMPLETE);
6060 	}
6061 
6062 	if (page_index->page_code & SMPH_SPF) {
6063 		page_len_offset = 2;
6064 		page_len_size = 2;
6065 	} else {
6066 		page_len_size = 1;
6067 		page_len_offset = 1;
6068 	}
6069 
6070 	/*
6071 	 * If the length the initiator gives us isn't the one we specify in
6072 	 * the mode page header, or if they didn't specify enough data in
6073 	 * the CDB to avoid truncating this page, kick out the request.
6074 	 */
6075 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6076 		ctl_set_invalid_field(ctsio,
6077 				      /*sks_valid*/ 1,
6078 				      /*command*/ 0,
6079 				      /*field*/ *len_used + page_len_offset,
6080 				      /*bit_valid*/ 0,
6081 				      /*bit*/ 0);
6082 		free(ctsio->kern_data_ptr, M_CTL);
6083 		ctl_done((union ctl_io *)ctsio);
6084 		return (CTL_RETVAL_COMPLETE);
6085 	}
6086 	if (*len_left < page_index->page_len) {
6087 		free(ctsio->kern_data_ptr, M_CTL);
6088 		ctl_set_param_len_error(ctsio);
6089 		ctl_done((union ctl_io *)ctsio);
6090 		return (CTL_RETVAL_COMPLETE);
6091 	}
6092 
6093 	/*
6094 	 * Run through the mode page, checking to make sure that the bits
6095 	 * the user changed are actually legal for him to change.
6096 	 */
6097 	for (i = 0; i < page_index->page_len; i++) {
6098 		uint8_t *user_byte, *change_mask, *current_byte;
6099 		int bad_bit;
6100 		int j;
6101 
6102 		user_byte = (uint8_t *)page_header + i;
6103 		change_mask = page_index->page_data +
6104 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6105 		current_byte = page_index->page_data +
6106 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6107 
6108 		/*
6109 		 * Check to see whether the user set any bits in this byte
6110 		 * that he is not allowed to set.
6111 		 */
6112 		if ((*user_byte & ~(*change_mask)) ==
6113 		    (*current_byte & ~(*change_mask)))
6114 			continue;
6115 
6116 		/*
6117 		 * Go through bit by bit to determine which one is illegal.
6118 		 */
6119 		bad_bit = 0;
6120 		for (j = 7; j >= 0; j--) {
6121 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6122 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6123 				bad_bit = i;
6124 				break;
6125 			}
6126 		}
6127 		ctl_set_invalid_field(ctsio,
6128 				      /*sks_valid*/ 1,
6129 				      /*command*/ 0,
6130 				      /*field*/ *len_used + i,
6131 				      /*bit_valid*/ 1,
6132 				      /*bit*/ bad_bit);
6133 		free(ctsio->kern_data_ptr, M_CTL);
6134 		ctl_done((union ctl_io *)ctsio);
6135 		return (CTL_RETVAL_COMPLETE);
6136 	}
6137 
6138 	/*
6139 	 * Decrement these before we call the page handler, since we may
6140 	 * end up getting called back one way or another before the handler
6141 	 * returns to this context.
6142 	 */
6143 	*len_left -= page_index->page_len;
6144 	*len_used += page_index->page_len;
6145 
6146 	retval = page_index->select_handler(ctsio, page_index,
6147 					    (uint8_t *)page_header);
6148 
6149 	/*
6150 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6151 	 * wait until this queued command completes to finish processing
6152 	 * the mode page.  If it returns anything other than
6153 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6154 	 * already set the sense information, freed the data pointer, and
6155 	 * completed the io for us.
6156 	 */
6157 	if (retval != CTL_RETVAL_COMPLETE)
6158 		goto bailout_no_done;
6159 
6160 	/*
6161 	 * If the initiator sent us more than one page, parse the next one.
6162 	 */
6163 	if (*len_left > 0)
6164 		goto do_next_page;
6165 
6166 	ctl_set_success(ctsio);
6167 	free(ctsio->kern_data_ptr, M_CTL);
6168 	ctl_done((union ctl_io *)ctsio);
6169 
6170 bailout_no_done:
6171 
6172 	return (CTL_RETVAL_COMPLETE);
6173 
6174 }
6175 
6176 int
6177 ctl_mode_select(struct ctl_scsiio *ctsio)
6178 {
6179 	struct ctl_lun *lun = CTL_LUN(ctsio);
6180 	union ctl_modepage_info *modepage_info;
6181 	int bd_len, i, header_size, param_len, pf, rtd, sp;
6182 	uint32_t initidx;
6183 
6184 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6185 	switch (ctsio->cdb[0]) {
6186 	case MODE_SELECT_6: {
6187 		struct scsi_mode_select_6 *cdb;
6188 
6189 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6190 
6191 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6192 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6193 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6194 		param_len = cdb->length;
6195 		header_size = sizeof(struct scsi_mode_header_6);
6196 		break;
6197 	}
6198 	case MODE_SELECT_10: {
6199 		struct scsi_mode_select_10 *cdb;
6200 
6201 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6202 
6203 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6204 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6205 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6206 		param_len = scsi_2btoul(cdb->length);
6207 		header_size = sizeof(struct scsi_mode_header_10);
6208 		break;
6209 	}
6210 	default:
6211 		ctl_set_invalid_opcode(ctsio);
6212 		ctl_done((union ctl_io *)ctsio);
6213 		return (CTL_RETVAL_COMPLETE);
6214 	}
6215 
6216 	if (rtd) {
6217 		if (param_len != 0) {
6218 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6219 			    /*command*/ 1, /*field*/ 0,
6220 			    /*bit_valid*/ 0, /*bit*/ 0);
6221 			ctl_done((union ctl_io *)ctsio);
6222 			return (CTL_RETVAL_COMPLETE);
6223 		}
6224 
6225 		/* Revert to defaults. */
6226 		ctl_init_page_index(lun);
6227 		mtx_lock(&lun->lun_lock);
6228 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6229 		mtx_unlock(&lun->lun_lock);
6230 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6231 			ctl_isc_announce_mode(lun, -1,
6232 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6233 			    lun->mode_pages.index[i].subpage);
6234 		}
6235 		ctl_set_success(ctsio);
6236 		ctl_done((union ctl_io *)ctsio);
6237 		return (CTL_RETVAL_COMPLETE);
6238 	}
6239 
6240 	/*
6241 	 * From SPC-3:
6242 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6243 	 * shall be empty. This condition shall not be considered as an error."
6244 	 */
6245 	if (param_len == 0) {
6246 		ctl_set_success(ctsio);
6247 		ctl_done((union ctl_io *)ctsio);
6248 		return (CTL_RETVAL_COMPLETE);
6249 	}
6250 
6251 	/*
6252 	 * Since we'll hit this the first time through, prior to
6253 	 * allocation, we don't need to free a data buffer here.
6254 	 */
6255 	if (param_len < header_size) {
6256 		ctl_set_param_len_error(ctsio);
6257 		ctl_done((union ctl_io *)ctsio);
6258 		return (CTL_RETVAL_COMPLETE);
6259 	}
6260 
6261 	/*
6262 	 * Allocate the data buffer and grab the user's data.  In theory,
6263 	 * we shouldn't have to sanity check the parameter list length here
6264 	 * because the maximum size is 64K.  We should be able to malloc
6265 	 * that much without too many problems.
6266 	 */
6267 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6268 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6269 		ctsio->kern_data_len = param_len;
6270 		ctsio->kern_total_len = param_len;
6271 		ctsio->kern_rel_offset = 0;
6272 		ctsio->kern_sg_entries = 0;
6273 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6274 		ctsio->be_move_done = ctl_config_move_done;
6275 		ctl_datamove((union ctl_io *)ctsio);
6276 
6277 		return (CTL_RETVAL_COMPLETE);
6278 	}
6279 
6280 	switch (ctsio->cdb[0]) {
6281 	case MODE_SELECT_6: {
6282 		struct scsi_mode_header_6 *mh6;
6283 
6284 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6285 		bd_len = mh6->blk_desc_len;
6286 		break;
6287 	}
6288 	case MODE_SELECT_10: {
6289 		struct scsi_mode_header_10 *mh10;
6290 
6291 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6292 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6293 		break;
6294 	}
6295 	default:
6296 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6297 	}
6298 
6299 	if (param_len < (header_size + bd_len)) {
6300 		free(ctsio->kern_data_ptr, M_CTL);
6301 		ctl_set_param_len_error(ctsio);
6302 		ctl_done((union ctl_io *)ctsio);
6303 		return (CTL_RETVAL_COMPLETE);
6304 	}
6305 
6306 	/*
6307 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6308 	 * ctl_config_write_done(), it'll get passed back to
6309 	 * ctl_do_mode_select() for further processing, or completion if
6310 	 * we're all done.
6311 	 */
6312 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6313 	ctsio->io_cont = ctl_do_mode_select;
6314 
6315 	modepage_info = (union ctl_modepage_info *)
6316 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6317 	memset(modepage_info, 0, sizeof(*modepage_info));
6318 	modepage_info->header.len_left = param_len - header_size - bd_len;
6319 	modepage_info->header.len_used = header_size + bd_len;
6320 
6321 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6322 }
6323 
6324 int
6325 ctl_mode_sense(struct ctl_scsiio *ctsio)
6326 {
6327 	struct ctl_lun *lun = CTL_LUN(ctsio);
6328 	int pc, page_code, dbd, llba, subpage;
6329 	int alloc_len, page_len, header_len, total_len;
6330 	struct scsi_mode_block_descr *block_desc;
6331 	struct ctl_page_index *page_index;
6332 
6333 	dbd = 0;
6334 	llba = 0;
6335 	block_desc = NULL;
6336 
6337 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6338 
6339 	switch (ctsio->cdb[0]) {
6340 	case MODE_SENSE_6: {
6341 		struct scsi_mode_sense_6 *cdb;
6342 
6343 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6344 
6345 		header_len = sizeof(struct scsi_mode_hdr_6);
6346 		if (cdb->byte2 & SMS_DBD)
6347 			dbd = 1;
6348 		else
6349 			header_len += sizeof(struct scsi_mode_block_descr);
6350 
6351 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6352 		page_code = cdb->page & SMS_PAGE_CODE;
6353 		subpage = cdb->subpage;
6354 		alloc_len = cdb->length;
6355 		break;
6356 	}
6357 	case MODE_SENSE_10: {
6358 		struct scsi_mode_sense_10 *cdb;
6359 
6360 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6361 
6362 		header_len = sizeof(struct scsi_mode_hdr_10);
6363 
6364 		if (cdb->byte2 & SMS_DBD)
6365 			dbd = 1;
6366 		else
6367 			header_len += sizeof(struct scsi_mode_block_descr);
6368 		if (cdb->byte2 & SMS10_LLBAA)
6369 			llba = 1;
6370 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6371 		page_code = cdb->page & SMS_PAGE_CODE;
6372 		subpage = cdb->subpage;
6373 		alloc_len = scsi_2btoul(cdb->length);
6374 		break;
6375 	}
6376 	default:
6377 		ctl_set_invalid_opcode(ctsio);
6378 		ctl_done((union ctl_io *)ctsio);
6379 		return (CTL_RETVAL_COMPLETE);
6380 		break; /* NOTREACHED */
6381 	}
6382 
6383 	/*
6384 	 * We have to make a first pass through to calculate the size of
6385 	 * the pages that match the user's query.  Then we allocate enough
6386 	 * memory to hold it, and actually copy the data into the buffer.
6387 	 */
6388 	switch (page_code) {
6389 	case SMS_ALL_PAGES_PAGE: {
6390 		u_int i;
6391 
6392 		page_len = 0;
6393 
6394 		/*
6395 		 * At the moment, values other than 0 and 0xff here are
6396 		 * reserved according to SPC-3.
6397 		 */
6398 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6399 		 && (subpage != SMS_SUBPAGE_ALL)) {
6400 			ctl_set_invalid_field(ctsio,
6401 					      /*sks_valid*/ 1,
6402 					      /*command*/ 1,
6403 					      /*field*/ 3,
6404 					      /*bit_valid*/ 0,
6405 					      /*bit*/ 0);
6406 			ctl_done((union ctl_io *)ctsio);
6407 			return (CTL_RETVAL_COMPLETE);
6408 		}
6409 
6410 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6411 			page_index = &lun->mode_pages.index[i];
6412 
6413 			/* Make sure the page is supported for this dev type */
6414 			if (lun->be_lun->lun_type == T_DIRECT &&
6415 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6416 				continue;
6417 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6418 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6419 				continue;
6420 			if (lun->be_lun->lun_type == T_CDROM &&
6421 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6422 				continue;
6423 
6424 			/*
6425 			 * We don't use this subpage if the user didn't
6426 			 * request all subpages.
6427 			 */
6428 			if ((page_index->subpage != 0)
6429 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6430 				continue;
6431 
6432 #if 0
6433 			printf("found page %#x len %d\n",
6434 			       page_index->page_code & SMPH_PC_MASK,
6435 			       page_index->page_len);
6436 #endif
6437 			page_len += page_index->page_len;
6438 		}
6439 		break;
6440 	}
6441 	default: {
6442 		u_int i;
6443 
6444 		page_len = 0;
6445 
6446 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6447 			page_index = &lun->mode_pages.index[i];
6448 
6449 			/* Make sure the page is supported for this dev type */
6450 			if (lun->be_lun->lun_type == T_DIRECT &&
6451 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6452 				continue;
6453 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6454 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6455 				continue;
6456 			if (lun->be_lun->lun_type == T_CDROM &&
6457 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6458 				continue;
6459 
6460 			/* Look for the right page code */
6461 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6462 				continue;
6463 
6464 			/* Look for the right subpage or the subpage wildcard*/
6465 			if ((page_index->subpage != subpage)
6466 			 && (subpage != SMS_SUBPAGE_ALL))
6467 				continue;
6468 
6469 #if 0
6470 			printf("found page %#x len %d\n",
6471 			       page_index->page_code & SMPH_PC_MASK,
6472 			       page_index->page_len);
6473 #endif
6474 
6475 			page_len += page_index->page_len;
6476 		}
6477 
6478 		if (page_len == 0) {
6479 			ctl_set_invalid_field(ctsio,
6480 					      /*sks_valid*/ 1,
6481 					      /*command*/ 1,
6482 					      /*field*/ 2,
6483 					      /*bit_valid*/ 1,
6484 					      /*bit*/ 5);
6485 			ctl_done((union ctl_io *)ctsio);
6486 			return (CTL_RETVAL_COMPLETE);
6487 		}
6488 		break;
6489 	}
6490 	}
6491 
6492 	total_len = header_len + page_len;
6493 #if 0
6494 	printf("header_len = %d, page_len = %d, total_len = %d\n",
6495 	       header_len, page_len, total_len);
6496 #endif
6497 
6498 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6499 	ctsio->kern_sg_entries = 0;
6500 	ctsio->kern_rel_offset = 0;
6501 	if (total_len < alloc_len) {
6502 		ctsio->residual = alloc_len - total_len;
6503 		ctsio->kern_data_len = total_len;
6504 		ctsio->kern_total_len = total_len;
6505 	} else {
6506 		ctsio->residual = 0;
6507 		ctsio->kern_data_len = alloc_len;
6508 		ctsio->kern_total_len = alloc_len;
6509 	}
6510 
6511 	switch (ctsio->cdb[0]) {
6512 	case MODE_SENSE_6: {
6513 		struct scsi_mode_hdr_6 *header;
6514 
6515 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6516 
6517 		header->datalen = MIN(total_len - 1, 254);
6518 		if (lun->be_lun->lun_type == T_DIRECT) {
6519 			header->dev_specific = 0x10; /* DPOFUA */
6520 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6521 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6522 				header->dev_specific |= 0x80; /* WP */
6523 		}
6524 		if (dbd)
6525 			header->block_descr_len = 0;
6526 		else
6527 			header->block_descr_len =
6528 				sizeof(struct scsi_mode_block_descr);
6529 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6530 		break;
6531 	}
6532 	case MODE_SENSE_10: {
6533 		struct scsi_mode_hdr_10 *header;
6534 		int datalen;
6535 
6536 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6537 
6538 		datalen = MIN(total_len - 2, 65533);
6539 		scsi_ulto2b(datalen, header->datalen);
6540 		if (lun->be_lun->lun_type == T_DIRECT) {
6541 			header->dev_specific = 0x10; /* DPOFUA */
6542 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6543 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6544 				header->dev_specific |= 0x80; /* WP */
6545 		}
6546 		if (dbd)
6547 			scsi_ulto2b(0, header->block_descr_len);
6548 		else
6549 			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6550 				    header->block_descr_len);
6551 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6552 		break;
6553 	}
6554 	default:
6555 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6556 	}
6557 
6558 	/*
6559 	 * If we've got a disk, use its blocksize in the block
6560 	 * descriptor.  Otherwise, just set it to 0.
6561 	 */
6562 	if (dbd == 0) {
6563 		if (lun->be_lun->lun_type == T_DIRECT)
6564 			scsi_ulto3b(lun->be_lun->blocksize,
6565 				    block_desc->block_len);
6566 		else
6567 			scsi_ulto3b(0, block_desc->block_len);
6568 	}
6569 
6570 	switch (page_code) {
6571 	case SMS_ALL_PAGES_PAGE: {
6572 		int i, data_used;
6573 
6574 		data_used = header_len;
6575 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6576 			struct ctl_page_index *page_index;
6577 
6578 			page_index = &lun->mode_pages.index[i];
6579 			if (lun->be_lun->lun_type == T_DIRECT &&
6580 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6581 				continue;
6582 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6583 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6584 				continue;
6585 			if (lun->be_lun->lun_type == T_CDROM &&
6586 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6587 				continue;
6588 
6589 			/*
6590 			 * We don't use this subpage if the user didn't
6591 			 * request all subpages.  We already checked (above)
6592 			 * to make sure the user only specified a subpage
6593 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6594 			 */
6595 			if ((page_index->subpage != 0)
6596 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6597 				continue;
6598 
6599 			/*
6600 			 * Call the handler, if it exists, to update the
6601 			 * page to the latest values.
6602 			 */
6603 			if (page_index->sense_handler != NULL)
6604 				page_index->sense_handler(ctsio, page_index,pc);
6605 
6606 			memcpy(ctsio->kern_data_ptr + data_used,
6607 			       page_index->page_data +
6608 			       (page_index->page_len * pc),
6609 			       page_index->page_len);
6610 			data_used += page_index->page_len;
6611 		}
6612 		break;
6613 	}
6614 	default: {
6615 		int i, data_used;
6616 
6617 		data_used = header_len;
6618 
6619 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6620 			struct ctl_page_index *page_index;
6621 
6622 			page_index = &lun->mode_pages.index[i];
6623 
6624 			/* Look for the right page code */
6625 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6626 				continue;
6627 
6628 			/* Look for the right subpage or the subpage wildcard*/
6629 			if ((page_index->subpage != subpage)
6630 			 && (subpage != SMS_SUBPAGE_ALL))
6631 				continue;
6632 
6633 			/* Make sure the page is supported for this dev type */
6634 			if (lun->be_lun->lun_type == T_DIRECT &&
6635 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6636 				continue;
6637 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6638 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6639 				continue;
6640 			if (lun->be_lun->lun_type == T_CDROM &&
6641 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6642 				continue;
6643 
6644 			/*
6645 			 * Call the handler, if it exists, to update the
6646 			 * page to the latest values.
6647 			 */
6648 			if (page_index->sense_handler != NULL)
6649 				page_index->sense_handler(ctsio, page_index,pc);
6650 
6651 			memcpy(ctsio->kern_data_ptr + data_used,
6652 			       page_index->page_data +
6653 			       (page_index->page_len * pc),
6654 			       page_index->page_len);
6655 			data_used += page_index->page_len;
6656 		}
6657 		break;
6658 	}
6659 	}
6660 
6661 	ctl_set_success(ctsio);
6662 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6663 	ctsio->be_move_done = ctl_config_move_done;
6664 	ctl_datamove((union ctl_io *)ctsio);
6665 	return (CTL_RETVAL_COMPLETE);
6666 }
6667 
6668 int
6669 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6670 			       struct ctl_page_index *page_index,
6671 			       int pc)
6672 {
6673 	struct ctl_lun *lun = CTL_LUN(ctsio);
6674 	struct scsi_log_param_header *phdr;
6675 	uint8_t *data;
6676 	uint64_t val;
6677 
6678 	data = page_index->page_data;
6679 
6680 	if (lun->backend->lun_attr != NULL &&
6681 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6682 	     != UINT64_MAX) {
6683 		phdr = (struct scsi_log_param_header *)data;
6684 		scsi_ulto2b(0x0001, phdr->param_code);
6685 		phdr->param_control = SLP_LBIN | SLP_LP;
6686 		phdr->param_len = 8;
6687 		data = (uint8_t *)(phdr + 1);
6688 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6689 		data[4] = 0x02; /* per-pool */
6690 		data += phdr->param_len;
6691 	}
6692 
6693 	if (lun->backend->lun_attr != NULL &&
6694 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6695 	     != UINT64_MAX) {
6696 		phdr = (struct scsi_log_param_header *)data;
6697 		scsi_ulto2b(0x0002, phdr->param_code);
6698 		phdr->param_control = SLP_LBIN | SLP_LP;
6699 		phdr->param_len = 8;
6700 		data = (uint8_t *)(phdr + 1);
6701 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6702 		data[4] = 0x01; /* per-LUN */
6703 		data += phdr->param_len;
6704 	}
6705 
6706 	if (lun->backend->lun_attr != NULL &&
6707 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6708 	     != UINT64_MAX) {
6709 		phdr = (struct scsi_log_param_header *)data;
6710 		scsi_ulto2b(0x00f1, phdr->param_code);
6711 		phdr->param_control = SLP_LBIN | SLP_LP;
6712 		phdr->param_len = 8;
6713 		data = (uint8_t *)(phdr + 1);
6714 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6715 		data[4] = 0x02; /* per-pool */
6716 		data += phdr->param_len;
6717 	}
6718 
6719 	if (lun->backend->lun_attr != NULL &&
6720 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6721 	     != UINT64_MAX) {
6722 		phdr = (struct scsi_log_param_header *)data;
6723 		scsi_ulto2b(0x00f2, phdr->param_code);
6724 		phdr->param_control = SLP_LBIN | SLP_LP;
6725 		phdr->param_len = 8;
6726 		data = (uint8_t *)(phdr + 1);
6727 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6728 		data[4] = 0x02; /* per-pool */
6729 		data += phdr->param_len;
6730 	}
6731 
6732 	page_index->page_len = data - page_index->page_data;
6733 	return (0);
6734 }
6735 
6736 int
6737 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6738 			       struct ctl_page_index *page_index,
6739 			       int pc)
6740 {
6741 	struct ctl_lun *lun = CTL_LUN(ctsio);
6742 	struct stat_page *data;
6743 	struct bintime *t;
6744 
6745 	data = (struct stat_page *)page_index->page_data;
6746 
6747 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6748 	data->sap.hdr.param_control = SLP_LBIN;
6749 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6750 	    sizeof(struct scsi_log_param_header);
6751 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6752 	    data->sap.read_num);
6753 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6754 	    data->sap.write_num);
6755 	if (lun->be_lun->blocksize > 0) {
6756 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6757 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6758 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6759 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6760 	}
6761 	t = &lun->stats.time[CTL_STATS_READ];
6762 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6763 	    data->sap.read_int);
6764 	t = &lun->stats.time[CTL_STATS_WRITE];
6765 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6766 	    data->sap.write_int);
6767 	scsi_u64to8b(0, data->sap.weighted_num);
6768 	scsi_u64to8b(0, data->sap.weighted_int);
6769 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6770 	data->it.hdr.param_control = SLP_LBIN;
6771 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6772 	    sizeof(struct scsi_log_param_header);
6773 #ifdef CTL_TIME_IO
6774 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6775 #endif
6776 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6777 	data->it.hdr.param_control = SLP_LBIN;
6778 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6779 	    sizeof(struct scsi_log_param_header);
6780 	scsi_ulto4b(3, data->ti.exponent);
6781 	scsi_ulto4b(1, data->ti.integer);
6782 	return (0);
6783 }
6784 
6785 int
6786 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6787 			       struct ctl_page_index *page_index,
6788 			       int pc)
6789 {
6790 	struct ctl_lun *lun = CTL_LUN(ctsio);
6791 	struct scsi_log_informational_exceptions *data;
6792 
6793 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6794 
6795 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6796 	data->hdr.param_control = SLP_LBIN;
6797 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6798 	    sizeof(struct scsi_log_param_header);
6799 	data->ie_asc = lun->ie_asc;
6800 	data->ie_ascq = lun->ie_ascq;
6801 	data->temperature = 0xff;
6802 	return (0);
6803 }
6804 
6805 int
6806 ctl_log_sense(struct ctl_scsiio *ctsio)
6807 {
6808 	struct ctl_lun *lun = CTL_LUN(ctsio);
6809 	int i, pc, page_code, subpage;
6810 	int alloc_len, total_len;
6811 	struct ctl_page_index *page_index;
6812 	struct scsi_log_sense *cdb;
6813 	struct scsi_log_header *header;
6814 
6815 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6816 
6817 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6818 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6819 	page_code = cdb->page & SLS_PAGE_CODE;
6820 	subpage = cdb->subpage;
6821 	alloc_len = scsi_2btoul(cdb->length);
6822 
6823 	page_index = NULL;
6824 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6825 		page_index = &lun->log_pages.index[i];
6826 
6827 		/* Look for the right page code */
6828 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6829 			continue;
6830 
6831 		/* Look for the right subpage or the subpage wildcard*/
6832 		if (page_index->subpage != subpage)
6833 			continue;
6834 
6835 		break;
6836 	}
6837 	if (i >= CTL_NUM_LOG_PAGES) {
6838 		ctl_set_invalid_field(ctsio,
6839 				      /*sks_valid*/ 1,
6840 				      /*command*/ 1,
6841 				      /*field*/ 2,
6842 				      /*bit_valid*/ 0,
6843 				      /*bit*/ 0);
6844 		ctl_done((union ctl_io *)ctsio);
6845 		return (CTL_RETVAL_COMPLETE);
6846 	}
6847 
6848 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6849 
6850 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6851 	ctsio->kern_sg_entries = 0;
6852 	ctsio->kern_rel_offset = 0;
6853 	if (total_len < alloc_len) {
6854 		ctsio->residual = alloc_len - total_len;
6855 		ctsio->kern_data_len = total_len;
6856 		ctsio->kern_total_len = total_len;
6857 	} else {
6858 		ctsio->residual = 0;
6859 		ctsio->kern_data_len = alloc_len;
6860 		ctsio->kern_total_len = alloc_len;
6861 	}
6862 
6863 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6864 	header->page = page_index->page_code;
6865 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6866 		header->page |= SL_DS;
6867 	if (page_index->subpage) {
6868 		header->page |= SL_SPF;
6869 		header->subpage = page_index->subpage;
6870 	}
6871 	scsi_ulto2b(page_index->page_len, header->datalen);
6872 
6873 	/*
6874 	 * Call the handler, if it exists, to update the
6875 	 * page to the latest values.
6876 	 */
6877 	if (page_index->sense_handler != NULL)
6878 		page_index->sense_handler(ctsio, page_index, pc);
6879 
6880 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6881 
6882 	ctl_set_success(ctsio);
6883 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6884 	ctsio->be_move_done = ctl_config_move_done;
6885 	ctl_datamove((union ctl_io *)ctsio);
6886 	return (CTL_RETVAL_COMPLETE);
6887 }
6888 
6889 int
6890 ctl_read_capacity(struct ctl_scsiio *ctsio)
6891 {
6892 	struct ctl_lun *lun = CTL_LUN(ctsio);
6893 	struct scsi_read_capacity *cdb;
6894 	struct scsi_read_capacity_data *data;
6895 	uint32_t lba;
6896 
6897 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6898 
6899 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6900 
6901 	lba = scsi_4btoul(cdb->addr);
6902 	if (((cdb->pmi & SRC_PMI) == 0)
6903 	 && (lba != 0)) {
6904 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6905 				      /*sks_valid*/ 1,
6906 				      /*command*/ 1,
6907 				      /*field*/ 2,
6908 				      /*bit_valid*/ 0,
6909 				      /*bit*/ 0);
6910 		ctl_done((union ctl_io *)ctsio);
6911 		return (CTL_RETVAL_COMPLETE);
6912 	}
6913 
6914 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6915 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6916 	ctsio->residual = 0;
6917 	ctsio->kern_data_len = sizeof(*data);
6918 	ctsio->kern_total_len = sizeof(*data);
6919 	ctsio->kern_rel_offset = 0;
6920 	ctsio->kern_sg_entries = 0;
6921 
6922 	/*
6923 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6924 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6925 	 * serivce action set.
6926 	 */
6927 	if (lun->be_lun->maxlba > 0xfffffffe)
6928 		scsi_ulto4b(0xffffffff, data->addr);
6929 	else
6930 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6931 
6932 	/*
6933 	 * XXX KDM this may not be 512 bytes...
6934 	 */
6935 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6936 
6937 	ctl_set_success(ctsio);
6938 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6939 	ctsio->be_move_done = ctl_config_move_done;
6940 	ctl_datamove((union ctl_io *)ctsio);
6941 	return (CTL_RETVAL_COMPLETE);
6942 }
6943 
6944 int
6945 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6946 {
6947 	struct ctl_lun *lun = CTL_LUN(ctsio);
6948 	struct scsi_read_capacity_16 *cdb;
6949 	struct scsi_read_capacity_data_long *data;
6950 	uint64_t lba;
6951 	uint32_t alloc_len;
6952 
6953 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6954 
6955 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6956 
6957 	alloc_len = scsi_4btoul(cdb->alloc_len);
6958 	lba = scsi_8btou64(cdb->addr);
6959 
6960 	if ((cdb->reladr & SRC16_PMI)
6961 	 && (lba != 0)) {
6962 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6963 				      /*sks_valid*/ 1,
6964 				      /*command*/ 1,
6965 				      /*field*/ 2,
6966 				      /*bit_valid*/ 0,
6967 				      /*bit*/ 0);
6968 		ctl_done((union ctl_io *)ctsio);
6969 		return (CTL_RETVAL_COMPLETE);
6970 	}
6971 
6972 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6973 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6974 
6975 	if (sizeof(*data) < alloc_len) {
6976 		ctsio->residual = alloc_len - sizeof(*data);
6977 		ctsio->kern_data_len = sizeof(*data);
6978 		ctsio->kern_total_len = sizeof(*data);
6979 	} else {
6980 		ctsio->residual = 0;
6981 		ctsio->kern_data_len = alloc_len;
6982 		ctsio->kern_total_len = alloc_len;
6983 	}
6984 	ctsio->kern_rel_offset = 0;
6985 	ctsio->kern_sg_entries = 0;
6986 
6987 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6988 	/* XXX KDM this may not be 512 bytes... */
6989 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6990 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6991 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6992 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6993 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6994 
6995 	ctl_set_success(ctsio);
6996 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6997 	ctsio->be_move_done = ctl_config_move_done;
6998 	ctl_datamove((union ctl_io *)ctsio);
6999 	return (CTL_RETVAL_COMPLETE);
7000 }
7001 
7002 int
7003 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7004 {
7005 	struct ctl_lun *lun = CTL_LUN(ctsio);
7006 	struct scsi_get_lba_status *cdb;
7007 	struct scsi_get_lba_status_data *data;
7008 	struct ctl_lba_len_flags *lbalen;
7009 	uint64_t lba;
7010 	uint32_t alloc_len, total_len;
7011 	int retval;
7012 
7013 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7014 
7015 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7016 	lba = scsi_8btou64(cdb->addr);
7017 	alloc_len = scsi_4btoul(cdb->alloc_len);
7018 
7019 	if (lba > lun->be_lun->maxlba) {
7020 		ctl_set_lba_out_of_range(ctsio, lba);
7021 		ctl_done((union ctl_io *)ctsio);
7022 		return (CTL_RETVAL_COMPLETE);
7023 	}
7024 
7025 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7026 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7027 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7028 
7029 	if (total_len < alloc_len) {
7030 		ctsio->residual = alloc_len - total_len;
7031 		ctsio->kern_data_len = total_len;
7032 		ctsio->kern_total_len = total_len;
7033 	} else {
7034 		ctsio->residual = 0;
7035 		ctsio->kern_data_len = alloc_len;
7036 		ctsio->kern_total_len = alloc_len;
7037 	}
7038 	ctsio->kern_rel_offset = 0;
7039 	ctsio->kern_sg_entries = 0;
7040 
7041 	/* Fill dummy data in case backend can't tell anything. */
7042 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7043 	scsi_u64to8b(lba, data->descr[0].addr);
7044 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7045 	    data->descr[0].length);
7046 	data->descr[0].status = 0; /* Mapped or unknown. */
7047 
7048 	ctl_set_success(ctsio);
7049 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7050 	ctsio->be_move_done = ctl_config_move_done;
7051 
7052 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7053 	lbalen->lba = lba;
7054 	lbalen->len = total_len;
7055 	lbalen->flags = 0;
7056 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7057 	return (CTL_RETVAL_COMPLETE);
7058 }
7059 
7060 int
7061 ctl_read_defect(struct ctl_scsiio *ctsio)
7062 {
7063 	struct scsi_read_defect_data_10 *ccb10;
7064 	struct scsi_read_defect_data_12 *ccb12;
7065 	struct scsi_read_defect_data_hdr_10 *data10;
7066 	struct scsi_read_defect_data_hdr_12 *data12;
7067 	uint32_t alloc_len, data_len;
7068 	uint8_t format;
7069 
7070 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7071 
7072 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7073 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7074 		format = ccb10->format;
7075 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7076 		data_len = sizeof(*data10);
7077 	} else {
7078 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7079 		format = ccb12->format;
7080 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7081 		data_len = sizeof(*data12);
7082 	}
7083 	if (alloc_len == 0) {
7084 		ctl_set_success(ctsio);
7085 		ctl_done((union ctl_io *)ctsio);
7086 		return (CTL_RETVAL_COMPLETE);
7087 	}
7088 
7089 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7090 	if (data_len < alloc_len) {
7091 		ctsio->residual = alloc_len - data_len;
7092 		ctsio->kern_data_len = data_len;
7093 		ctsio->kern_total_len = data_len;
7094 	} else {
7095 		ctsio->residual = 0;
7096 		ctsio->kern_data_len = alloc_len;
7097 		ctsio->kern_total_len = alloc_len;
7098 	}
7099 	ctsio->kern_rel_offset = 0;
7100 	ctsio->kern_sg_entries = 0;
7101 
7102 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7103 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7104 		    ctsio->kern_data_ptr;
7105 		data10->format = format;
7106 		scsi_ulto2b(0, data10->length);
7107 	} else {
7108 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7109 		    ctsio->kern_data_ptr;
7110 		data12->format = format;
7111 		scsi_ulto2b(0, data12->generation);
7112 		scsi_ulto4b(0, data12->length);
7113 	}
7114 
7115 	ctl_set_success(ctsio);
7116 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7117 	ctsio->be_move_done = ctl_config_move_done;
7118 	ctl_datamove((union ctl_io *)ctsio);
7119 	return (CTL_RETVAL_COMPLETE);
7120 }
7121 
7122 int
7123 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7124 {
7125 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7126 	struct ctl_lun *lun = CTL_LUN(ctsio);
7127 	struct scsi_maintenance_in *cdb;
7128 	int retval;
7129 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7130 	int num_ha_groups, num_target_ports, shared_group;
7131 	struct ctl_port *port;
7132 	struct scsi_target_group_data *rtg_ptr;
7133 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7134 	struct scsi_target_port_group_descriptor *tpg_desc;
7135 
7136 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7137 
7138 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7139 	retval = CTL_RETVAL_COMPLETE;
7140 
7141 	switch (cdb->byte2 & STG_PDF_MASK) {
7142 	case STG_PDF_LENGTH:
7143 		ext = 0;
7144 		break;
7145 	case STG_PDF_EXTENDED:
7146 		ext = 1;
7147 		break;
7148 	default:
7149 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7150 				      /*sks_valid*/ 1,
7151 				      /*command*/ 1,
7152 				      /*field*/ 2,
7153 				      /*bit_valid*/ 1,
7154 				      /*bit*/ 5);
7155 		ctl_done((union ctl_io *)ctsio);
7156 		return(retval);
7157 	}
7158 
7159 	num_target_ports = 0;
7160 	shared_group = (softc->is_single != 0);
7161 	mtx_lock(&softc->ctl_lock);
7162 	STAILQ_FOREACH(port, &softc->port_list, links) {
7163 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7164 			continue;
7165 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7166 			continue;
7167 		num_target_ports++;
7168 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7169 			shared_group = 1;
7170 	}
7171 	mtx_unlock(&softc->ctl_lock);
7172 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7173 
7174 	if (ext)
7175 		total_len = sizeof(struct scsi_target_group_data_extended);
7176 	else
7177 		total_len = sizeof(struct scsi_target_group_data);
7178 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7179 		(shared_group + num_ha_groups) +
7180 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7181 
7182 	alloc_len = scsi_4btoul(cdb->length);
7183 
7184 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7185 
7186 	ctsio->kern_sg_entries = 0;
7187 
7188 	if (total_len < alloc_len) {
7189 		ctsio->residual = alloc_len - total_len;
7190 		ctsio->kern_data_len = total_len;
7191 		ctsio->kern_total_len = total_len;
7192 	} else {
7193 		ctsio->residual = 0;
7194 		ctsio->kern_data_len = alloc_len;
7195 		ctsio->kern_total_len = alloc_len;
7196 	}
7197 	ctsio->kern_rel_offset = 0;
7198 
7199 	if (ext) {
7200 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7201 		    ctsio->kern_data_ptr;
7202 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7203 		rtg_ext_ptr->format_type = 0x10;
7204 		rtg_ext_ptr->implicit_transition_time = 0;
7205 		tpg_desc = &rtg_ext_ptr->groups[0];
7206 	} else {
7207 		rtg_ptr = (struct scsi_target_group_data *)
7208 		    ctsio->kern_data_ptr;
7209 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7210 		tpg_desc = &rtg_ptr->groups[0];
7211 	}
7212 
7213 	mtx_lock(&softc->ctl_lock);
7214 	pg = softc->port_min / softc->port_cnt;
7215 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7216 		/* Some shelf is known to be primary. */
7217 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7218 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7219 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7220 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7221 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7222 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7223 		else
7224 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7225 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7226 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7227 		} else {
7228 			ts = os;
7229 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7230 		}
7231 	} else {
7232 		/* No known primary shelf. */
7233 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7234 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7235 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7236 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7237 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7238 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7239 		} else {
7240 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7241 		}
7242 	}
7243 	if (shared_group) {
7244 		tpg_desc->pref_state = ts;
7245 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7246 		    TPG_U_SUP | TPG_T_SUP;
7247 		scsi_ulto2b(1, tpg_desc->target_port_group);
7248 		tpg_desc->status = TPG_IMPLICIT;
7249 		pc = 0;
7250 		STAILQ_FOREACH(port, &softc->port_list, links) {
7251 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7252 				continue;
7253 			if (!softc->is_single &&
7254 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7255 				continue;
7256 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7257 				continue;
7258 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7259 			    relative_target_port_identifier);
7260 			pc++;
7261 		}
7262 		tpg_desc->target_port_count = pc;
7263 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7264 		    &tpg_desc->descriptors[pc];
7265 	}
7266 	for (g = 0; g < num_ha_groups; g++) {
7267 		tpg_desc->pref_state = (g == pg) ? ts : os;
7268 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7269 		    TPG_U_SUP | TPG_T_SUP;
7270 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7271 		tpg_desc->status = TPG_IMPLICIT;
7272 		pc = 0;
7273 		STAILQ_FOREACH(port, &softc->port_list, links) {
7274 			if (port->targ_port < g * softc->port_cnt ||
7275 			    port->targ_port >= (g + 1) * softc->port_cnt)
7276 				continue;
7277 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7278 				continue;
7279 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7280 				continue;
7281 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7282 				continue;
7283 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7284 			    relative_target_port_identifier);
7285 			pc++;
7286 		}
7287 		tpg_desc->target_port_count = pc;
7288 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7289 		    &tpg_desc->descriptors[pc];
7290 	}
7291 	mtx_unlock(&softc->ctl_lock);
7292 
7293 	ctl_set_success(ctsio);
7294 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7295 	ctsio->be_move_done = ctl_config_move_done;
7296 	ctl_datamove((union ctl_io *)ctsio);
7297 	return(retval);
7298 }
7299 
7300 int
7301 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7302 {
7303 	struct ctl_lun *lun = CTL_LUN(ctsio);
7304 	struct scsi_report_supported_opcodes *cdb;
7305 	const struct ctl_cmd_entry *entry, *sentry;
7306 	struct scsi_report_supported_opcodes_all *all;
7307 	struct scsi_report_supported_opcodes_descr *descr;
7308 	struct scsi_report_supported_opcodes_one *one;
7309 	int retval;
7310 	int alloc_len, total_len;
7311 	int opcode, service_action, i, j, num;
7312 
7313 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7314 
7315 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7316 	retval = CTL_RETVAL_COMPLETE;
7317 
7318 	opcode = cdb->requested_opcode;
7319 	service_action = scsi_2btoul(cdb->requested_service_action);
7320 	switch (cdb->options & RSO_OPTIONS_MASK) {
7321 	case RSO_OPTIONS_ALL:
7322 		num = 0;
7323 		for (i = 0; i < 256; i++) {
7324 			entry = &ctl_cmd_table[i];
7325 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7326 				for (j = 0; j < 32; j++) {
7327 					sentry = &((const struct ctl_cmd_entry *)
7328 					    entry->execute)[j];
7329 					if (ctl_cmd_applicable(
7330 					    lun->be_lun->lun_type, sentry))
7331 						num++;
7332 				}
7333 			} else {
7334 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7335 				    entry))
7336 					num++;
7337 			}
7338 		}
7339 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7340 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7341 		break;
7342 	case RSO_OPTIONS_OC:
7343 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7344 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7345 					      /*sks_valid*/ 1,
7346 					      /*command*/ 1,
7347 					      /*field*/ 2,
7348 					      /*bit_valid*/ 1,
7349 					      /*bit*/ 2);
7350 			ctl_done((union ctl_io *)ctsio);
7351 			return (CTL_RETVAL_COMPLETE);
7352 		}
7353 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7354 		break;
7355 	case RSO_OPTIONS_OC_SA:
7356 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7357 		    service_action >= 32) {
7358 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7359 					      /*sks_valid*/ 1,
7360 					      /*command*/ 1,
7361 					      /*field*/ 2,
7362 					      /*bit_valid*/ 1,
7363 					      /*bit*/ 2);
7364 			ctl_done((union ctl_io *)ctsio);
7365 			return (CTL_RETVAL_COMPLETE);
7366 		}
7367 		/* FALLTHROUGH */
7368 	case RSO_OPTIONS_OC_ASA:
7369 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7370 		break;
7371 	default:
7372 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7373 				      /*sks_valid*/ 1,
7374 				      /*command*/ 1,
7375 				      /*field*/ 2,
7376 				      /*bit_valid*/ 1,
7377 				      /*bit*/ 2);
7378 		ctl_done((union ctl_io *)ctsio);
7379 		return (CTL_RETVAL_COMPLETE);
7380 	}
7381 
7382 	alloc_len = scsi_4btoul(cdb->length);
7383 
7384 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7385 
7386 	ctsio->kern_sg_entries = 0;
7387 
7388 	if (total_len < alloc_len) {
7389 		ctsio->residual = alloc_len - total_len;
7390 		ctsio->kern_data_len = total_len;
7391 		ctsio->kern_total_len = total_len;
7392 	} else {
7393 		ctsio->residual = 0;
7394 		ctsio->kern_data_len = alloc_len;
7395 		ctsio->kern_total_len = alloc_len;
7396 	}
7397 	ctsio->kern_rel_offset = 0;
7398 
7399 	switch (cdb->options & RSO_OPTIONS_MASK) {
7400 	case RSO_OPTIONS_ALL:
7401 		all = (struct scsi_report_supported_opcodes_all *)
7402 		    ctsio->kern_data_ptr;
7403 		num = 0;
7404 		for (i = 0; i < 256; i++) {
7405 			entry = &ctl_cmd_table[i];
7406 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7407 				for (j = 0; j < 32; j++) {
7408 					sentry = &((const struct ctl_cmd_entry *)
7409 					    entry->execute)[j];
7410 					if (!ctl_cmd_applicable(
7411 					    lun->be_lun->lun_type, sentry))
7412 						continue;
7413 					descr = &all->descr[num++];
7414 					descr->opcode = i;
7415 					scsi_ulto2b(j, descr->service_action);
7416 					descr->flags = RSO_SERVACTV;
7417 					scsi_ulto2b(sentry->length,
7418 					    descr->cdb_length);
7419 				}
7420 			} else {
7421 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7422 				    entry))
7423 					continue;
7424 				descr = &all->descr[num++];
7425 				descr->opcode = i;
7426 				scsi_ulto2b(0, descr->service_action);
7427 				descr->flags = 0;
7428 				scsi_ulto2b(entry->length, descr->cdb_length);
7429 			}
7430 		}
7431 		scsi_ulto4b(
7432 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7433 		    all->length);
7434 		break;
7435 	case RSO_OPTIONS_OC:
7436 		one = (struct scsi_report_supported_opcodes_one *)
7437 		    ctsio->kern_data_ptr;
7438 		entry = &ctl_cmd_table[opcode];
7439 		goto fill_one;
7440 	case RSO_OPTIONS_OC_SA:
7441 		one = (struct scsi_report_supported_opcodes_one *)
7442 		    ctsio->kern_data_ptr;
7443 		entry = &ctl_cmd_table[opcode];
7444 		entry = &((const struct ctl_cmd_entry *)
7445 		    entry->execute)[service_action];
7446 fill_one:
7447 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7448 			one->support = 3;
7449 			scsi_ulto2b(entry->length, one->cdb_length);
7450 			one->cdb_usage[0] = opcode;
7451 			memcpy(&one->cdb_usage[1], entry->usage,
7452 			    entry->length - 1);
7453 		} else
7454 			one->support = 1;
7455 		break;
7456 	case RSO_OPTIONS_OC_ASA:
7457 		one = (struct scsi_report_supported_opcodes_one *)
7458 		    ctsio->kern_data_ptr;
7459 		entry = &ctl_cmd_table[opcode];
7460 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7461 			entry = &((const struct ctl_cmd_entry *)
7462 			    entry->execute)[service_action];
7463 		} else if (service_action != 0) {
7464 			one->support = 1;
7465 			break;
7466 		}
7467 		goto fill_one;
7468 	}
7469 
7470 	ctl_set_success(ctsio);
7471 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7472 	ctsio->be_move_done = ctl_config_move_done;
7473 	ctl_datamove((union ctl_io *)ctsio);
7474 	return(retval);
7475 }
7476 
7477 int
7478 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7479 {
7480 	struct scsi_report_supported_tmf *cdb;
7481 	struct scsi_report_supported_tmf_ext_data *data;
7482 	int retval;
7483 	int alloc_len, total_len;
7484 
7485 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7486 
7487 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7488 
7489 	retval = CTL_RETVAL_COMPLETE;
7490 
7491 	if (cdb->options & RST_REPD)
7492 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7493 	else
7494 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7495 	alloc_len = scsi_4btoul(cdb->length);
7496 
7497 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7498 
7499 	ctsio->kern_sg_entries = 0;
7500 
7501 	if (total_len < alloc_len) {
7502 		ctsio->residual = alloc_len - total_len;
7503 		ctsio->kern_data_len = total_len;
7504 		ctsio->kern_total_len = total_len;
7505 	} else {
7506 		ctsio->residual = 0;
7507 		ctsio->kern_data_len = alloc_len;
7508 		ctsio->kern_total_len = alloc_len;
7509 	}
7510 	ctsio->kern_rel_offset = 0;
7511 
7512 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7513 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7514 	    RST_TRS;
7515 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7516 	data->length = total_len - 4;
7517 
7518 	ctl_set_success(ctsio);
7519 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7520 	ctsio->be_move_done = ctl_config_move_done;
7521 	ctl_datamove((union ctl_io *)ctsio);
7522 	return (retval);
7523 }
7524 
7525 int
7526 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7527 {
7528 	struct scsi_report_timestamp *cdb;
7529 	struct scsi_report_timestamp_data *data;
7530 	struct timeval tv;
7531 	int64_t timestamp;
7532 	int retval;
7533 	int alloc_len, total_len;
7534 
7535 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7536 
7537 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7538 
7539 	retval = CTL_RETVAL_COMPLETE;
7540 
7541 	total_len = sizeof(struct scsi_report_timestamp_data);
7542 	alloc_len = scsi_4btoul(cdb->length);
7543 
7544 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7545 
7546 	ctsio->kern_sg_entries = 0;
7547 
7548 	if (total_len < alloc_len) {
7549 		ctsio->residual = alloc_len - total_len;
7550 		ctsio->kern_data_len = total_len;
7551 		ctsio->kern_total_len = total_len;
7552 	} else {
7553 		ctsio->residual = 0;
7554 		ctsio->kern_data_len = alloc_len;
7555 		ctsio->kern_total_len = alloc_len;
7556 	}
7557 	ctsio->kern_rel_offset = 0;
7558 
7559 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7560 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7561 	data->origin = RTS_ORIG_OUTSIDE;
7562 	getmicrotime(&tv);
7563 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7564 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7565 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7566 
7567 	ctl_set_success(ctsio);
7568 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7569 	ctsio->be_move_done = ctl_config_move_done;
7570 	ctl_datamove((union ctl_io *)ctsio);
7571 	return (retval);
7572 }
7573 
7574 int
7575 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7576 {
7577 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7578 	struct ctl_lun *lun = CTL_LUN(ctsio);
7579 	struct scsi_per_res_in *cdb;
7580 	int alloc_len, total_len = 0;
7581 	/* struct scsi_per_res_in_rsrv in_data; */
7582 	uint64_t key;
7583 
7584 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7585 
7586 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7587 
7588 	alloc_len = scsi_2btoul(cdb->length);
7589 
7590 retry:
7591 	mtx_lock(&lun->lun_lock);
7592 	switch (cdb->action) {
7593 	case SPRI_RK: /* read keys */
7594 		total_len = sizeof(struct scsi_per_res_in_keys) +
7595 			lun->pr_key_count *
7596 			sizeof(struct scsi_per_res_key);
7597 		break;
7598 	case SPRI_RR: /* read reservation */
7599 		if (lun->flags & CTL_LUN_PR_RESERVED)
7600 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7601 		else
7602 			total_len = sizeof(struct scsi_per_res_in_header);
7603 		break;
7604 	case SPRI_RC: /* report capabilities */
7605 		total_len = sizeof(struct scsi_per_res_cap);
7606 		break;
7607 	case SPRI_RS: /* read full status */
7608 		total_len = sizeof(struct scsi_per_res_in_header) +
7609 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7610 		    lun->pr_key_count;
7611 		break;
7612 	default:
7613 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7614 	}
7615 	mtx_unlock(&lun->lun_lock);
7616 
7617 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7618 
7619 	if (total_len < alloc_len) {
7620 		ctsio->residual = alloc_len - total_len;
7621 		ctsio->kern_data_len = total_len;
7622 		ctsio->kern_total_len = total_len;
7623 	} else {
7624 		ctsio->residual = 0;
7625 		ctsio->kern_data_len = alloc_len;
7626 		ctsio->kern_total_len = alloc_len;
7627 	}
7628 
7629 	ctsio->kern_rel_offset = 0;
7630 	ctsio->kern_sg_entries = 0;
7631 
7632 	mtx_lock(&lun->lun_lock);
7633 	switch (cdb->action) {
7634 	case SPRI_RK: { // read keys
7635         struct scsi_per_res_in_keys *res_keys;
7636 		int i, key_count;
7637 
7638 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7639 
7640 		/*
7641 		 * We had to drop the lock to allocate our buffer, which
7642 		 * leaves time for someone to come in with another
7643 		 * persistent reservation.  (That is unlikely, though,
7644 		 * since this should be the only persistent reservation
7645 		 * command active right now.)
7646 		 */
7647 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7648 		    (lun->pr_key_count *
7649 		     sizeof(struct scsi_per_res_key)))){
7650 			mtx_unlock(&lun->lun_lock);
7651 			free(ctsio->kern_data_ptr, M_CTL);
7652 			printf("%s: reservation length changed, retrying\n",
7653 			       __func__);
7654 			goto retry;
7655 		}
7656 
7657 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7658 
7659 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7660 			     lun->pr_key_count, res_keys->header.length);
7661 
7662 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7663 			if ((key = ctl_get_prkey(lun, i)) == 0)
7664 				continue;
7665 
7666 			/*
7667 			 * We used lun->pr_key_count to calculate the
7668 			 * size to allocate.  If it turns out the number of
7669 			 * initiators with the registered flag set is
7670 			 * larger than that (i.e. they haven't been kept in
7671 			 * sync), we've got a problem.
7672 			 */
7673 			if (key_count >= lun->pr_key_count) {
7674 				key_count++;
7675 				continue;
7676 			}
7677 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7678 			key_count++;
7679 		}
7680 		break;
7681 	}
7682 	case SPRI_RR: { // read reservation
7683 		struct scsi_per_res_in_rsrv *res;
7684 		int tmp_len, header_only;
7685 
7686 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7687 
7688 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7689 
7690 		if (lun->flags & CTL_LUN_PR_RESERVED)
7691 		{
7692 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7693 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7694 				    res->header.length);
7695 			header_only = 0;
7696 		} else {
7697 			tmp_len = sizeof(struct scsi_per_res_in_header);
7698 			scsi_ulto4b(0, res->header.length);
7699 			header_only = 1;
7700 		}
7701 
7702 		/*
7703 		 * We had to drop the lock to allocate our buffer, which
7704 		 * leaves time for someone to come in with another
7705 		 * persistent reservation.  (That is unlikely, though,
7706 		 * since this should be the only persistent reservation
7707 		 * command active right now.)
7708 		 */
7709 		if (tmp_len != total_len) {
7710 			mtx_unlock(&lun->lun_lock);
7711 			free(ctsio->kern_data_ptr, M_CTL);
7712 			printf("%s: reservation status changed, retrying\n",
7713 			       __func__);
7714 			goto retry;
7715 		}
7716 
7717 		/*
7718 		 * No reservation held, so we're done.
7719 		 */
7720 		if (header_only != 0)
7721 			break;
7722 
7723 		/*
7724 		 * If the registration is an All Registrants type, the key
7725 		 * is 0, since it doesn't really matter.
7726 		 */
7727 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7728 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7729 			    res->data.reservation);
7730 		}
7731 		res->data.scopetype = lun->pr_res_type;
7732 		break;
7733 	}
7734 	case SPRI_RC:     //report capabilities
7735 	{
7736 		struct scsi_per_res_cap *res_cap;
7737 		uint16_t type_mask;
7738 
7739 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7740 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7741 		res_cap->flags1 = SPRI_CRH;
7742 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7743 		type_mask = SPRI_TM_WR_EX_AR |
7744 			    SPRI_TM_EX_AC_RO |
7745 			    SPRI_TM_WR_EX_RO |
7746 			    SPRI_TM_EX_AC |
7747 			    SPRI_TM_WR_EX |
7748 			    SPRI_TM_EX_AC_AR;
7749 		scsi_ulto2b(type_mask, res_cap->type_mask);
7750 		break;
7751 	}
7752 	case SPRI_RS: { // read full status
7753 		struct scsi_per_res_in_full *res_status;
7754 		struct scsi_per_res_in_full_desc *res_desc;
7755 		struct ctl_port *port;
7756 		int i, len;
7757 
7758 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7759 
7760 		/*
7761 		 * We had to drop the lock to allocate our buffer, which
7762 		 * leaves time for someone to come in with another
7763 		 * persistent reservation.  (That is unlikely, though,
7764 		 * since this should be the only persistent reservation
7765 		 * command active right now.)
7766 		 */
7767 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7768 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7769 		     lun->pr_key_count)){
7770 			mtx_unlock(&lun->lun_lock);
7771 			free(ctsio->kern_data_ptr, M_CTL);
7772 			printf("%s: reservation length changed, retrying\n",
7773 			       __func__);
7774 			goto retry;
7775 		}
7776 
7777 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7778 
7779 		res_desc = &res_status->desc[0];
7780 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7781 			if ((key = ctl_get_prkey(lun, i)) == 0)
7782 				continue;
7783 
7784 			scsi_u64to8b(key, res_desc->res_key.key);
7785 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7786 			    (lun->pr_res_idx == i ||
7787 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7788 				res_desc->flags = SPRI_FULL_R_HOLDER;
7789 				res_desc->scopetype = lun->pr_res_type;
7790 			}
7791 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7792 			    res_desc->rel_trgt_port_id);
7793 			len = 0;
7794 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7795 			if (port != NULL)
7796 				len = ctl_create_iid(port,
7797 				    i % CTL_MAX_INIT_PER_PORT,
7798 				    res_desc->transport_id);
7799 			scsi_ulto4b(len, res_desc->additional_length);
7800 			res_desc = (struct scsi_per_res_in_full_desc *)
7801 			    &res_desc->transport_id[len];
7802 		}
7803 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7804 		    res_status->header.length);
7805 		break;
7806 	}
7807 	default:
7808 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7809 	}
7810 	mtx_unlock(&lun->lun_lock);
7811 
7812 	ctl_set_success(ctsio);
7813 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7814 	ctsio->be_move_done = ctl_config_move_done;
7815 	ctl_datamove((union ctl_io *)ctsio);
7816 	return (CTL_RETVAL_COMPLETE);
7817 }
7818 
7819 /*
7820  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7821  * it should return.
7822  */
7823 static int
7824 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7825 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7826 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7827 		struct scsi_per_res_out_parms* param)
7828 {
7829 	union ctl_ha_msg persis_io;
7830 	int i;
7831 
7832 	mtx_lock(&lun->lun_lock);
7833 	if (sa_res_key == 0) {
7834 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7835 			/* validate scope and type */
7836 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7837 			     SPR_LU_SCOPE) {
7838 				mtx_unlock(&lun->lun_lock);
7839 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7840 						      /*sks_valid*/ 1,
7841 						      /*command*/ 1,
7842 						      /*field*/ 2,
7843 						      /*bit_valid*/ 1,
7844 						      /*bit*/ 4);
7845 				ctl_done((union ctl_io *)ctsio);
7846 				return (1);
7847 			}
7848 
7849 		        if (type>8 || type==2 || type==4 || type==0) {
7850 				mtx_unlock(&lun->lun_lock);
7851 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7852        	           				      /*sks_valid*/ 1,
7853 						      /*command*/ 1,
7854 						      /*field*/ 2,
7855 						      /*bit_valid*/ 1,
7856 						      /*bit*/ 0);
7857 				ctl_done((union ctl_io *)ctsio);
7858 				return (1);
7859 		        }
7860 
7861 			/*
7862 			 * Unregister everybody else and build UA for
7863 			 * them
7864 			 */
7865 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7866 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7867 					continue;
7868 
7869 				ctl_clr_prkey(lun, i);
7870 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7871 			}
7872 			lun->pr_key_count = 1;
7873 			lun->pr_res_type = type;
7874 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7875 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7876 				lun->pr_res_idx = residx;
7877 			lun->pr_generation++;
7878 			mtx_unlock(&lun->lun_lock);
7879 
7880 			/* send msg to other side */
7881 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7882 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7883 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7884 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7885 			persis_io.pr.pr_info.res_type = type;
7886 			memcpy(persis_io.pr.pr_info.sa_res_key,
7887 			       param->serv_act_res_key,
7888 			       sizeof(param->serv_act_res_key));
7889 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7890 			    sizeof(persis_io.pr), M_WAITOK);
7891 		} else {
7892 			/* not all registrants */
7893 			mtx_unlock(&lun->lun_lock);
7894 			free(ctsio->kern_data_ptr, M_CTL);
7895 			ctl_set_invalid_field(ctsio,
7896 					      /*sks_valid*/ 1,
7897 					      /*command*/ 0,
7898 					      /*field*/ 8,
7899 					      /*bit_valid*/ 0,
7900 					      /*bit*/ 0);
7901 			ctl_done((union ctl_io *)ctsio);
7902 			return (1);
7903 		}
7904 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7905 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7906 		int found = 0;
7907 
7908 		if (res_key == sa_res_key) {
7909 			/* special case */
7910 			/*
7911 			 * The spec implies this is not good but doesn't
7912 			 * say what to do. There are two choices either
7913 			 * generate a res conflict or check condition
7914 			 * with illegal field in parameter data. Since
7915 			 * that is what is done when the sa_res_key is
7916 			 * zero I'll take that approach since this has
7917 			 * to do with the sa_res_key.
7918 			 */
7919 			mtx_unlock(&lun->lun_lock);
7920 			free(ctsio->kern_data_ptr, M_CTL);
7921 			ctl_set_invalid_field(ctsio,
7922 					      /*sks_valid*/ 1,
7923 					      /*command*/ 0,
7924 					      /*field*/ 8,
7925 					      /*bit_valid*/ 0,
7926 					      /*bit*/ 0);
7927 			ctl_done((union ctl_io *)ctsio);
7928 			return (1);
7929 		}
7930 
7931 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7932 			if (ctl_get_prkey(lun, i) != sa_res_key)
7933 				continue;
7934 
7935 			found = 1;
7936 			ctl_clr_prkey(lun, i);
7937 			lun->pr_key_count--;
7938 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7939 		}
7940 		if (!found) {
7941 			mtx_unlock(&lun->lun_lock);
7942 			free(ctsio->kern_data_ptr, M_CTL);
7943 			ctl_set_reservation_conflict(ctsio);
7944 			ctl_done((union ctl_io *)ctsio);
7945 			return (CTL_RETVAL_COMPLETE);
7946 		}
7947 		lun->pr_generation++;
7948 		mtx_unlock(&lun->lun_lock);
7949 
7950 		/* send msg to other side */
7951 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7952 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7953 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7954 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7955 		persis_io.pr.pr_info.res_type = type;
7956 		memcpy(persis_io.pr.pr_info.sa_res_key,
7957 		       param->serv_act_res_key,
7958 		       sizeof(param->serv_act_res_key));
7959 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7960 		    sizeof(persis_io.pr), M_WAITOK);
7961 	} else {
7962 		/* Reserved but not all registrants */
7963 		/* sa_res_key is res holder */
7964 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7965 			/* validate scope and type */
7966 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7967 			     SPR_LU_SCOPE) {
7968 				mtx_unlock(&lun->lun_lock);
7969 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7970 						      /*sks_valid*/ 1,
7971 						      /*command*/ 1,
7972 						      /*field*/ 2,
7973 						      /*bit_valid*/ 1,
7974 						      /*bit*/ 4);
7975 				ctl_done((union ctl_io *)ctsio);
7976 				return (1);
7977 			}
7978 
7979 			if (type>8 || type==2 || type==4 || type==0) {
7980 				mtx_unlock(&lun->lun_lock);
7981 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7982 						      /*sks_valid*/ 1,
7983 						      /*command*/ 1,
7984 						      /*field*/ 2,
7985 						      /*bit_valid*/ 1,
7986 						      /*bit*/ 0);
7987 				ctl_done((union ctl_io *)ctsio);
7988 				return (1);
7989 			}
7990 
7991 			/*
7992 			 * Do the following:
7993 			 * if sa_res_key != res_key remove all
7994 			 * registrants w/sa_res_key and generate UA
7995 			 * for these registrants(Registrations
7996 			 * Preempted) if it wasn't an exclusive
7997 			 * reservation generate UA(Reservations
7998 			 * Preempted) for all other registered nexuses
7999 			 * if the type has changed. Establish the new
8000 			 * reservation and holder. If res_key and
8001 			 * sa_res_key are the same do the above
8002 			 * except don't unregister the res holder.
8003 			 */
8004 
8005 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8006 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8007 					continue;
8008 
8009 				if (sa_res_key == ctl_get_prkey(lun, i)) {
8010 					ctl_clr_prkey(lun, i);
8011 					lun->pr_key_count--;
8012 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8013 				} else if (type != lun->pr_res_type &&
8014 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8015 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8016 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8017 				}
8018 			}
8019 			lun->pr_res_type = type;
8020 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8021 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8022 				lun->pr_res_idx = residx;
8023 			else
8024 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8025 			lun->pr_generation++;
8026 			mtx_unlock(&lun->lun_lock);
8027 
8028 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8029 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8030 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8031 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8032 			persis_io.pr.pr_info.res_type = type;
8033 			memcpy(persis_io.pr.pr_info.sa_res_key,
8034 			       param->serv_act_res_key,
8035 			       sizeof(param->serv_act_res_key));
8036 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8037 			    sizeof(persis_io.pr), M_WAITOK);
8038 		} else {
8039 			/*
8040 			 * sa_res_key is not the res holder just
8041 			 * remove registrants
8042 			 */
8043 			int found=0;
8044 
8045 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8046 				if (sa_res_key != ctl_get_prkey(lun, i))
8047 					continue;
8048 
8049 				found = 1;
8050 				ctl_clr_prkey(lun, i);
8051 				lun->pr_key_count--;
8052 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8053 			}
8054 
8055 			if (!found) {
8056 				mtx_unlock(&lun->lun_lock);
8057 				free(ctsio->kern_data_ptr, M_CTL);
8058 				ctl_set_reservation_conflict(ctsio);
8059 				ctl_done((union ctl_io *)ctsio);
8060 		        	return (1);
8061 			}
8062 			lun->pr_generation++;
8063 			mtx_unlock(&lun->lun_lock);
8064 
8065 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8066 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8067 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8068 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8069 			persis_io.pr.pr_info.res_type = type;
8070 			memcpy(persis_io.pr.pr_info.sa_res_key,
8071 			       param->serv_act_res_key,
8072 			       sizeof(param->serv_act_res_key));
8073 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8074 			    sizeof(persis_io.pr), M_WAITOK);
8075 		}
8076 	}
8077 	return (0);
8078 }
8079 
8080 static void
8081 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8082 {
8083 	uint64_t sa_res_key;
8084 	int i;
8085 
8086 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8087 
8088 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8089 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8090 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8091 		if (sa_res_key == 0) {
8092 			/*
8093 			 * Unregister everybody else and build UA for
8094 			 * them
8095 			 */
8096 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8097 				if (i == msg->pr.pr_info.residx ||
8098 				    ctl_get_prkey(lun, i) == 0)
8099 					continue;
8100 
8101 				ctl_clr_prkey(lun, i);
8102 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8103 			}
8104 
8105 			lun->pr_key_count = 1;
8106 			lun->pr_res_type = msg->pr.pr_info.res_type;
8107 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8108 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8109 				lun->pr_res_idx = msg->pr.pr_info.residx;
8110 		} else {
8111 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8112 				if (sa_res_key == ctl_get_prkey(lun, i))
8113 					continue;
8114 
8115 				ctl_clr_prkey(lun, i);
8116 				lun->pr_key_count--;
8117 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8118 			}
8119 		}
8120 	} else {
8121 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8122 			if (i == msg->pr.pr_info.residx ||
8123 			    ctl_get_prkey(lun, i) == 0)
8124 				continue;
8125 
8126 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8127 				ctl_clr_prkey(lun, i);
8128 				lun->pr_key_count--;
8129 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8130 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8131 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8132 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8133 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8134 			}
8135 		}
8136 		lun->pr_res_type = msg->pr.pr_info.res_type;
8137 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8138 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8139 			lun->pr_res_idx = msg->pr.pr_info.residx;
8140 		else
8141 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8142 	}
8143 	lun->pr_generation++;
8144 
8145 }
8146 
8147 
8148 int
8149 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8150 {
8151 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8152 	struct ctl_lun *lun = CTL_LUN(ctsio);
8153 	int retval;
8154 	u_int32_t param_len;
8155 	struct scsi_per_res_out *cdb;
8156 	struct scsi_per_res_out_parms* param;
8157 	uint32_t residx;
8158 	uint64_t res_key, sa_res_key, key;
8159 	uint8_t type;
8160 	union ctl_ha_msg persis_io;
8161 	int    i;
8162 
8163 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8164 
8165 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8166 	retval = CTL_RETVAL_COMPLETE;
8167 
8168 	/*
8169 	 * We only support whole-LUN scope.  The scope & type are ignored for
8170 	 * register, register and ignore existing key and clear.
8171 	 * We sometimes ignore scope and type on preempts too!!
8172 	 * Verify reservation type here as well.
8173 	 */
8174 	type = cdb->scope_type & SPR_TYPE_MASK;
8175 	if ((cdb->action == SPRO_RESERVE)
8176 	 || (cdb->action == SPRO_RELEASE)) {
8177 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8178 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8179 					      /*sks_valid*/ 1,
8180 					      /*command*/ 1,
8181 					      /*field*/ 2,
8182 					      /*bit_valid*/ 1,
8183 					      /*bit*/ 4);
8184 			ctl_done((union ctl_io *)ctsio);
8185 			return (CTL_RETVAL_COMPLETE);
8186 		}
8187 
8188 		if (type>8 || type==2 || type==4 || type==0) {
8189 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8190 					      /*sks_valid*/ 1,
8191 					      /*command*/ 1,
8192 					      /*field*/ 2,
8193 					      /*bit_valid*/ 1,
8194 					      /*bit*/ 0);
8195 			ctl_done((union ctl_io *)ctsio);
8196 			return (CTL_RETVAL_COMPLETE);
8197 		}
8198 	}
8199 
8200 	param_len = scsi_4btoul(cdb->length);
8201 
8202 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8203 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8204 		ctsio->kern_data_len = param_len;
8205 		ctsio->kern_total_len = param_len;
8206 		ctsio->kern_rel_offset = 0;
8207 		ctsio->kern_sg_entries = 0;
8208 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8209 		ctsio->be_move_done = ctl_config_move_done;
8210 		ctl_datamove((union ctl_io *)ctsio);
8211 
8212 		return (CTL_RETVAL_COMPLETE);
8213 	}
8214 
8215 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8216 
8217 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8218 	res_key = scsi_8btou64(param->res_key.key);
8219 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8220 
8221 	/*
8222 	 * Validate the reservation key here except for SPRO_REG_IGNO
8223 	 * This must be done for all other service actions
8224 	 */
8225 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8226 		mtx_lock(&lun->lun_lock);
8227 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8228 			if (res_key != key) {
8229 				/*
8230 				 * The current key passed in doesn't match
8231 				 * the one the initiator previously
8232 				 * registered.
8233 				 */
8234 				mtx_unlock(&lun->lun_lock);
8235 				free(ctsio->kern_data_ptr, M_CTL);
8236 				ctl_set_reservation_conflict(ctsio);
8237 				ctl_done((union ctl_io *)ctsio);
8238 				return (CTL_RETVAL_COMPLETE);
8239 			}
8240 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8241 			/*
8242 			 * We are not registered
8243 			 */
8244 			mtx_unlock(&lun->lun_lock);
8245 			free(ctsio->kern_data_ptr, M_CTL);
8246 			ctl_set_reservation_conflict(ctsio);
8247 			ctl_done((union ctl_io *)ctsio);
8248 			return (CTL_RETVAL_COMPLETE);
8249 		} else if (res_key != 0) {
8250 			/*
8251 			 * We are not registered and trying to register but
8252 			 * the register key isn't zero.
8253 			 */
8254 			mtx_unlock(&lun->lun_lock);
8255 			free(ctsio->kern_data_ptr, M_CTL);
8256 			ctl_set_reservation_conflict(ctsio);
8257 			ctl_done((union ctl_io *)ctsio);
8258 			return (CTL_RETVAL_COMPLETE);
8259 		}
8260 		mtx_unlock(&lun->lun_lock);
8261 	}
8262 
8263 	switch (cdb->action & SPRO_ACTION_MASK) {
8264 	case SPRO_REGISTER:
8265 	case SPRO_REG_IGNO: {
8266 
8267 #if 0
8268 		printf("Registration received\n");
8269 #endif
8270 
8271 		/*
8272 		 * We don't support any of these options, as we report in
8273 		 * the read capabilities request (see
8274 		 * ctl_persistent_reserve_in(), above).
8275 		 */
8276 		if ((param->flags & SPR_SPEC_I_PT)
8277 		 || (param->flags & SPR_ALL_TG_PT)
8278 		 || (param->flags & SPR_APTPL)) {
8279 			int bit_ptr;
8280 
8281 			if (param->flags & SPR_APTPL)
8282 				bit_ptr = 0;
8283 			else if (param->flags & SPR_ALL_TG_PT)
8284 				bit_ptr = 2;
8285 			else /* SPR_SPEC_I_PT */
8286 				bit_ptr = 3;
8287 
8288 			free(ctsio->kern_data_ptr, M_CTL);
8289 			ctl_set_invalid_field(ctsio,
8290 					      /*sks_valid*/ 1,
8291 					      /*command*/ 0,
8292 					      /*field*/ 20,
8293 					      /*bit_valid*/ 1,
8294 					      /*bit*/ bit_ptr);
8295 			ctl_done((union ctl_io *)ctsio);
8296 			return (CTL_RETVAL_COMPLETE);
8297 		}
8298 
8299 		mtx_lock(&lun->lun_lock);
8300 
8301 		/*
8302 		 * The initiator wants to clear the
8303 		 * key/unregister.
8304 		 */
8305 		if (sa_res_key == 0) {
8306 			if ((res_key == 0
8307 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8308 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8309 			  && ctl_get_prkey(lun, residx) == 0)) {
8310 				mtx_unlock(&lun->lun_lock);
8311 				goto done;
8312 			}
8313 
8314 			ctl_clr_prkey(lun, residx);
8315 			lun->pr_key_count--;
8316 
8317 			if (residx == lun->pr_res_idx) {
8318 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8319 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8320 
8321 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8322 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8323 				    lun->pr_key_count) {
8324 					/*
8325 					 * If the reservation is a registrants
8326 					 * only type we need to generate a UA
8327 					 * for other registered inits.  The
8328 					 * sense code should be RESERVATIONS
8329 					 * RELEASED
8330 					 */
8331 
8332 					for (i = softc->init_min; i < softc->init_max; i++){
8333 						if (ctl_get_prkey(lun, i) == 0)
8334 							continue;
8335 						ctl_est_ua(lun, i,
8336 						    CTL_UA_RES_RELEASE);
8337 					}
8338 				}
8339 				lun->pr_res_type = 0;
8340 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8341 				if (lun->pr_key_count==0) {
8342 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8343 					lun->pr_res_type = 0;
8344 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8345 				}
8346 			}
8347 			lun->pr_generation++;
8348 			mtx_unlock(&lun->lun_lock);
8349 
8350 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8351 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8352 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8353 			persis_io.pr.pr_info.residx = residx;
8354 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8355 			    sizeof(persis_io.pr), M_WAITOK);
8356 		} else /* sa_res_key != 0 */ {
8357 
8358 			/*
8359 			 * If we aren't registered currently then increment
8360 			 * the key count and set the registered flag.
8361 			 */
8362 			ctl_alloc_prkey(lun, residx);
8363 			if (ctl_get_prkey(lun, residx) == 0)
8364 				lun->pr_key_count++;
8365 			ctl_set_prkey(lun, residx, sa_res_key);
8366 			lun->pr_generation++;
8367 			mtx_unlock(&lun->lun_lock);
8368 
8369 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8370 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8371 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8372 			persis_io.pr.pr_info.residx = residx;
8373 			memcpy(persis_io.pr.pr_info.sa_res_key,
8374 			       param->serv_act_res_key,
8375 			       sizeof(param->serv_act_res_key));
8376 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8377 			    sizeof(persis_io.pr), M_WAITOK);
8378 		}
8379 
8380 		break;
8381 	}
8382 	case SPRO_RESERVE:
8383 #if 0
8384                 printf("Reserve executed type %d\n", type);
8385 #endif
8386 		mtx_lock(&lun->lun_lock);
8387 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8388 			/*
8389 			 * if this isn't the reservation holder and it's
8390 			 * not a "all registrants" type or if the type is
8391 			 * different then we have a conflict
8392 			 */
8393 			if ((lun->pr_res_idx != residx
8394 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8395 			 || lun->pr_res_type != type) {
8396 				mtx_unlock(&lun->lun_lock);
8397 				free(ctsio->kern_data_ptr, M_CTL);
8398 				ctl_set_reservation_conflict(ctsio);
8399 				ctl_done((union ctl_io *)ctsio);
8400 				return (CTL_RETVAL_COMPLETE);
8401 			}
8402 			mtx_unlock(&lun->lun_lock);
8403 		} else /* create a reservation */ {
8404 			/*
8405 			 * If it's not an "all registrants" type record
8406 			 * reservation holder
8407 			 */
8408 			if (type != SPR_TYPE_WR_EX_AR
8409 			 && type != SPR_TYPE_EX_AC_AR)
8410 				lun->pr_res_idx = residx; /* Res holder */
8411 			else
8412 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8413 
8414 			lun->flags |= CTL_LUN_PR_RESERVED;
8415 			lun->pr_res_type = type;
8416 
8417 			mtx_unlock(&lun->lun_lock);
8418 
8419 			/* send msg to other side */
8420 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8421 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8422 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8423 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8424 			persis_io.pr.pr_info.res_type = type;
8425 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8426 			    sizeof(persis_io.pr), M_WAITOK);
8427 		}
8428 		break;
8429 
8430 	case SPRO_RELEASE:
8431 		mtx_lock(&lun->lun_lock);
8432 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8433 			/* No reservation exists return good status */
8434 			mtx_unlock(&lun->lun_lock);
8435 			goto done;
8436 		}
8437 		/*
8438 		 * Is this nexus a reservation holder?
8439 		 */
8440 		if (lun->pr_res_idx != residx
8441 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8442 			/*
8443 			 * not a res holder return good status but
8444 			 * do nothing
8445 			 */
8446 			mtx_unlock(&lun->lun_lock);
8447 			goto done;
8448 		}
8449 
8450 		if (lun->pr_res_type != type) {
8451 			mtx_unlock(&lun->lun_lock);
8452 			free(ctsio->kern_data_ptr, M_CTL);
8453 			ctl_set_illegal_pr_release(ctsio);
8454 			ctl_done((union ctl_io *)ctsio);
8455 			return (CTL_RETVAL_COMPLETE);
8456 		}
8457 
8458 		/* okay to release */
8459 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8460 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8461 		lun->pr_res_type = 0;
8462 
8463 		/*
8464 		 * If this isn't an exclusive access reservation and NUAR
8465 		 * is not set, generate UA for all other registrants.
8466 		 */
8467 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8468 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8469 			for (i = softc->init_min; i < softc->init_max; i++) {
8470 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8471 					continue;
8472 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8473 			}
8474 		}
8475 		mtx_unlock(&lun->lun_lock);
8476 
8477 		/* Send msg to other side */
8478 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8479 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8480 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8481 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8482 		     sizeof(persis_io.pr), M_WAITOK);
8483 		break;
8484 
8485 	case SPRO_CLEAR:
8486 		/* send msg to other side */
8487 
8488 		mtx_lock(&lun->lun_lock);
8489 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8490 		lun->pr_res_type = 0;
8491 		lun->pr_key_count = 0;
8492 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8493 
8494 		ctl_clr_prkey(lun, residx);
8495 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8496 			if (ctl_get_prkey(lun, i) != 0) {
8497 				ctl_clr_prkey(lun, i);
8498 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8499 			}
8500 		lun->pr_generation++;
8501 		mtx_unlock(&lun->lun_lock);
8502 
8503 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8504 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8505 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8506 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8507 		     sizeof(persis_io.pr), M_WAITOK);
8508 		break;
8509 
8510 	case SPRO_PREEMPT:
8511 	case SPRO_PRE_ABO: {
8512 		int nretval;
8513 
8514 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8515 					  residx, ctsio, cdb, param);
8516 		if (nretval != 0)
8517 			return (CTL_RETVAL_COMPLETE);
8518 		break;
8519 	}
8520 	default:
8521 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8522 	}
8523 
8524 done:
8525 	free(ctsio->kern_data_ptr, M_CTL);
8526 	ctl_set_success(ctsio);
8527 	ctl_done((union ctl_io *)ctsio);
8528 
8529 	return (retval);
8530 }
8531 
8532 /*
8533  * This routine is for handling a message from the other SC pertaining to
8534  * persistent reserve out. All the error checking will have been done
8535  * so only perorming the action need be done here to keep the two
8536  * in sync.
8537  */
8538 static void
8539 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8540 {
8541 	struct ctl_softc *softc = CTL_SOFTC(io);
8542 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8543 	struct ctl_lun *lun;
8544 	int i;
8545 	uint32_t residx, targ_lun;
8546 
8547 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8548 	mtx_lock(&softc->ctl_lock);
8549 	if (targ_lun >= CTL_MAX_LUNS ||
8550 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8551 		mtx_unlock(&softc->ctl_lock);
8552 		return;
8553 	}
8554 	mtx_lock(&lun->lun_lock);
8555 	mtx_unlock(&softc->ctl_lock);
8556 	if (lun->flags & CTL_LUN_DISABLED) {
8557 		mtx_unlock(&lun->lun_lock);
8558 		return;
8559 	}
8560 	residx = ctl_get_initindex(&msg->hdr.nexus);
8561 	switch(msg->pr.pr_info.action) {
8562 	case CTL_PR_REG_KEY:
8563 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8564 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8565 			lun->pr_key_count++;
8566 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8567 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8568 		lun->pr_generation++;
8569 		break;
8570 
8571 	case CTL_PR_UNREG_KEY:
8572 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8573 		lun->pr_key_count--;
8574 
8575 		/* XXX Need to see if the reservation has been released */
8576 		/* if so do we need to generate UA? */
8577 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8578 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8579 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8580 
8581 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8582 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8583 			    lun->pr_key_count) {
8584 				/*
8585 				 * If the reservation is a registrants
8586 				 * only type we need to generate a UA
8587 				 * for other registered inits.  The
8588 				 * sense code should be RESERVATIONS
8589 				 * RELEASED
8590 				 */
8591 
8592 				for (i = softc->init_min; i < softc->init_max; i++) {
8593 					if (ctl_get_prkey(lun, i) == 0)
8594 						continue;
8595 
8596 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8597 				}
8598 			}
8599 			lun->pr_res_type = 0;
8600 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8601 			if (lun->pr_key_count==0) {
8602 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8603 				lun->pr_res_type = 0;
8604 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8605 			}
8606 		}
8607 		lun->pr_generation++;
8608 		break;
8609 
8610 	case CTL_PR_RESERVE:
8611 		lun->flags |= CTL_LUN_PR_RESERVED;
8612 		lun->pr_res_type = msg->pr.pr_info.res_type;
8613 		lun->pr_res_idx = msg->pr.pr_info.residx;
8614 
8615 		break;
8616 
8617 	case CTL_PR_RELEASE:
8618 		/*
8619 		 * If this isn't an exclusive access reservation and NUAR
8620 		 * is not set, generate UA for all other registrants.
8621 		 */
8622 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8623 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8624 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8625 			for (i = softc->init_min; i < softc->init_max; i++)
8626 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8627 					continue;
8628 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8629 		}
8630 
8631 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8632 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8633 		lun->pr_res_type = 0;
8634 		break;
8635 
8636 	case CTL_PR_PREEMPT:
8637 		ctl_pro_preempt_other(lun, msg);
8638 		break;
8639 	case CTL_PR_CLEAR:
8640 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8641 		lun->pr_res_type = 0;
8642 		lun->pr_key_count = 0;
8643 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8644 
8645 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8646 			if (ctl_get_prkey(lun, i) == 0)
8647 				continue;
8648 			ctl_clr_prkey(lun, i);
8649 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8650 		}
8651 		lun->pr_generation++;
8652 		break;
8653 	}
8654 
8655 	mtx_unlock(&lun->lun_lock);
8656 }
8657 
8658 int
8659 ctl_read_write(struct ctl_scsiio *ctsio)
8660 {
8661 	struct ctl_lun *lun = CTL_LUN(ctsio);
8662 	struct ctl_lba_len_flags *lbalen;
8663 	uint64_t lba;
8664 	uint32_t num_blocks;
8665 	int flags, retval;
8666 	int isread;
8667 
8668 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8669 
8670 	flags = 0;
8671 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8672 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8673 	switch (ctsio->cdb[0]) {
8674 	case READ_6:
8675 	case WRITE_6: {
8676 		struct scsi_rw_6 *cdb;
8677 
8678 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8679 
8680 		lba = scsi_3btoul(cdb->addr);
8681 		/* only 5 bits are valid in the most significant address byte */
8682 		lba &= 0x1fffff;
8683 		num_blocks = cdb->length;
8684 		/*
8685 		 * This is correct according to SBC-2.
8686 		 */
8687 		if (num_blocks == 0)
8688 			num_blocks = 256;
8689 		break;
8690 	}
8691 	case READ_10:
8692 	case WRITE_10: {
8693 		struct scsi_rw_10 *cdb;
8694 
8695 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8696 		if (cdb->byte2 & SRW10_FUA)
8697 			flags |= CTL_LLF_FUA;
8698 		if (cdb->byte2 & SRW10_DPO)
8699 			flags |= CTL_LLF_DPO;
8700 		lba = scsi_4btoul(cdb->addr);
8701 		num_blocks = scsi_2btoul(cdb->length);
8702 		break;
8703 	}
8704 	case WRITE_VERIFY_10: {
8705 		struct scsi_write_verify_10 *cdb;
8706 
8707 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8708 		flags |= CTL_LLF_FUA;
8709 		if (cdb->byte2 & SWV_DPO)
8710 			flags |= CTL_LLF_DPO;
8711 		lba = scsi_4btoul(cdb->addr);
8712 		num_blocks = scsi_2btoul(cdb->length);
8713 		break;
8714 	}
8715 	case READ_12:
8716 	case WRITE_12: {
8717 		struct scsi_rw_12 *cdb;
8718 
8719 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8720 		if (cdb->byte2 & SRW12_FUA)
8721 			flags |= CTL_LLF_FUA;
8722 		if (cdb->byte2 & SRW12_DPO)
8723 			flags |= CTL_LLF_DPO;
8724 		lba = scsi_4btoul(cdb->addr);
8725 		num_blocks = scsi_4btoul(cdb->length);
8726 		break;
8727 	}
8728 	case WRITE_VERIFY_12: {
8729 		struct scsi_write_verify_12 *cdb;
8730 
8731 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8732 		flags |= CTL_LLF_FUA;
8733 		if (cdb->byte2 & SWV_DPO)
8734 			flags |= CTL_LLF_DPO;
8735 		lba = scsi_4btoul(cdb->addr);
8736 		num_blocks = scsi_4btoul(cdb->length);
8737 		break;
8738 	}
8739 	case READ_16:
8740 	case WRITE_16: {
8741 		struct scsi_rw_16 *cdb;
8742 
8743 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8744 		if (cdb->byte2 & SRW12_FUA)
8745 			flags |= CTL_LLF_FUA;
8746 		if (cdb->byte2 & SRW12_DPO)
8747 			flags |= CTL_LLF_DPO;
8748 		lba = scsi_8btou64(cdb->addr);
8749 		num_blocks = scsi_4btoul(cdb->length);
8750 		break;
8751 	}
8752 	case WRITE_ATOMIC_16: {
8753 		struct scsi_write_atomic_16 *cdb;
8754 
8755 		if (lun->be_lun->atomicblock == 0) {
8756 			ctl_set_invalid_opcode(ctsio);
8757 			ctl_done((union ctl_io *)ctsio);
8758 			return (CTL_RETVAL_COMPLETE);
8759 		}
8760 
8761 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8762 		if (cdb->byte2 & SRW12_FUA)
8763 			flags |= CTL_LLF_FUA;
8764 		if (cdb->byte2 & SRW12_DPO)
8765 			flags |= CTL_LLF_DPO;
8766 		lba = scsi_8btou64(cdb->addr);
8767 		num_blocks = scsi_2btoul(cdb->length);
8768 		if (num_blocks > lun->be_lun->atomicblock) {
8769 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8770 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8771 			    /*bit*/ 0);
8772 			ctl_done((union ctl_io *)ctsio);
8773 			return (CTL_RETVAL_COMPLETE);
8774 		}
8775 		break;
8776 	}
8777 	case WRITE_VERIFY_16: {
8778 		struct scsi_write_verify_16 *cdb;
8779 
8780 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8781 		flags |= CTL_LLF_FUA;
8782 		if (cdb->byte2 & SWV_DPO)
8783 			flags |= CTL_LLF_DPO;
8784 		lba = scsi_8btou64(cdb->addr);
8785 		num_blocks = scsi_4btoul(cdb->length);
8786 		break;
8787 	}
8788 	default:
8789 		/*
8790 		 * We got a command we don't support.  This shouldn't
8791 		 * happen, commands should be filtered out above us.
8792 		 */
8793 		ctl_set_invalid_opcode(ctsio);
8794 		ctl_done((union ctl_io *)ctsio);
8795 
8796 		return (CTL_RETVAL_COMPLETE);
8797 		break; /* NOTREACHED */
8798 	}
8799 
8800 	/*
8801 	 * The first check is to make sure we're in bounds, the second
8802 	 * check is to catch wrap-around problems.  If the lba + num blocks
8803 	 * is less than the lba, then we've wrapped around and the block
8804 	 * range is invalid anyway.
8805 	 */
8806 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8807 	 || ((lba + num_blocks) < lba)) {
8808 		ctl_set_lba_out_of_range(ctsio,
8809 		    MAX(lba, lun->be_lun->maxlba + 1));
8810 		ctl_done((union ctl_io *)ctsio);
8811 		return (CTL_RETVAL_COMPLETE);
8812 	}
8813 
8814 	/*
8815 	 * According to SBC-3, a transfer length of 0 is not an error.
8816 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8817 	 * translates to 256 blocks for those commands.
8818 	 */
8819 	if (num_blocks == 0) {
8820 		ctl_set_success(ctsio);
8821 		ctl_done((union ctl_io *)ctsio);
8822 		return (CTL_RETVAL_COMPLETE);
8823 	}
8824 
8825 	/* Set FUA and/or DPO if caches are disabled. */
8826 	if (isread) {
8827 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8828 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8829 	} else {
8830 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8831 			flags |= CTL_LLF_FUA;
8832 	}
8833 
8834 	lbalen = (struct ctl_lba_len_flags *)
8835 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8836 	lbalen->lba = lba;
8837 	lbalen->len = num_blocks;
8838 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8839 
8840 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8841 	ctsio->kern_rel_offset = 0;
8842 
8843 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8844 
8845 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8846 	return (retval);
8847 }
8848 
8849 static int
8850 ctl_cnw_cont(union ctl_io *io)
8851 {
8852 	struct ctl_lun *lun = CTL_LUN(io);
8853 	struct ctl_scsiio *ctsio;
8854 	struct ctl_lba_len_flags *lbalen;
8855 	int retval;
8856 
8857 	ctsio = &io->scsiio;
8858 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8859 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8860 	lbalen = (struct ctl_lba_len_flags *)
8861 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8862 	lbalen->flags &= ~CTL_LLF_COMPARE;
8863 	lbalen->flags |= CTL_LLF_WRITE;
8864 
8865 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8866 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8867 	return (retval);
8868 }
8869 
8870 int
8871 ctl_cnw(struct ctl_scsiio *ctsio)
8872 {
8873 	struct ctl_lun *lun = CTL_LUN(ctsio);
8874 	struct ctl_lba_len_flags *lbalen;
8875 	uint64_t lba;
8876 	uint32_t num_blocks;
8877 	int flags, retval;
8878 
8879 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8880 
8881 	flags = 0;
8882 	switch (ctsio->cdb[0]) {
8883 	case COMPARE_AND_WRITE: {
8884 		struct scsi_compare_and_write *cdb;
8885 
8886 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8887 		if (cdb->byte2 & SRW10_FUA)
8888 			flags |= CTL_LLF_FUA;
8889 		if (cdb->byte2 & SRW10_DPO)
8890 			flags |= CTL_LLF_DPO;
8891 		lba = scsi_8btou64(cdb->addr);
8892 		num_blocks = cdb->length;
8893 		break;
8894 	}
8895 	default:
8896 		/*
8897 		 * We got a command we don't support.  This shouldn't
8898 		 * happen, commands should be filtered out above us.
8899 		 */
8900 		ctl_set_invalid_opcode(ctsio);
8901 		ctl_done((union ctl_io *)ctsio);
8902 
8903 		return (CTL_RETVAL_COMPLETE);
8904 		break; /* NOTREACHED */
8905 	}
8906 
8907 	/*
8908 	 * The first check is to make sure we're in bounds, the second
8909 	 * check is to catch wrap-around problems.  If the lba + num blocks
8910 	 * is less than the lba, then we've wrapped around and the block
8911 	 * range is invalid anyway.
8912 	 */
8913 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8914 	 || ((lba + num_blocks) < lba)) {
8915 		ctl_set_lba_out_of_range(ctsio,
8916 		    MAX(lba, lun->be_lun->maxlba + 1));
8917 		ctl_done((union ctl_io *)ctsio);
8918 		return (CTL_RETVAL_COMPLETE);
8919 	}
8920 
8921 	/*
8922 	 * According to SBC-3, a transfer length of 0 is not an error.
8923 	 */
8924 	if (num_blocks == 0) {
8925 		ctl_set_success(ctsio);
8926 		ctl_done((union ctl_io *)ctsio);
8927 		return (CTL_RETVAL_COMPLETE);
8928 	}
8929 
8930 	/* Set FUA if write cache is disabled. */
8931 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8932 		flags |= CTL_LLF_FUA;
8933 
8934 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8935 	ctsio->kern_rel_offset = 0;
8936 
8937 	/*
8938 	 * Set the IO_CONT flag, so that if this I/O gets passed to
8939 	 * ctl_data_submit_done(), it'll get passed back to
8940 	 * ctl_ctl_cnw_cont() for further processing.
8941 	 */
8942 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8943 	ctsio->io_cont = ctl_cnw_cont;
8944 
8945 	lbalen = (struct ctl_lba_len_flags *)
8946 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8947 	lbalen->lba = lba;
8948 	lbalen->len = num_blocks;
8949 	lbalen->flags = CTL_LLF_COMPARE | flags;
8950 
8951 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8952 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8953 	return (retval);
8954 }
8955 
8956 int
8957 ctl_verify(struct ctl_scsiio *ctsio)
8958 {
8959 	struct ctl_lun *lun = CTL_LUN(ctsio);
8960 	struct ctl_lba_len_flags *lbalen;
8961 	uint64_t lba;
8962 	uint32_t num_blocks;
8963 	int bytchk, flags;
8964 	int retval;
8965 
8966 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8967 
8968 	bytchk = 0;
8969 	flags = CTL_LLF_FUA;
8970 	switch (ctsio->cdb[0]) {
8971 	case VERIFY_10: {
8972 		struct scsi_verify_10 *cdb;
8973 
8974 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8975 		if (cdb->byte2 & SVFY_BYTCHK)
8976 			bytchk = 1;
8977 		if (cdb->byte2 & SVFY_DPO)
8978 			flags |= CTL_LLF_DPO;
8979 		lba = scsi_4btoul(cdb->addr);
8980 		num_blocks = scsi_2btoul(cdb->length);
8981 		break;
8982 	}
8983 	case VERIFY_12: {
8984 		struct scsi_verify_12 *cdb;
8985 
8986 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8987 		if (cdb->byte2 & SVFY_BYTCHK)
8988 			bytchk = 1;
8989 		if (cdb->byte2 & SVFY_DPO)
8990 			flags |= CTL_LLF_DPO;
8991 		lba = scsi_4btoul(cdb->addr);
8992 		num_blocks = scsi_4btoul(cdb->length);
8993 		break;
8994 	}
8995 	case VERIFY_16: {
8996 		struct scsi_rw_16 *cdb;
8997 
8998 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8999 		if (cdb->byte2 & SVFY_BYTCHK)
9000 			bytchk = 1;
9001 		if (cdb->byte2 & SVFY_DPO)
9002 			flags |= CTL_LLF_DPO;
9003 		lba = scsi_8btou64(cdb->addr);
9004 		num_blocks = scsi_4btoul(cdb->length);
9005 		break;
9006 	}
9007 	default:
9008 		/*
9009 		 * We got a command we don't support.  This shouldn't
9010 		 * happen, commands should be filtered out above us.
9011 		 */
9012 		ctl_set_invalid_opcode(ctsio);
9013 		ctl_done((union ctl_io *)ctsio);
9014 		return (CTL_RETVAL_COMPLETE);
9015 	}
9016 
9017 	/*
9018 	 * The first check is to make sure we're in bounds, the second
9019 	 * check is to catch wrap-around problems.  If the lba + num blocks
9020 	 * is less than the lba, then we've wrapped around and the block
9021 	 * range is invalid anyway.
9022 	 */
9023 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9024 	 || ((lba + num_blocks) < lba)) {
9025 		ctl_set_lba_out_of_range(ctsio,
9026 		    MAX(lba, lun->be_lun->maxlba + 1));
9027 		ctl_done((union ctl_io *)ctsio);
9028 		return (CTL_RETVAL_COMPLETE);
9029 	}
9030 
9031 	/*
9032 	 * According to SBC-3, a transfer length of 0 is not an error.
9033 	 */
9034 	if (num_blocks == 0) {
9035 		ctl_set_success(ctsio);
9036 		ctl_done((union ctl_io *)ctsio);
9037 		return (CTL_RETVAL_COMPLETE);
9038 	}
9039 
9040 	lbalen = (struct ctl_lba_len_flags *)
9041 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9042 	lbalen->lba = lba;
9043 	lbalen->len = num_blocks;
9044 	if (bytchk) {
9045 		lbalen->flags = CTL_LLF_COMPARE | flags;
9046 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9047 	} else {
9048 		lbalen->flags = CTL_LLF_VERIFY | flags;
9049 		ctsio->kern_total_len = 0;
9050 	}
9051 	ctsio->kern_rel_offset = 0;
9052 
9053 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9054 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9055 	return (retval);
9056 }
9057 
9058 int
9059 ctl_report_luns(struct ctl_scsiio *ctsio)
9060 {
9061 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9062 	struct ctl_port *port = CTL_PORT(ctsio);
9063 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9064 	struct scsi_report_luns *cdb;
9065 	struct scsi_report_luns_data *lun_data;
9066 	int num_filled, num_luns, num_port_luns, retval;
9067 	uint32_t alloc_len, lun_datalen;
9068 	uint32_t initidx, targ_lun_id, lun_id;
9069 
9070 	retval = CTL_RETVAL_COMPLETE;
9071 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9072 
9073 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9074 
9075 	num_luns = 0;
9076 	num_port_luns = port->lun_map ? port->lun_map_size : CTL_MAX_LUNS;
9077 	mtx_lock(&softc->ctl_lock);
9078 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9079 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9080 			num_luns++;
9081 	}
9082 	mtx_unlock(&softc->ctl_lock);
9083 
9084 	switch (cdb->select_report) {
9085 	case RPL_REPORT_DEFAULT:
9086 	case RPL_REPORT_ALL:
9087 	case RPL_REPORT_NONSUBSID:
9088 		break;
9089 	case RPL_REPORT_WELLKNOWN:
9090 	case RPL_REPORT_ADMIN:
9091 	case RPL_REPORT_CONGLOM:
9092 		num_luns = 0;
9093 		break;
9094 	default:
9095 		ctl_set_invalid_field(ctsio,
9096 				      /*sks_valid*/ 1,
9097 				      /*command*/ 1,
9098 				      /*field*/ 2,
9099 				      /*bit_valid*/ 0,
9100 				      /*bit*/ 0);
9101 		ctl_done((union ctl_io *)ctsio);
9102 		return (retval);
9103 		break; /* NOTREACHED */
9104 	}
9105 
9106 	alloc_len = scsi_4btoul(cdb->length);
9107 	/*
9108 	 * The initiator has to allocate at least 16 bytes for this request,
9109 	 * so he can at least get the header and the first LUN.  Otherwise
9110 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9111 	 */
9112 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9113 	    sizeof(struct scsi_report_luns_lundata))) {
9114 		ctl_set_invalid_field(ctsio,
9115 				      /*sks_valid*/ 1,
9116 				      /*command*/ 1,
9117 				      /*field*/ 6,
9118 				      /*bit_valid*/ 0,
9119 				      /*bit*/ 0);
9120 		ctl_done((union ctl_io *)ctsio);
9121 		return (retval);
9122 	}
9123 
9124 	lun_datalen = sizeof(*lun_data) +
9125 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9126 
9127 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9128 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9129 	ctsio->kern_sg_entries = 0;
9130 
9131 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9132 
9133 	mtx_lock(&softc->ctl_lock);
9134 	for (targ_lun_id = 0, num_filled = 0;
9135 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9136 	    targ_lun_id++) {
9137 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9138 		if (lun_id == UINT32_MAX)
9139 			continue;
9140 		lun = softc->ctl_luns[lun_id];
9141 		if (lun == NULL)
9142 			continue;
9143 
9144 		be64enc(lun_data->luns[num_filled++].lundata,
9145 		    ctl_encode_lun(targ_lun_id));
9146 
9147 		/*
9148 		 * According to SPC-3, rev 14 section 6.21:
9149 		 *
9150 		 * "The execution of a REPORT LUNS command to any valid and
9151 		 * installed logical unit shall clear the REPORTED LUNS DATA
9152 		 * HAS CHANGED unit attention condition for all logical
9153 		 * units of that target with respect to the requesting
9154 		 * initiator. A valid and installed logical unit is one
9155 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9156 		 * INQUIRY data (see 6.4.2)."
9157 		 *
9158 		 * If request_lun is NULL, the LUN this report luns command
9159 		 * was issued to is either disabled or doesn't exist. In that
9160 		 * case, we shouldn't clear any pending lun change unit
9161 		 * attention.
9162 		 */
9163 		if (request_lun != NULL) {
9164 			mtx_lock(&lun->lun_lock);
9165 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9166 			mtx_unlock(&lun->lun_lock);
9167 		}
9168 	}
9169 	mtx_unlock(&softc->ctl_lock);
9170 
9171 	/*
9172 	 * It's quite possible that we've returned fewer LUNs than we allocated
9173 	 * space for.  Trim it.
9174 	 */
9175 	lun_datalen = sizeof(*lun_data) +
9176 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9177 
9178 	if (lun_datalen < alloc_len) {
9179 		ctsio->residual = alloc_len - lun_datalen;
9180 		ctsio->kern_data_len = lun_datalen;
9181 		ctsio->kern_total_len = lun_datalen;
9182 	} else {
9183 		ctsio->residual = 0;
9184 		ctsio->kern_data_len = alloc_len;
9185 		ctsio->kern_total_len = alloc_len;
9186 	}
9187 	ctsio->kern_rel_offset = 0;
9188 	ctsio->kern_sg_entries = 0;
9189 
9190 	/*
9191 	 * We set this to the actual data length, regardless of how much
9192 	 * space we actually have to return results.  If the user looks at
9193 	 * this value, he'll know whether or not he allocated enough space
9194 	 * and reissue the command if necessary.  We don't support well
9195 	 * known logical units, so if the user asks for that, return none.
9196 	 */
9197 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9198 
9199 	/*
9200 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9201 	 * this request.
9202 	 */
9203 	ctl_set_success(ctsio);
9204 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9205 	ctsio->be_move_done = ctl_config_move_done;
9206 	ctl_datamove((union ctl_io *)ctsio);
9207 	return (retval);
9208 }
9209 
9210 int
9211 ctl_request_sense(struct ctl_scsiio *ctsio)
9212 {
9213 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9214 	struct ctl_lun *lun = CTL_LUN(ctsio);
9215 	struct scsi_request_sense *cdb;
9216 	struct scsi_sense_data *sense_ptr;
9217 	uint32_t initidx;
9218 	int have_error;
9219 	u_int sense_len = SSD_FULL_SIZE;
9220 	scsi_sense_data_type sense_format;
9221 	ctl_ua_type ua_type;
9222 	uint8_t asc = 0, ascq = 0;
9223 
9224 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9225 
9226 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9227 
9228 	/*
9229 	 * Determine which sense format the user wants.
9230 	 */
9231 	if (cdb->byte2 & SRS_DESC)
9232 		sense_format = SSD_TYPE_DESC;
9233 	else
9234 		sense_format = SSD_TYPE_FIXED;
9235 
9236 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9237 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9238 	ctsio->kern_sg_entries = 0;
9239 
9240 	/*
9241 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9242 	 * larger than the largest allowed value for the length field in the
9243 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9244 	 */
9245 	ctsio->residual = 0;
9246 	ctsio->kern_data_len = cdb->length;
9247 	ctsio->kern_total_len = cdb->length;
9248 
9249 	ctsio->kern_rel_offset = 0;
9250 	ctsio->kern_sg_entries = 0;
9251 
9252 	/*
9253 	 * If we don't have a LUN, we don't have any pending sense.
9254 	 */
9255 	if (lun == NULL ||
9256 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9257 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9258 		/* "Logical unit not supported" */
9259 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9260 		    /*current_error*/ 1,
9261 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9262 		    /*asc*/ 0x25,
9263 		    /*ascq*/ 0x00,
9264 		    SSD_ELEM_NONE);
9265 		goto send;
9266 	}
9267 
9268 	have_error = 0;
9269 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9270 	/*
9271 	 * Check for pending sense, and then for pending unit attentions.
9272 	 * Pending sense gets returned first, then pending unit attentions.
9273 	 */
9274 	mtx_lock(&lun->lun_lock);
9275 #ifdef CTL_WITH_CA
9276 	if (ctl_is_set(lun->have_ca, initidx)) {
9277 		scsi_sense_data_type stored_format;
9278 
9279 		/*
9280 		 * Check to see which sense format was used for the stored
9281 		 * sense data.
9282 		 */
9283 		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9284 
9285 		/*
9286 		 * If the user requested a different sense format than the
9287 		 * one we stored, then we need to convert it to the other
9288 		 * format.  If we're going from descriptor to fixed format
9289 		 * sense data, we may lose things in translation, depending
9290 		 * on what options were used.
9291 		 *
9292 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9293 		 * for some reason we'll just copy it out as-is.
9294 		 */
9295 		if ((stored_format == SSD_TYPE_FIXED)
9296 		 && (sense_format == SSD_TYPE_DESC))
9297 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9298 			    &lun->pending_sense[initidx],
9299 			    (struct scsi_sense_data_desc *)sense_ptr);
9300 		else if ((stored_format == SSD_TYPE_DESC)
9301 		      && (sense_format == SSD_TYPE_FIXED))
9302 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9303 			    &lun->pending_sense[initidx],
9304 			    (struct scsi_sense_data_fixed *)sense_ptr);
9305 		else
9306 			memcpy(sense_ptr, &lun->pending_sense[initidx],
9307 			       MIN(sizeof(*sense_ptr),
9308 			       sizeof(lun->pending_sense[initidx])));
9309 
9310 		ctl_clear_mask(lun->have_ca, initidx);
9311 		have_error = 1;
9312 	} else
9313 #endif
9314 	if (have_error == 0) {
9315 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9316 		    sense_format);
9317 		if (ua_type != CTL_UA_NONE)
9318 			have_error = 1;
9319 	}
9320 	if (have_error == 0) {
9321 		/*
9322 		 * Report informational exception if have one and allowed.
9323 		 */
9324 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9325 			asc = lun->ie_asc;
9326 			ascq = lun->ie_ascq;
9327 		}
9328 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9329 		    /*current_error*/ 1,
9330 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9331 		    /*asc*/ asc,
9332 		    /*ascq*/ ascq,
9333 		    SSD_ELEM_NONE);
9334 	}
9335 	mtx_unlock(&lun->lun_lock);
9336 
9337 send:
9338 	/*
9339 	 * We report the SCSI status as OK, since the status of the command
9340 	 * itself is OK.  We're reporting sense as parameter data.
9341 	 */
9342 	ctl_set_success(ctsio);
9343 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9344 	ctsio->be_move_done = ctl_config_move_done;
9345 	ctl_datamove((union ctl_io *)ctsio);
9346 	return (CTL_RETVAL_COMPLETE);
9347 }
9348 
9349 int
9350 ctl_tur(struct ctl_scsiio *ctsio)
9351 {
9352 
9353 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9354 
9355 	ctl_set_success(ctsio);
9356 	ctl_done((union ctl_io *)ctsio);
9357 
9358 	return (CTL_RETVAL_COMPLETE);
9359 }
9360 
9361 /*
9362  * SCSI VPD page 0x00, the Supported VPD Pages page.
9363  */
9364 static int
9365 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9366 {
9367 	struct ctl_lun *lun = CTL_LUN(ctsio);
9368 	struct scsi_vpd_supported_pages *pages;
9369 	int sup_page_size;
9370 	int p;
9371 
9372 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9373 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9374 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9375 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9376 	ctsio->kern_sg_entries = 0;
9377 
9378 	if (sup_page_size < alloc_len) {
9379 		ctsio->residual = alloc_len - sup_page_size;
9380 		ctsio->kern_data_len = sup_page_size;
9381 		ctsio->kern_total_len = sup_page_size;
9382 	} else {
9383 		ctsio->residual = 0;
9384 		ctsio->kern_data_len = alloc_len;
9385 		ctsio->kern_total_len = alloc_len;
9386 	}
9387 	ctsio->kern_rel_offset = 0;
9388 	ctsio->kern_sg_entries = 0;
9389 
9390 	/*
9391 	 * The control device is always connected.  The disk device, on the
9392 	 * other hand, may not be online all the time.  Need to change this
9393 	 * to figure out whether the disk device is actually online or not.
9394 	 */
9395 	if (lun != NULL)
9396 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9397 				lun->be_lun->lun_type;
9398 	else
9399 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9400 
9401 	p = 0;
9402 	/* Supported VPD pages */
9403 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9404 	/* Serial Number */
9405 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9406 	/* Device Identification */
9407 	pages->page_list[p++] = SVPD_DEVICE_ID;
9408 	/* Extended INQUIRY Data */
9409 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9410 	/* Mode Page Policy */
9411 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9412 	/* SCSI Ports */
9413 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9414 	/* Third-party Copy */
9415 	pages->page_list[p++] = SVPD_SCSI_TPC;
9416 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9417 		/* Block limits */
9418 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9419 		/* Block Device Characteristics */
9420 		pages->page_list[p++] = SVPD_BDC;
9421 		/* Logical Block Provisioning */
9422 		pages->page_list[p++] = SVPD_LBP;
9423 	}
9424 	pages->length = p;
9425 
9426 	ctl_set_success(ctsio);
9427 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9428 	ctsio->be_move_done = ctl_config_move_done;
9429 	ctl_datamove((union ctl_io *)ctsio);
9430 	return (CTL_RETVAL_COMPLETE);
9431 }
9432 
9433 /*
9434  * SCSI VPD page 0x80, the Unit Serial Number page.
9435  */
9436 static int
9437 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9438 {
9439 	struct ctl_lun *lun = CTL_LUN(ctsio);
9440 	struct scsi_vpd_unit_serial_number *sn_ptr;
9441 	int data_len;
9442 
9443 	data_len = 4 + CTL_SN_LEN;
9444 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9445 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9446 	if (data_len < alloc_len) {
9447 		ctsio->residual = alloc_len - data_len;
9448 		ctsio->kern_data_len = data_len;
9449 		ctsio->kern_total_len = data_len;
9450 	} else {
9451 		ctsio->residual = 0;
9452 		ctsio->kern_data_len = alloc_len;
9453 		ctsio->kern_total_len = alloc_len;
9454 	}
9455 	ctsio->kern_rel_offset = 0;
9456 	ctsio->kern_sg_entries = 0;
9457 
9458 	/*
9459 	 * The control device is always connected.  The disk device, on the
9460 	 * other hand, may not be online all the time.  Need to change this
9461 	 * to figure out whether the disk device is actually online or not.
9462 	 */
9463 	if (lun != NULL)
9464 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9465 				  lun->be_lun->lun_type;
9466 	else
9467 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9468 
9469 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9470 	sn_ptr->length = CTL_SN_LEN;
9471 	/*
9472 	 * If we don't have a LUN, we just leave the serial number as
9473 	 * all spaces.
9474 	 */
9475 	if (lun != NULL) {
9476 		strncpy((char *)sn_ptr->serial_num,
9477 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9478 	} else
9479 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9480 
9481 	ctl_set_success(ctsio);
9482 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9483 	ctsio->be_move_done = ctl_config_move_done;
9484 	ctl_datamove((union ctl_io *)ctsio);
9485 	return (CTL_RETVAL_COMPLETE);
9486 }
9487 
9488 
9489 /*
9490  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9491  */
9492 static int
9493 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9494 {
9495 	struct ctl_lun *lun = CTL_LUN(ctsio);
9496 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9497 	int data_len;
9498 
9499 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9500 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9501 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9502 	ctsio->kern_sg_entries = 0;
9503 
9504 	if (data_len < alloc_len) {
9505 		ctsio->residual = alloc_len - data_len;
9506 		ctsio->kern_data_len = data_len;
9507 		ctsio->kern_total_len = data_len;
9508 	} else {
9509 		ctsio->residual = 0;
9510 		ctsio->kern_data_len = alloc_len;
9511 		ctsio->kern_total_len = alloc_len;
9512 	}
9513 	ctsio->kern_rel_offset = 0;
9514 	ctsio->kern_sg_entries = 0;
9515 
9516 	/*
9517 	 * The control device is always connected.  The disk device, on the
9518 	 * other hand, may not be online all the time.
9519 	 */
9520 	if (lun != NULL)
9521 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9522 				     lun->be_lun->lun_type;
9523 	else
9524 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9525 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9526 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9527 	/*
9528 	 * We support head of queue, ordered and simple tags.
9529 	 */
9530 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9531 	/*
9532 	 * Volatile cache supported.
9533 	 */
9534 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9535 
9536 	/*
9537 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9538 	 * attention for a particular IT nexus on all LUNs once we report
9539 	 * it to that nexus once.  This bit is required as of SPC-4.
9540 	 */
9541 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9542 
9543 	/*
9544 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9545 	 */
9546 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9547 
9548 	/*
9549 	 * XXX KDM in order to correctly answer this, we would need
9550 	 * information from the SIM to determine how much sense data it
9551 	 * can send.  So this would really be a path inquiry field, most
9552 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9553 	 * but the hardware may or may not be able to support that much.
9554 	 * 0 just means that the maximum sense data length is not reported.
9555 	 */
9556 	eid_ptr->max_sense_length = 0;
9557 
9558 	ctl_set_success(ctsio);
9559 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9560 	ctsio->be_move_done = ctl_config_move_done;
9561 	ctl_datamove((union ctl_io *)ctsio);
9562 	return (CTL_RETVAL_COMPLETE);
9563 }
9564 
9565 static int
9566 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9567 {
9568 	struct ctl_lun *lun = CTL_LUN(ctsio);
9569 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9570 	int data_len;
9571 
9572 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9573 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9574 
9575 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9576 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9577 	ctsio->kern_sg_entries = 0;
9578 
9579 	if (data_len < alloc_len) {
9580 		ctsio->residual = alloc_len - data_len;
9581 		ctsio->kern_data_len = data_len;
9582 		ctsio->kern_total_len = data_len;
9583 	} else {
9584 		ctsio->residual = 0;
9585 		ctsio->kern_data_len = alloc_len;
9586 		ctsio->kern_total_len = alloc_len;
9587 	}
9588 	ctsio->kern_rel_offset = 0;
9589 	ctsio->kern_sg_entries = 0;
9590 
9591 	/*
9592 	 * The control device is always connected.  The disk device, on the
9593 	 * other hand, may not be online all the time.
9594 	 */
9595 	if (lun != NULL)
9596 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9597 				     lun->be_lun->lun_type;
9598 	else
9599 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9600 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9601 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9602 	mpp_ptr->descr[0].page_code = 0x3f;
9603 	mpp_ptr->descr[0].subpage_code = 0xff;
9604 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9605 
9606 	ctl_set_success(ctsio);
9607 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9608 	ctsio->be_move_done = ctl_config_move_done;
9609 	ctl_datamove((union ctl_io *)ctsio);
9610 	return (CTL_RETVAL_COMPLETE);
9611 }
9612 
9613 /*
9614  * SCSI VPD page 0x83, the Device Identification page.
9615  */
9616 static int
9617 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9618 {
9619 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9620 	struct ctl_port *port = CTL_PORT(ctsio);
9621 	struct ctl_lun *lun = CTL_LUN(ctsio);
9622 	struct scsi_vpd_device_id *devid_ptr;
9623 	struct scsi_vpd_id_descriptor *desc;
9624 	int data_len, g;
9625 	uint8_t proto;
9626 
9627 	data_len = sizeof(struct scsi_vpd_device_id) +
9628 	    sizeof(struct scsi_vpd_id_descriptor) +
9629 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9630 	    sizeof(struct scsi_vpd_id_descriptor) +
9631 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9632 	if (lun && lun->lun_devid)
9633 		data_len += lun->lun_devid->len;
9634 	if (port && port->port_devid)
9635 		data_len += port->port_devid->len;
9636 	if (port && port->target_devid)
9637 		data_len += port->target_devid->len;
9638 
9639 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9640 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9641 	ctsio->kern_sg_entries = 0;
9642 
9643 	if (data_len < alloc_len) {
9644 		ctsio->residual = alloc_len - data_len;
9645 		ctsio->kern_data_len = data_len;
9646 		ctsio->kern_total_len = data_len;
9647 	} else {
9648 		ctsio->residual = 0;
9649 		ctsio->kern_data_len = alloc_len;
9650 		ctsio->kern_total_len = alloc_len;
9651 	}
9652 	ctsio->kern_rel_offset = 0;
9653 	ctsio->kern_sg_entries = 0;
9654 
9655 	/*
9656 	 * The control device is always connected.  The disk device, on the
9657 	 * other hand, may not be online all the time.
9658 	 */
9659 	if (lun != NULL)
9660 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9661 				     lun->be_lun->lun_type;
9662 	else
9663 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9664 	devid_ptr->page_code = SVPD_DEVICE_ID;
9665 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9666 
9667 	if (port && port->port_type == CTL_PORT_FC)
9668 		proto = SCSI_PROTO_FC << 4;
9669 	else if (port && port->port_type == CTL_PORT_ISCSI)
9670 		proto = SCSI_PROTO_ISCSI << 4;
9671 	else
9672 		proto = SCSI_PROTO_SPI << 4;
9673 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9674 
9675 	/*
9676 	 * We're using a LUN association here.  i.e., this device ID is a
9677 	 * per-LUN identifier.
9678 	 */
9679 	if (lun && lun->lun_devid) {
9680 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9681 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9682 		    lun->lun_devid->len);
9683 	}
9684 
9685 	/*
9686 	 * This is for the WWPN which is a port association.
9687 	 */
9688 	if (port && port->port_devid) {
9689 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9690 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9691 		    port->port_devid->len);
9692 	}
9693 
9694 	/*
9695 	 * This is for the Relative Target Port(type 4h) identifier
9696 	 */
9697 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9698 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9699 	    SVPD_ID_TYPE_RELTARG;
9700 	desc->length = 4;
9701 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9702 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9703 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9704 
9705 	/*
9706 	 * This is for the Target Port Group(type 5h) identifier
9707 	 */
9708 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9709 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9710 	    SVPD_ID_TYPE_TPORTGRP;
9711 	desc->length = 4;
9712 	if (softc->is_single ||
9713 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9714 		g = 1;
9715 	else
9716 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9717 	scsi_ulto2b(g, &desc->identifier[2]);
9718 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9719 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9720 
9721 	/*
9722 	 * This is for the Target identifier
9723 	 */
9724 	if (port && port->target_devid) {
9725 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9726 	}
9727 
9728 	ctl_set_success(ctsio);
9729 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9730 	ctsio->be_move_done = ctl_config_move_done;
9731 	ctl_datamove((union ctl_io *)ctsio);
9732 	return (CTL_RETVAL_COMPLETE);
9733 }
9734 
9735 static int
9736 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9737 {
9738 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9739 	struct ctl_lun *lun = CTL_LUN(ctsio);
9740 	struct scsi_vpd_scsi_ports *sp;
9741 	struct scsi_vpd_port_designation *pd;
9742 	struct scsi_vpd_port_designation_cont *pdc;
9743 	struct ctl_port *port;
9744 	int data_len, num_target_ports, iid_len, id_len;
9745 
9746 	num_target_ports = 0;
9747 	iid_len = 0;
9748 	id_len = 0;
9749 	mtx_lock(&softc->ctl_lock);
9750 	STAILQ_FOREACH(port, &softc->port_list, links) {
9751 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9752 			continue;
9753 		if (lun != NULL &&
9754 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9755 			continue;
9756 		num_target_ports++;
9757 		if (port->init_devid)
9758 			iid_len += port->init_devid->len;
9759 		if (port->port_devid)
9760 			id_len += port->port_devid->len;
9761 	}
9762 	mtx_unlock(&softc->ctl_lock);
9763 
9764 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9765 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9766 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9767 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9768 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9769 	ctsio->kern_sg_entries = 0;
9770 
9771 	if (data_len < alloc_len) {
9772 		ctsio->residual = alloc_len - data_len;
9773 		ctsio->kern_data_len = data_len;
9774 		ctsio->kern_total_len = data_len;
9775 	} else {
9776 		ctsio->residual = 0;
9777 		ctsio->kern_data_len = alloc_len;
9778 		ctsio->kern_total_len = alloc_len;
9779 	}
9780 	ctsio->kern_rel_offset = 0;
9781 	ctsio->kern_sg_entries = 0;
9782 
9783 	/*
9784 	 * The control device is always connected.  The disk device, on the
9785 	 * other hand, may not be online all the time.  Need to change this
9786 	 * to figure out whether the disk device is actually online or not.
9787 	 */
9788 	if (lun != NULL)
9789 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9790 				  lun->be_lun->lun_type;
9791 	else
9792 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9793 
9794 	sp->page_code = SVPD_SCSI_PORTS;
9795 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9796 	    sp->page_length);
9797 	pd = &sp->design[0];
9798 
9799 	mtx_lock(&softc->ctl_lock);
9800 	STAILQ_FOREACH(port, &softc->port_list, links) {
9801 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9802 			continue;
9803 		if (lun != NULL &&
9804 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9805 			continue;
9806 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9807 		if (port->init_devid) {
9808 			iid_len = port->init_devid->len;
9809 			memcpy(pd->initiator_transportid,
9810 			    port->init_devid->data, port->init_devid->len);
9811 		} else
9812 			iid_len = 0;
9813 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9814 		pdc = (struct scsi_vpd_port_designation_cont *)
9815 		    (&pd->initiator_transportid[iid_len]);
9816 		if (port->port_devid) {
9817 			id_len = port->port_devid->len;
9818 			memcpy(pdc->target_port_descriptors,
9819 			    port->port_devid->data, port->port_devid->len);
9820 		} else
9821 			id_len = 0;
9822 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9823 		pd = (struct scsi_vpd_port_designation *)
9824 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9825 	}
9826 	mtx_unlock(&softc->ctl_lock);
9827 
9828 	ctl_set_success(ctsio);
9829 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9830 	ctsio->be_move_done = ctl_config_move_done;
9831 	ctl_datamove((union ctl_io *)ctsio);
9832 	return (CTL_RETVAL_COMPLETE);
9833 }
9834 
9835 static int
9836 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9837 {
9838 	struct ctl_lun *lun = CTL_LUN(ctsio);
9839 	struct scsi_vpd_block_limits *bl_ptr;
9840 	uint64_t ival;
9841 
9842 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9843 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9844 	ctsio->kern_sg_entries = 0;
9845 
9846 	if (sizeof(*bl_ptr) < alloc_len) {
9847 		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9848 		ctsio->kern_data_len = sizeof(*bl_ptr);
9849 		ctsio->kern_total_len = sizeof(*bl_ptr);
9850 	} else {
9851 		ctsio->residual = 0;
9852 		ctsio->kern_data_len = alloc_len;
9853 		ctsio->kern_total_len = alloc_len;
9854 	}
9855 	ctsio->kern_rel_offset = 0;
9856 	ctsio->kern_sg_entries = 0;
9857 
9858 	/*
9859 	 * The control device is always connected.  The disk device, on the
9860 	 * other hand, may not be online all the time.  Need to change this
9861 	 * to figure out whether the disk device is actually online or not.
9862 	 */
9863 	if (lun != NULL)
9864 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9865 				  lun->be_lun->lun_type;
9866 	else
9867 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9868 
9869 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9870 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9871 	bl_ptr->max_cmp_write_len = 0xff;
9872 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9873 	if (lun != NULL) {
9874 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9875 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9876 			ival = 0xffffffff;
9877 			ctl_get_opt_number(&lun->be_lun->options,
9878 			    "unmap_max_lba", &ival);
9879 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9880 			ival = 0xffffffff;
9881 			ctl_get_opt_number(&lun->be_lun->options,
9882 			    "unmap_max_descr", &ival);
9883 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9884 			if (lun->be_lun->ublockexp != 0) {
9885 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9886 				    bl_ptr->opt_unmap_grain);
9887 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9888 				    bl_ptr->unmap_grain_align);
9889 			}
9890 		}
9891 		scsi_ulto4b(lun->be_lun->atomicblock,
9892 		    bl_ptr->max_atomic_transfer_length);
9893 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9894 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9895 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9896 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9897 		ival = UINT64_MAX;
9898 		ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9899 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9900 	}
9901 
9902 	ctl_set_success(ctsio);
9903 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9904 	ctsio->be_move_done = ctl_config_move_done;
9905 	ctl_datamove((union ctl_io *)ctsio);
9906 	return (CTL_RETVAL_COMPLETE);
9907 }
9908 
9909 static int
9910 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9911 {
9912 	struct ctl_lun *lun = CTL_LUN(ctsio);
9913 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9914 	const char *value;
9915 	u_int i;
9916 
9917 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9918 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9919 	ctsio->kern_sg_entries = 0;
9920 
9921 	if (sizeof(*bdc_ptr) < alloc_len) {
9922 		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9923 		ctsio->kern_data_len = sizeof(*bdc_ptr);
9924 		ctsio->kern_total_len = sizeof(*bdc_ptr);
9925 	} else {
9926 		ctsio->residual = 0;
9927 		ctsio->kern_data_len = alloc_len;
9928 		ctsio->kern_total_len = alloc_len;
9929 	}
9930 	ctsio->kern_rel_offset = 0;
9931 	ctsio->kern_sg_entries = 0;
9932 
9933 	/*
9934 	 * The control device is always connected.  The disk device, on the
9935 	 * other hand, may not be online all the time.  Need to change this
9936 	 * to figure out whether the disk device is actually online or not.
9937 	 */
9938 	if (lun != NULL)
9939 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9940 				  lun->be_lun->lun_type;
9941 	else
9942 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9943 	bdc_ptr->page_code = SVPD_BDC;
9944 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9945 	if (lun != NULL &&
9946 	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9947 		i = strtol(value, NULL, 0);
9948 	else
9949 		i = CTL_DEFAULT_ROTATION_RATE;
9950 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9951 	if (lun != NULL &&
9952 	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9953 		i = strtol(value, NULL, 0);
9954 	else
9955 		i = 0;
9956 	bdc_ptr->wab_wac_ff = (i & 0x0f);
9957 	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9958 
9959 	ctl_set_success(ctsio);
9960 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9961 	ctsio->be_move_done = ctl_config_move_done;
9962 	ctl_datamove((union ctl_io *)ctsio);
9963 	return (CTL_RETVAL_COMPLETE);
9964 }
9965 
9966 static int
9967 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9968 {
9969 	struct ctl_lun *lun = CTL_LUN(ctsio);
9970 	struct scsi_vpd_logical_block_prov *lbp_ptr;
9971 	const char *value;
9972 
9973 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9974 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9975 	ctsio->kern_sg_entries = 0;
9976 
9977 	if (sizeof(*lbp_ptr) < alloc_len) {
9978 		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9979 		ctsio->kern_data_len = sizeof(*lbp_ptr);
9980 		ctsio->kern_total_len = sizeof(*lbp_ptr);
9981 	} else {
9982 		ctsio->residual = 0;
9983 		ctsio->kern_data_len = alloc_len;
9984 		ctsio->kern_total_len = alloc_len;
9985 	}
9986 	ctsio->kern_rel_offset = 0;
9987 	ctsio->kern_sg_entries = 0;
9988 
9989 	/*
9990 	 * The control device is always connected.  The disk device, on the
9991 	 * other hand, may not be online all the time.  Need to change this
9992 	 * to figure out whether the disk device is actually online or not.
9993 	 */
9994 	if (lun != NULL)
9995 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9996 				  lun->be_lun->lun_type;
9997 	else
9998 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9999 
10000 	lbp_ptr->page_code = SVPD_LBP;
10001 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10002 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10003 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10004 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10005 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10006 		value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
10007 		if (value != NULL) {
10008 			if (strcmp(value, "resource") == 0)
10009 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10010 			else if (strcmp(value, "thin") == 0)
10011 				lbp_ptr->prov_type = SVPD_LBP_THIN;
10012 		} else
10013 			lbp_ptr->prov_type = SVPD_LBP_THIN;
10014 	}
10015 
10016 	ctl_set_success(ctsio);
10017 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10018 	ctsio->be_move_done = ctl_config_move_done;
10019 	ctl_datamove((union ctl_io *)ctsio);
10020 	return (CTL_RETVAL_COMPLETE);
10021 }
10022 
10023 /*
10024  * INQUIRY with the EVPD bit set.
10025  */
10026 static int
10027 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10028 {
10029 	struct ctl_lun *lun = CTL_LUN(ctsio);
10030 	struct scsi_inquiry *cdb;
10031 	int alloc_len, retval;
10032 
10033 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10034 	alloc_len = scsi_2btoul(cdb->length);
10035 
10036 	switch (cdb->page_code) {
10037 	case SVPD_SUPPORTED_PAGES:
10038 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10039 		break;
10040 	case SVPD_UNIT_SERIAL_NUMBER:
10041 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10042 		break;
10043 	case SVPD_DEVICE_ID:
10044 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10045 		break;
10046 	case SVPD_EXTENDED_INQUIRY_DATA:
10047 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10048 		break;
10049 	case SVPD_MODE_PAGE_POLICY:
10050 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10051 		break;
10052 	case SVPD_SCSI_PORTS:
10053 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10054 		break;
10055 	case SVPD_SCSI_TPC:
10056 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10057 		break;
10058 	case SVPD_BLOCK_LIMITS:
10059 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10060 			goto err;
10061 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10062 		break;
10063 	case SVPD_BDC:
10064 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10065 			goto err;
10066 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10067 		break;
10068 	case SVPD_LBP:
10069 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10070 			goto err;
10071 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10072 		break;
10073 	default:
10074 err:
10075 		ctl_set_invalid_field(ctsio,
10076 				      /*sks_valid*/ 1,
10077 				      /*command*/ 1,
10078 				      /*field*/ 2,
10079 				      /*bit_valid*/ 0,
10080 				      /*bit*/ 0);
10081 		ctl_done((union ctl_io *)ctsio);
10082 		retval = CTL_RETVAL_COMPLETE;
10083 		break;
10084 	}
10085 
10086 	return (retval);
10087 }
10088 
10089 /*
10090  * Standard INQUIRY data.
10091  */
10092 static int
10093 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10094 {
10095 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
10096 	struct ctl_port *port = CTL_PORT(ctsio);
10097 	struct ctl_lun *lun = CTL_LUN(ctsio);
10098 	struct scsi_inquiry_data *inq_ptr;
10099 	struct scsi_inquiry *cdb;
10100 	char *val;
10101 	uint32_t alloc_len, data_len;
10102 	ctl_port_type port_type;
10103 
10104 	port_type = port->port_type;
10105 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10106 		port_type = CTL_PORT_SCSI;
10107 
10108 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10109 	alloc_len = scsi_2btoul(cdb->length);
10110 
10111 	/*
10112 	 * We malloc the full inquiry data size here and fill it
10113 	 * in.  If the user only asks for less, we'll give him
10114 	 * that much.
10115 	 */
10116 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10117 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10118 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10119 	ctsio->kern_sg_entries = 0;
10120 	ctsio->kern_rel_offset = 0;
10121 
10122 	if (data_len < alloc_len) {
10123 		ctsio->residual = alloc_len - data_len;
10124 		ctsio->kern_data_len = data_len;
10125 		ctsio->kern_total_len = data_len;
10126 	} else {
10127 		ctsio->residual = 0;
10128 		ctsio->kern_data_len = alloc_len;
10129 		ctsio->kern_total_len = alloc_len;
10130 	}
10131 
10132 	if (lun != NULL) {
10133 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10134 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10135 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10136 			    lun->be_lun->lun_type;
10137 		} else {
10138 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10139 			    lun->be_lun->lun_type;
10140 		}
10141 		if (lun->flags & CTL_LUN_REMOVABLE)
10142 			inq_ptr->dev_qual2 |= SID_RMB;
10143 	} else
10144 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10145 
10146 	/* RMB in byte 2 is 0 */
10147 	inq_ptr->version = SCSI_REV_SPC5;
10148 
10149 	/*
10150 	 * According to SAM-3, even if a device only supports a single
10151 	 * level of LUN addressing, it should still set the HISUP bit:
10152 	 *
10153 	 * 4.9.1 Logical unit numbers overview
10154 	 *
10155 	 * All logical unit number formats described in this standard are
10156 	 * hierarchical in structure even when only a single level in that
10157 	 * hierarchy is used. The HISUP bit shall be set to one in the
10158 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10159 	 * format described in this standard is used.  Non-hierarchical
10160 	 * formats are outside the scope of this standard.
10161 	 *
10162 	 * Therefore we set the HiSup bit here.
10163 	 *
10164 	 * The response format is 2, per SPC-3.
10165 	 */
10166 	inq_ptr->response_format = SID_HiSup | 2;
10167 
10168 	inq_ptr->additional_length = data_len -
10169 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10170 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10171 			 inq_ptr->additional_length));
10172 
10173 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10174 	if (port_type == CTL_PORT_SCSI)
10175 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10176 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10177 	inq_ptr->flags = SID_CmdQue;
10178 	if (port_type == CTL_PORT_SCSI)
10179 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10180 
10181 	/*
10182 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10183 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10184 	 * name and 4 bytes for the revision.
10185 	 */
10186 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10187 	    "vendor")) == NULL) {
10188 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10189 	} else {
10190 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10191 		strncpy(inq_ptr->vendor, val,
10192 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10193 	}
10194 	if (lun == NULL) {
10195 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10196 		    sizeof(inq_ptr->product));
10197 	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10198 		switch (lun->be_lun->lun_type) {
10199 		case T_DIRECT:
10200 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10201 			    sizeof(inq_ptr->product));
10202 			break;
10203 		case T_PROCESSOR:
10204 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10205 			    sizeof(inq_ptr->product));
10206 			break;
10207 		case T_CDROM:
10208 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10209 			    sizeof(inq_ptr->product));
10210 			break;
10211 		default:
10212 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10213 			    sizeof(inq_ptr->product));
10214 			break;
10215 		}
10216 	} else {
10217 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10218 		strncpy(inq_ptr->product, val,
10219 		    min(sizeof(inq_ptr->product), strlen(val)));
10220 	}
10221 
10222 	/*
10223 	 * XXX make this a macro somewhere so it automatically gets
10224 	 * incremented when we make changes.
10225 	 */
10226 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10227 	    "revision")) == NULL) {
10228 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10229 	} else {
10230 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10231 		strncpy(inq_ptr->revision, val,
10232 		    min(sizeof(inq_ptr->revision), strlen(val)));
10233 	}
10234 
10235 	/*
10236 	 * For parallel SCSI, we support double transition and single
10237 	 * transition clocking.  We also support QAS (Quick Arbitration
10238 	 * and Selection) and Information Unit transfers on both the
10239 	 * control and array devices.
10240 	 */
10241 	if (port_type == CTL_PORT_SCSI)
10242 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10243 				    SID_SPI_IUS;
10244 
10245 	/* SAM-6 (no version claimed) */
10246 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10247 	/* SPC-5 (no version claimed) */
10248 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10249 	if (port_type == CTL_PORT_FC) {
10250 		/* FCP-2 ANSI INCITS.350:2003 */
10251 		scsi_ulto2b(0x0917, inq_ptr->version3);
10252 	} else if (port_type == CTL_PORT_SCSI) {
10253 		/* SPI-4 ANSI INCITS.362:200x */
10254 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10255 	} else if (port_type == CTL_PORT_ISCSI) {
10256 		/* iSCSI (no version claimed) */
10257 		scsi_ulto2b(0x0960, inq_ptr->version3);
10258 	} else if (port_type == CTL_PORT_SAS) {
10259 		/* SAS (no version claimed) */
10260 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10261 	}
10262 
10263 	if (lun == NULL) {
10264 		/* SBC-4 (no version claimed) */
10265 		scsi_ulto2b(0x0600, inq_ptr->version4);
10266 	} else {
10267 		switch (lun->be_lun->lun_type) {
10268 		case T_DIRECT:
10269 			/* SBC-4 (no version claimed) */
10270 			scsi_ulto2b(0x0600, inq_ptr->version4);
10271 			break;
10272 		case T_PROCESSOR:
10273 			break;
10274 		case T_CDROM:
10275 			/* MMC-6 (no version claimed) */
10276 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10277 			break;
10278 		default:
10279 			break;
10280 		}
10281 	}
10282 
10283 	ctl_set_success(ctsio);
10284 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10285 	ctsio->be_move_done = ctl_config_move_done;
10286 	ctl_datamove((union ctl_io *)ctsio);
10287 	return (CTL_RETVAL_COMPLETE);
10288 }
10289 
10290 int
10291 ctl_inquiry(struct ctl_scsiio *ctsio)
10292 {
10293 	struct scsi_inquiry *cdb;
10294 	int retval;
10295 
10296 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10297 
10298 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10299 	if (cdb->byte2 & SI_EVPD)
10300 		retval = ctl_inquiry_evpd(ctsio);
10301 	else if (cdb->page_code == 0)
10302 		retval = ctl_inquiry_std(ctsio);
10303 	else {
10304 		ctl_set_invalid_field(ctsio,
10305 				      /*sks_valid*/ 1,
10306 				      /*command*/ 1,
10307 				      /*field*/ 2,
10308 				      /*bit_valid*/ 0,
10309 				      /*bit*/ 0);
10310 		ctl_done((union ctl_io *)ctsio);
10311 		return (CTL_RETVAL_COMPLETE);
10312 	}
10313 
10314 	return (retval);
10315 }
10316 
10317 int
10318 ctl_get_config(struct ctl_scsiio *ctsio)
10319 {
10320 	struct ctl_lun *lun = CTL_LUN(ctsio);
10321 	struct scsi_get_config_header *hdr;
10322 	struct scsi_get_config_feature *feature;
10323 	struct scsi_get_config *cdb;
10324 	uint32_t alloc_len, data_len;
10325 	int rt, starting;
10326 
10327 	cdb = (struct scsi_get_config *)ctsio->cdb;
10328 	rt = (cdb->rt & SGC_RT_MASK);
10329 	starting = scsi_2btoul(cdb->starting_feature);
10330 	alloc_len = scsi_2btoul(cdb->length);
10331 
10332 	data_len = sizeof(struct scsi_get_config_header) +
10333 	    sizeof(struct scsi_get_config_feature) + 8 +
10334 	    sizeof(struct scsi_get_config_feature) + 8 +
10335 	    sizeof(struct scsi_get_config_feature) + 4 +
10336 	    sizeof(struct scsi_get_config_feature) + 4 +
10337 	    sizeof(struct scsi_get_config_feature) + 8 +
10338 	    sizeof(struct scsi_get_config_feature) +
10339 	    sizeof(struct scsi_get_config_feature) + 4 +
10340 	    sizeof(struct scsi_get_config_feature) + 4 +
10341 	    sizeof(struct scsi_get_config_feature) + 4 +
10342 	    sizeof(struct scsi_get_config_feature) + 4 +
10343 	    sizeof(struct scsi_get_config_feature) + 4 +
10344 	    sizeof(struct scsi_get_config_feature) + 4;
10345 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10346 	ctsio->kern_sg_entries = 0;
10347 	ctsio->kern_rel_offset = 0;
10348 
10349 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10350 	if (lun->flags & CTL_LUN_NO_MEDIA)
10351 		scsi_ulto2b(0x0000, hdr->current_profile);
10352 	else
10353 		scsi_ulto2b(0x0010, hdr->current_profile);
10354 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10355 
10356 	if (starting > 0x003b)
10357 		goto done;
10358 	if (starting > 0x003a)
10359 		goto f3b;
10360 	if (starting > 0x002b)
10361 		goto f3a;
10362 	if (starting > 0x002a)
10363 		goto f2b;
10364 	if (starting > 0x001f)
10365 		goto f2a;
10366 	if (starting > 0x001e)
10367 		goto f1f;
10368 	if (starting > 0x001d)
10369 		goto f1e;
10370 	if (starting > 0x0010)
10371 		goto f1d;
10372 	if (starting > 0x0003)
10373 		goto f10;
10374 	if (starting > 0x0002)
10375 		goto f3;
10376 	if (starting > 0x0001)
10377 		goto f2;
10378 	if (starting > 0x0000)
10379 		goto f1;
10380 
10381 	/* Profile List */
10382 	scsi_ulto2b(0x0000, feature->feature_code);
10383 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10384 	feature->add_length = 8;
10385 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10386 	feature->feature_data[2] = 0x00;
10387 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10388 	feature->feature_data[6] = 0x01;
10389 	feature = (struct scsi_get_config_feature *)
10390 	    &feature->feature_data[feature->add_length];
10391 
10392 f1:	/* Core */
10393 	scsi_ulto2b(0x0001, feature->feature_code);
10394 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10395 	feature->add_length = 8;
10396 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10397 	feature->feature_data[4] = 0x03;
10398 	feature = (struct scsi_get_config_feature *)
10399 	    &feature->feature_data[feature->add_length];
10400 
10401 f2:	/* Morphing */
10402 	scsi_ulto2b(0x0002, feature->feature_code);
10403 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10404 	feature->add_length = 4;
10405 	feature->feature_data[0] = 0x02;
10406 	feature = (struct scsi_get_config_feature *)
10407 	    &feature->feature_data[feature->add_length];
10408 
10409 f3:	/* Removable Medium */
10410 	scsi_ulto2b(0x0003, feature->feature_code);
10411 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10412 	feature->add_length = 4;
10413 	feature->feature_data[0] = 0x39;
10414 	feature = (struct scsi_get_config_feature *)
10415 	    &feature->feature_data[feature->add_length];
10416 
10417 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10418 		goto done;
10419 
10420 f10:	/* Random Read */
10421 	scsi_ulto2b(0x0010, feature->feature_code);
10422 	feature->flags = 0x00;
10423 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10424 		feature->flags |= SGC_F_CURRENT;
10425 	feature->add_length = 8;
10426 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10427 	scsi_ulto2b(1, &feature->feature_data[4]);
10428 	feature->feature_data[6] = 0x00;
10429 	feature = (struct scsi_get_config_feature *)
10430 	    &feature->feature_data[feature->add_length];
10431 
10432 f1d:	/* Multi-Read */
10433 	scsi_ulto2b(0x001D, feature->feature_code);
10434 	feature->flags = 0x00;
10435 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10436 		feature->flags |= SGC_F_CURRENT;
10437 	feature->add_length = 0;
10438 	feature = (struct scsi_get_config_feature *)
10439 	    &feature->feature_data[feature->add_length];
10440 
10441 f1e:	/* CD Read */
10442 	scsi_ulto2b(0x001E, feature->feature_code);
10443 	feature->flags = 0x00;
10444 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10445 		feature->flags |= SGC_F_CURRENT;
10446 	feature->add_length = 4;
10447 	feature->feature_data[0] = 0x00;
10448 	feature = (struct scsi_get_config_feature *)
10449 	    &feature->feature_data[feature->add_length];
10450 
10451 f1f:	/* DVD Read */
10452 	scsi_ulto2b(0x001F, feature->feature_code);
10453 	feature->flags = 0x08;
10454 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10455 		feature->flags |= SGC_F_CURRENT;
10456 	feature->add_length = 4;
10457 	feature->feature_data[0] = 0x01;
10458 	feature->feature_data[2] = 0x03;
10459 	feature = (struct scsi_get_config_feature *)
10460 	    &feature->feature_data[feature->add_length];
10461 
10462 f2a:	/* DVD+RW */
10463 	scsi_ulto2b(0x002A, feature->feature_code);
10464 	feature->flags = 0x04;
10465 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10466 		feature->flags |= SGC_F_CURRENT;
10467 	feature->add_length = 4;
10468 	feature->feature_data[0] = 0x00;
10469 	feature->feature_data[1] = 0x00;
10470 	feature = (struct scsi_get_config_feature *)
10471 	    &feature->feature_data[feature->add_length];
10472 
10473 f2b:	/* DVD+R */
10474 	scsi_ulto2b(0x002B, feature->feature_code);
10475 	feature->flags = 0x00;
10476 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10477 		feature->flags |= SGC_F_CURRENT;
10478 	feature->add_length = 4;
10479 	feature->feature_data[0] = 0x00;
10480 	feature = (struct scsi_get_config_feature *)
10481 	    &feature->feature_data[feature->add_length];
10482 
10483 f3a:	/* DVD+RW Dual Layer */
10484 	scsi_ulto2b(0x003A, feature->feature_code);
10485 	feature->flags = 0x00;
10486 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10487 		feature->flags |= SGC_F_CURRENT;
10488 	feature->add_length = 4;
10489 	feature->feature_data[0] = 0x00;
10490 	feature->feature_data[1] = 0x00;
10491 	feature = (struct scsi_get_config_feature *)
10492 	    &feature->feature_data[feature->add_length];
10493 
10494 f3b:	/* DVD+R Dual Layer */
10495 	scsi_ulto2b(0x003B, feature->feature_code);
10496 	feature->flags = 0x00;
10497 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10498 		feature->flags |= SGC_F_CURRENT;
10499 	feature->add_length = 4;
10500 	feature->feature_data[0] = 0x00;
10501 	feature = (struct scsi_get_config_feature *)
10502 	    &feature->feature_data[feature->add_length];
10503 
10504 done:
10505 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10506 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10507 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10508 		if (scsi_2btoul(feature->feature_code) == starting)
10509 			feature = (struct scsi_get_config_feature *)
10510 			    &feature->feature_data[feature->add_length];
10511 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10512 	}
10513 	scsi_ulto4b(data_len - 4, hdr->data_length);
10514 	if (data_len < alloc_len) {
10515 		ctsio->residual = alloc_len - data_len;
10516 		ctsio->kern_data_len = data_len;
10517 		ctsio->kern_total_len = data_len;
10518 	} else {
10519 		ctsio->residual = 0;
10520 		ctsio->kern_data_len = alloc_len;
10521 		ctsio->kern_total_len = alloc_len;
10522 	}
10523 
10524 	ctl_set_success(ctsio);
10525 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10526 	ctsio->be_move_done = ctl_config_move_done;
10527 	ctl_datamove((union ctl_io *)ctsio);
10528 	return (CTL_RETVAL_COMPLETE);
10529 }
10530 
10531 int
10532 ctl_get_event_status(struct ctl_scsiio *ctsio)
10533 {
10534 	struct scsi_get_event_status_header *hdr;
10535 	struct scsi_get_event_status *cdb;
10536 	uint32_t alloc_len, data_len;
10537 	int notif_class;
10538 
10539 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10540 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10541 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10542 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10543 		ctl_done((union ctl_io *)ctsio);
10544 		return (CTL_RETVAL_COMPLETE);
10545 	}
10546 	notif_class = cdb->notif_class;
10547 	alloc_len = scsi_2btoul(cdb->length);
10548 
10549 	data_len = sizeof(struct scsi_get_event_status_header);
10550 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10551 	ctsio->kern_sg_entries = 0;
10552 	ctsio->kern_rel_offset = 0;
10553 
10554 	if (data_len < alloc_len) {
10555 		ctsio->residual = alloc_len - data_len;
10556 		ctsio->kern_data_len = data_len;
10557 		ctsio->kern_total_len = data_len;
10558 	} else {
10559 		ctsio->residual = 0;
10560 		ctsio->kern_data_len = alloc_len;
10561 		ctsio->kern_total_len = alloc_len;
10562 	}
10563 
10564 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10565 	scsi_ulto2b(0, hdr->descr_length);
10566 	hdr->nea_class = SGESN_NEA;
10567 	hdr->supported_class = 0;
10568 
10569 	ctl_set_success(ctsio);
10570 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10571 	ctsio->be_move_done = ctl_config_move_done;
10572 	ctl_datamove((union ctl_io *)ctsio);
10573 	return (CTL_RETVAL_COMPLETE);
10574 }
10575 
10576 int
10577 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10578 {
10579 	struct scsi_mechanism_status_header *hdr;
10580 	struct scsi_mechanism_status *cdb;
10581 	uint32_t alloc_len, data_len;
10582 
10583 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10584 	alloc_len = scsi_2btoul(cdb->length);
10585 
10586 	data_len = sizeof(struct scsi_mechanism_status_header);
10587 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10588 	ctsio->kern_sg_entries = 0;
10589 	ctsio->kern_rel_offset = 0;
10590 
10591 	if (data_len < alloc_len) {
10592 		ctsio->residual = alloc_len - data_len;
10593 		ctsio->kern_data_len = data_len;
10594 		ctsio->kern_total_len = data_len;
10595 	} else {
10596 		ctsio->residual = 0;
10597 		ctsio->kern_data_len = alloc_len;
10598 		ctsio->kern_total_len = alloc_len;
10599 	}
10600 
10601 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10602 	hdr->state1 = 0x00;
10603 	hdr->state2 = 0xe0;
10604 	scsi_ulto3b(0, hdr->lba);
10605 	hdr->slots_num = 0;
10606 	scsi_ulto2b(0, hdr->slots_length);
10607 
10608 	ctl_set_success(ctsio);
10609 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10610 	ctsio->be_move_done = ctl_config_move_done;
10611 	ctl_datamove((union ctl_io *)ctsio);
10612 	return (CTL_RETVAL_COMPLETE);
10613 }
10614 
10615 static void
10616 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10617 {
10618 
10619 	lba += 150;
10620 	buf[0] = 0;
10621 	buf[1] = bin2bcd((lba / 75) / 60);
10622 	buf[2] = bin2bcd((lba / 75) % 60);
10623 	buf[3] = bin2bcd(lba % 75);
10624 }
10625 
10626 int
10627 ctl_read_toc(struct ctl_scsiio *ctsio)
10628 {
10629 	struct ctl_lun *lun = CTL_LUN(ctsio);
10630 	struct scsi_read_toc_hdr *hdr;
10631 	struct scsi_read_toc_type01_descr *descr;
10632 	struct scsi_read_toc *cdb;
10633 	uint32_t alloc_len, data_len;
10634 	int format, msf;
10635 
10636 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10637 	msf = (cdb->byte2 & CD_MSF) != 0;
10638 	format = cdb->format;
10639 	alloc_len = scsi_2btoul(cdb->data_len);
10640 
10641 	data_len = sizeof(struct scsi_read_toc_hdr);
10642 	if (format == 0)
10643 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10644 	else
10645 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10646 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10647 	ctsio->kern_sg_entries = 0;
10648 	ctsio->kern_rel_offset = 0;
10649 
10650 	if (data_len < alloc_len) {
10651 		ctsio->residual = alloc_len - data_len;
10652 		ctsio->kern_data_len = data_len;
10653 		ctsio->kern_total_len = data_len;
10654 	} else {
10655 		ctsio->residual = 0;
10656 		ctsio->kern_data_len = alloc_len;
10657 		ctsio->kern_total_len = alloc_len;
10658 	}
10659 
10660 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10661 	if (format == 0) {
10662 		scsi_ulto2b(0x12, hdr->data_length);
10663 		hdr->first = 1;
10664 		hdr->last = 1;
10665 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10666 		descr->addr_ctl = 0x14;
10667 		descr->track_number = 1;
10668 		if (msf)
10669 			ctl_ultomsf(0, descr->track_start);
10670 		else
10671 			scsi_ulto4b(0, descr->track_start);
10672 		descr++;
10673 		descr->addr_ctl = 0x14;
10674 		descr->track_number = 0xaa;
10675 		if (msf)
10676 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10677 		else
10678 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10679 	} else {
10680 		scsi_ulto2b(0x0a, hdr->data_length);
10681 		hdr->first = 1;
10682 		hdr->last = 1;
10683 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10684 		descr->addr_ctl = 0x14;
10685 		descr->track_number = 1;
10686 		if (msf)
10687 			ctl_ultomsf(0, descr->track_start);
10688 		else
10689 			scsi_ulto4b(0, descr->track_start);
10690 	}
10691 
10692 	ctl_set_success(ctsio);
10693 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10694 	ctsio->be_move_done = ctl_config_move_done;
10695 	ctl_datamove((union ctl_io *)ctsio);
10696 	return (CTL_RETVAL_COMPLETE);
10697 }
10698 
10699 /*
10700  * For known CDB types, parse the LBA and length.
10701  */
10702 static int
10703 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10704 {
10705 	if (io->io_hdr.io_type != CTL_IO_SCSI)
10706 		return (1);
10707 
10708 	switch (io->scsiio.cdb[0]) {
10709 	case COMPARE_AND_WRITE: {
10710 		struct scsi_compare_and_write *cdb;
10711 
10712 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10713 
10714 		*lba = scsi_8btou64(cdb->addr);
10715 		*len = cdb->length;
10716 		break;
10717 	}
10718 	case READ_6:
10719 	case WRITE_6: {
10720 		struct scsi_rw_6 *cdb;
10721 
10722 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10723 
10724 		*lba = scsi_3btoul(cdb->addr);
10725 		/* only 5 bits are valid in the most significant address byte */
10726 		*lba &= 0x1fffff;
10727 		*len = cdb->length;
10728 		break;
10729 	}
10730 	case READ_10:
10731 	case WRITE_10: {
10732 		struct scsi_rw_10 *cdb;
10733 
10734 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10735 
10736 		*lba = scsi_4btoul(cdb->addr);
10737 		*len = scsi_2btoul(cdb->length);
10738 		break;
10739 	}
10740 	case WRITE_VERIFY_10: {
10741 		struct scsi_write_verify_10 *cdb;
10742 
10743 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10744 
10745 		*lba = scsi_4btoul(cdb->addr);
10746 		*len = scsi_2btoul(cdb->length);
10747 		break;
10748 	}
10749 	case READ_12:
10750 	case WRITE_12: {
10751 		struct scsi_rw_12 *cdb;
10752 
10753 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10754 
10755 		*lba = scsi_4btoul(cdb->addr);
10756 		*len = scsi_4btoul(cdb->length);
10757 		break;
10758 	}
10759 	case WRITE_VERIFY_12: {
10760 		struct scsi_write_verify_12 *cdb;
10761 
10762 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10763 
10764 		*lba = scsi_4btoul(cdb->addr);
10765 		*len = scsi_4btoul(cdb->length);
10766 		break;
10767 	}
10768 	case READ_16:
10769 	case WRITE_16: {
10770 		struct scsi_rw_16 *cdb;
10771 
10772 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10773 
10774 		*lba = scsi_8btou64(cdb->addr);
10775 		*len = scsi_4btoul(cdb->length);
10776 		break;
10777 	}
10778 	case WRITE_ATOMIC_16: {
10779 		struct scsi_write_atomic_16 *cdb;
10780 
10781 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10782 
10783 		*lba = scsi_8btou64(cdb->addr);
10784 		*len = scsi_2btoul(cdb->length);
10785 		break;
10786 	}
10787 	case WRITE_VERIFY_16: {
10788 		struct scsi_write_verify_16 *cdb;
10789 
10790 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10791 
10792 		*lba = scsi_8btou64(cdb->addr);
10793 		*len = scsi_4btoul(cdb->length);
10794 		break;
10795 	}
10796 	case WRITE_SAME_10: {
10797 		struct scsi_write_same_10 *cdb;
10798 
10799 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10800 
10801 		*lba = scsi_4btoul(cdb->addr);
10802 		*len = scsi_2btoul(cdb->length);
10803 		break;
10804 	}
10805 	case WRITE_SAME_16: {
10806 		struct scsi_write_same_16 *cdb;
10807 
10808 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10809 
10810 		*lba = scsi_8btou64(cdb->addr);
10811 		*len = scsi_4btoul(cdb->length);
10812 		break;
10813 	}
10814 	case VERIFY_10: {
10815 		struct scsi_verify_10 *cdb;
10816 
10817 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10818 
10819 		*lba = scsi_4btoul(cdb->addr);
10820 		*len = scsi_2btoul(cdb->length);
10821 		break;
10822 	}
10823 	case VERIFY_12: {
10824 		struct scsi_verify_12 *cdb;
10825 
10826 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10827 
10828 		*lba = scsi_4btoul(cdb->addr);
10829 		*len = scsi_4btoul(cdb->length);
10830 		break;
10831 	}
10832 	case VERIFY_16: {
10833 		struct scsi_verify_16 *cdb;
10834 
10835 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10836 
10837 		*lba = scsi_8btou64(cdb->addr);
10838 		*len = scsi_4btoul(cdb->length);
10839 		break;
10840 	}
10841 	case UNMAP: {
10842 		*lba = 0;
10843 		*len = UINT64_MAX;
10844 		break;
10845 	}
10846 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10847 		struct scsi_get_lba_status *cdb;
10848 
10849 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10850 		*lba = scsi_8btou64(cdb->addr);
10851 		*len = UINT32_MAX;
10852 		break;
10853 	}
10854 	default:
10855 		return (1);
10856 		break; /* NOTREACHED */
10857 	}
10858 
10859 	return (0);
10860 }
10861 
10862 static ctl_action
10863 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10864     bool seq)
10865 {
10866 	uint64_t endlba1, endlba2;
10867 
10868 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10869 	endlba2 = lba2 + len2 - 1;
10870 
10871 	if ((endlba1 < lba2) || (endlba2 < lba1))
10872 		return (CTL_ACTION_PASS);
10873 	else
10874 		return (CTL_ACTION_BLOCK);
10875 }
10876 
10877 static int
10878 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10879 {
10880 	struct ctl_ptr_len_flags *ptrlen;
10881 	struct scsi_unmap_desc *buf, *end, *range;
10882 	uint64_t lba;
10883 	uint32_t len;
10884 
10885 	/* If not UNMAP -- go other way. */
10886 	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10887 	    io->scsiio.cdb[0] != UNMAP)
10888 		return (CTL_ACTION_ERROR);
10889 
10890 	/* If UNMAP without data -- block and wait for data. */
10891 	ptrlen = (struct ctl_ptr_len_flags *)
10892 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10893 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10894 	    ptrlen->ptr == NULL)
10895 		return (CTL_ACTION_BLOCK);
10896 
10897 	/* UNMAP with data -- check for collision. */
10898 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10899 	end = buf + ptrlen->len / sizeof(*buf);
10900 	for (range = buf; range < end; range++) {
10901 		lba = scsi_8btou64(range->lba);
10902 		len = scsi_4btoul(range->length);
10903 		if ((lba < lba2 + len2) && (lba + len > lba2))
10904 			return (CTL_ACTION_BLOCK);
10905 	}
10906 	return (CTL_ACTION_PASS);
10907 }
10908 
10909 static ctl_action
10910 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10911 {
10912 	uint64_t lba1, lba2;
10913 	uint64_t len1, len2;
10914 	int retval;
10915 
10916 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10917 		return (CTL_ACTION_ERROR);
10918 
10919 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10920 	if (retval != CTL_ACTION_ERROR)
10921 		return (retval);
10922 
10923 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10924 		return (CTL_ACTION_ERROR);
10925 
10926 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10927 		seq = FALSE;
10928 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10929 }
10930 
10931 static ctl_action
10932 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10933 {
10934 	uint64_t lba1, lba2;
10935 	uint64_t len1, len2;
10936 
10937 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10938 		return (CTL_ACTION_PASS);
10939 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10940 		return (CTL_ACTION_ERROR);
10941 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10942 		return (CTL_ACTION_ERROR);
10943 
10944 	if (lba1 + len1 == lba2)
10945 		return (CTL_ACTION_BLOCK);
10946 	return (CTL_ACTION_PASS);
10947 }
10948 
10949 static ctl_action
10950 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10951     union ctl_io *ooa_io)
10952 {
10953 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10954 	const ctl_serialize_action *serialize_row;
10955 
10956 	/*
10957 	 * The initiator attempted multiple untagged commands at the same
10958 	 * time.  Can't do that.
10959 	 */
10960 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10961 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10962 	 && ((pending_io->io_hdr.nexus.targ_port ==
10963 	      ooa_io->io_hdr.nexus.targ_port)
10964 	  && (pending_io->io_hdr.nexus.initid ==
10965 	      ooa_io->io_hdr.nexus.initid))
10966 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10967 	      CTL_FLAG_STATUS_SENT)) == 0))
10968 		return (CTL_ACTION_OVERLAP);
10969 
10970 	/*
10971 	 * The initiator attempted to send multiple tagged commands with
10972 	 * the same ID.  (It's fine if different initiators have the same
10973 	 * tag ID.)
10974 	 *
10975 	 * Even if all of those conditions are true, we don't kill the I/O
10976 	 * if the command ahead of us has been aborted.  We won't end up
10977 	 * sending it to the FETD, and it's perfectly legal to resend a
10978 	 * command with the same tag number as long as the previous
10979 	 * instance of this tag number has been aborted somehow.
10980 	 */
10981 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10982 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10983 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10984 	 && ((pending_io->io_hdr.nexus.targ_port ==
10985 	      ooa_io->io_hdr.nexus.targ_port)
10986 	  && (pending_io->io_hdr.nexus.initid ==
10987 	      ooa_io->io_hdr.nexus.initid))
10988 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10989 	      CTL_FLAG_STATUS_SENT)) == 0))
10990 		return (CTL_ACTION_OVERLAP_TAG);
10991 
10992 	/*
10993 	 * If we get a head of queue tag, SAM-3 says that we should
10994 	 * immediately execute it.
10995 	 *
10996 	 * What happens if this command would normally block for some other
10997 	 * reason?  e.g. a request sense with a head of queue tag
10998 	 * immediately after a write.  Normally that would block, but this
10999 	 * will result in its getting executed immediately...
11000 	 *
11001 	 * We currently return "pass" instead of "skip", so we'll end up
11002 	 * going through the rest of the queue to check for overlapped tags.
11003 	 *
11004 	 * XXX KDM check for other types of blockage first??
11005 	 */
11006 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11007 		return (CTL_ACTION_PASS);
11008 
11009 	/*
11010 	 * Ordered tags have to block until all items ahead of them
11011 	 * have completed.  If we get called with an ordered tag, we always
11012 	 * block, if something else is ahead of us in the queue.
11013 	 */
11014 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11015 		return (CTL_ACTION_BLOCK);
11016 
11017 	/*
11018 	 * Simple tags get blocked until all head of queue and ordered tags
11019 	 * ahead of them have completed.  I'm lumping untagged commands in
11020 	 * with simple tags here.  XXX KDM is that the right thing to do?
11021 	 */
11022 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11023 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11024 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11025 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11026 		return (CTL_ACTION_BLOCK);
11027 
11028 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11029 	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11030 	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11031 	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11032 	     pending_io->scsiio.cdb[1], pending_io));
11033 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11034 	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11035 		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11036 	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11037 	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11038 	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11039 	     ooa_io->scsiio.cdb[1], ooa_io));
11040 
11041 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11042 
11043 	switch (serialize_row[pending_entry->seridx]) {
11044 	case CTL_SER_BLOCK:
11045 		return (CTL_ACTION_BLOCK);
11046 	case CTL_SER_EXTENT:
11047 		return (ctl_extent_check(ooa_io, pending_io,
11048 		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11049 	case CTL_SER_EXTENTOPT:
11050 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11051 		    SCP_QUEUE_ALG_UNRESTRICTED)
11052 			return (ctl_extent_check(ooa_io, pending_io,
11053 			    (lun->be_lun &&
11054 			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11055 		return (CTL_ACTION_PASS);
11056 	case CTL_SER_EXTENTSEQ:
11057 		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11058 			return (ctl_extent_check_seq(ooa_io, pending_io));
11059 		return (CTL_ACTION_PASS);
11060 	case CTL_SER_PASS:
11061 		return (CTL_ACTION_PASS);
11062 	case CTL_SER_BLOCKOPT:
11063 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11064 		    SCP_QUEUE_ALG_UNRESTRICTED)
11065 			return (CTL_ACTION_BLOCK);
11066 		return (CTL_ACTION_PASS);
11067 	case CTL_SER_SKIP:
11068 		return (CTL_ACTION_SKIP);
11069 	default:
11070 		panic("%s: Invalid serialization value %d for %d => %d",
11071 		    __func__, serialize_row[pending_entry->seridx],
11072 		    pending_entry->seridx, ooa_entry->seridx);
11073 	}
11074 
11075 	return (CTL_ACTION_ERROR);
11076 }
11077 
11078 /*
11079  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11080  * Assumptions:
11081  * - pending_io is generally either incoming, or on the blocked queue
11082  * - starting I/O is the I/O we want to start the check with.
11083  */
11084 static ctl_action
11085 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11086 	      union ctl_io *starting_io)
11087 {
11088 	union ctl_io *ooa_io;
11089 	ctl_action action;
11090 
11091 	mtx_assert(&lun->lun_lock, MA_OWNED);
11092 
11093 	/*
11094 	 * Run back along the OOA queue, starting with the current
11095 	 * blocked I/O and going through every I/O before it on the
11096 	 * queue.  If starting_io is NULL, we'll just end up returning
11097 	 * CTL_ACTION_PASS.
11098 	 */
11099 	for (ooa_io = starting_io; ooa_io != NULL;
11100 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11101 	     ooa_links)){
11102 
11103 		/*
11104 		 * This routine just checks to see whether
11105 		 * cur_blocked is blocked by ooa_io, which is ahead
11106 		 * of it in the queue.  It doesn't queue/dequeue
11107 		 * cur_blocked.
11108 		 */
11109 		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11110 		switch (action) {
11111 		case CTL_ACTION_BLOCK:
11112 		case CTL_ACTION_OVERLAP:
11113 		case CTL_ACTION_OVERLAP_TAG:
11114 		case CTL_ACTION_SKIP:
11115 		case CTL_ACTION_ERROR:
11116 			return (action);
11117 			break; /* NOTREACHED */
11118 		case CTL_ACTION_PASS:
11119 			break;
11120 		default:
11121 			panic("%s: Invalid action %d\n", __func__, action);
11122 		}
11123 	}
11124 
11125 	return (CTL_ACTION_PASS);
11126 }
11127 
11128 /*
11129  * Assumptions:
11130  * - An I/O has just completed, and has been removed from the per-LUN OOA
11131  *   queue, so some items on the blocked queue may now be unblocked.
11132  */
11133 static int
11134 ctl_check_blocked(struct ctl_lun *lun)
11135 {
11136 	struct ctl_softc *softc = lun->ctl_softc;
11137 	union ctl_io *cur_blocked, *next_blocked;
11138 
11139 	mtx_assert(&lun->lun_lock, MA_OWNED);
11140 
11141 	/*
11142 	 * Run forward from the head of the blocked queue, checking each
11143 	 * entry against the I/Os prior to it on the OOA queue to see if
11144 	 * there is still any blockage.
11145 	 *
11146 	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11147 	 * with our removing a variable on it while it is traversing the
11148 	 * list.
11149 	 */
11150 	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11151 	     cur_blocked != NULL; cur_blocked = next_blocked) {
11152 		union ctl_io *prev_ooa;
11153 		ctl_action action;
11154 
11155 		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11156 							  blocked_links);
11157 
11158 		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11159 						      ctl_ooaq, ooa_links);
11160 
11161 		/*
11162 		 * If cur_blocked happens to be the first item in the OOA
11163 		 * queue now, prev_ooa will be NULL, and the action
11164 		 * returned will just be CTL_ACTION_PASS.
11165 		 */
11166 		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11167 
11168 		switch (action) {
11169 		case CTL_ACTION_BLOCK:
11170 			/* Nothing to do here, still blocked */
11171 			break;
11172 		case CTL_ACTION_OVERLAP:
11173 		case CTL_ACTION_OVERLAP_TAG:
11174 			/*
11175 			 * This shouldn't happen!  In theory we've already
11176 			 * checked this command for overlap...
11177 			 */
11178 			break;
11179 		case CTL_ACTION_PASS:
11180 		case CTL_ACTION_SKIP: {
11181 			const struct ctl_cmd_entry *entry;
11182 
11183 			/*
11184 			 * The skip case shouldn't happen, this transaction
11185 			 * should have never made it onto the blocked queue.
11186 			 */
11187 			/*
11188 			 * This I/O is no longer blocked, we can remove it
11189 			 * from the blocked queue.  Since this is a TAILQ
11190 			 * (doubly linked list), we can do O(1) removals
11191 			 * from any place on the list.
11192 			 */
11193 			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11194 				     blocked_links);
11195 			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11196 
11197 			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11198 			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11199 				/*
11200 				 * Need to send IO back to original side to
11201 				 * run
11202 				 */
11203 				union ctl_ha_msg msg_info;
11204 
11205 				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11206 				msg_info.hdr.original_sc =
11207 					cur_blocked->io_hdr.original_sc;
11208 				msg_info.hdr.serializing_sc = cur_blocked;
11209 				msg_info.hdr.msg_type = CTL_MSG_R2R;
11210 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11211 				    sizeof(msg_info.hdr), M_NOWAIT);
11212 				break;
11213 			}
11214 			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11215 
11216 			/*
11217 			 * Check this I/O for LUN state changes that may
11218 			 * have happened while this command was blocked.
11219 			 * The LUN state may have been changed by a command
11220 			 * ahead of us in the queue, so we need to re-check
11221 			 * for any states that can be caused by SCSI
11222 			 * commands.
11223 			 */
11224 			if (ctl_scsiio_lun_check(lun, entry,
11225 						 &cur_blocked->scsiio) == 0) {
11226 				cur_blocked->io_hdr.flags |=
11227 				                      CTL_FLAG_IS_WAS_ON_RTR;
11228 				ctl_enqueue_rtr(cur_blocked);
11229 			} else
11230 				ctl_done(cur_blocked);
11231 			break;
11232 		}
11233 		default:
11234 			/*
11235 			 * This probably shouldn't happen -- we shouldn't
11236 			 * get CTL_ACTION_ERROR, or anything else.
11237 			 */
11238 			break;
11239 		}
11240 	}
11241 
11242 	return (CTL_RETVAL_COMPLETE);
11243 }
11244 
11245 /*
11246  * This routine (with one exception) checks LUN flags that can be set by
11247  * commands ahead of us in the OOA queue.  These flags have to be checked
11248  * when a command initially comes in, and when we pull a command off the
11249  * blocked queue and are preparing to execute it.  The reason we have to
11250  * check these flags for commands on the blocked queue is that the LUN
11251  * state may have been changed by a command ahead of us while we're on the
11252  * blocked queue.
11253  *
11254  * Ordering is somewhat important with these checks, so please pay
11255  * careful attention to the placement of any new checks.
11256  */
11257 static int
11258 ctl_scsiio_lun_check(struct ctl_lun *lun,
11259     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11260 {
11261 	struct ctl_softc *softc = lun->ctl_softc;
11262 	int retval;
11263 	uint32_t residx;
11264 
11265 	retval = 0;
11266 
11267 	mtx_assert(&lun->lun_lock, MA_OWNED);
11268 
11269 	/*
11270 	 * If this shelf is a secondary shelf controller, we may have to
11271 	 * reject some commands disallowed by HA mode and link state.
11272 	 */
11273 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11274 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11275 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11276 			ctl_set_lun_unavail(ctsio);
11277 			retval = 1;
11278 			goto bailout;
11279 		}
11280 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11281 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11282 			ctl_set_lun_transit(ctsio);
11283 			retval = 1;
11284 			goto bailout;
11285 		}
11286 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11287 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11288 			ctl_set_lun_standby(ctsio);
11289 			retval = 1;
11290 			goto bailout;
11291 		}
11292 
11293 		/* The rest of checks are only done on executing side */
11294 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11295 			goto bailout;
11296 	}
11297 
11298 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11299 		if (lun->be_lun &&
11300 		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11301 			ctl_set_hw_write_protected(ctsio);
11302 			retval = 1;
11303 			goto bailout;
11304 		}
11305 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11306 			ctl_set_sense(ctsio, /*current_error*/ 1,
11307 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11308 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11309 			retval = 1;
11310 			goto bailout;
11311 		}
11312 	}
11313 
11314 	/*
11315 	 * Check for a reservation conflict.  If this command isn't allowed
11316 	 * even on reserved LUNs, and if this initiator isn't the one who
11317 	 * reserved us, reject the command with a reservation conflict.
11318 	 */
11319 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11320 	if ((lun->flags & CTL_LUN_RESERVED)
11321 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11322 		if (lun->res_idx != residx) {
11323 			ctl_set_reservation_conflict(ctsio);
11324 			retval = 1;
11325 			goto bailout;
11326 		}
11327 	}
11328 
11329 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11330 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11331 		/* No reservation or command is allowed. */;
11332 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11333 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11334 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11335 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11336 		/* The command is allowed for Write Exclusive resv. */;
11337 	} else {
11338 		/*
11339 		 * if we aren't registered or it's a res holder type
11340 		 * reservation and this isn't the res holder then set a
11341 		 * conflict.
11342 		 */
11343 		if (ctl_get_prkey(lun, residx) == 0 ||
11344 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11345 			ctl_set_reservation_conflict(ctsio);
11346 			retval = 1;
11347 			goto bailout;
11348 		}
11349 	}
11350 
11351 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11352 		if (lun->flags & CTL_LUN_EJECTED)
11353 			ctl_set_lun_ejected(ctsio);
11354 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11355 			if (lun->flags & CTL_LUN_REMOVABLE)
11356 				ctl_set_lun_no_media(ctsio);
11357 			else
11358 				ctl_set_lun_int_reqd(ctsio);
11359 		} else if (lun->flags & CTL_LUN_STOPPED)
11360 			ctl_set_lun_stopped(ctsio);
11361 		else
11362 			goto bailout;
11363 		retval = 1;
11364 		goto bailout;
11365 	}
11366 
11367 bailout:
11368 	return (retval);
11369 }
11370 
11371 static void
11372 ctl_failover_io(union ctl_io *io, int have_lock)
11373 {
11374 	ctl_set_busy(&io->scsiio);
11375 	ctl_done(io);
11376 }
11377 
11378 static void
11379 ctl_failover_lun(union ctl_io *rio)
11380 {
11381 	struct ctl_softc *softc = CTL_SOFTC(rio);
11382 	struct ctl_lun *lun;
11383 	struct ctl_io_hdr *io, *next_io;
11384 	uint32_t targ_lun;
11385 
11386 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11387 	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11388 
11389 	/* Find and lock the LUN. */
11390 	mtx_lock(&softc->ctl_lock);
11391 	if (targ_lun > CTL_MAX_LUNS ||
11392 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11393 		mtx_unlock(&softc->ctl_lock);
11394 		return;
11395 	}
11396 	mtx_lock(&lun->lun_lock);
11397 	mtx_unlock(&softc->ctl_lock);
11398 	if (lun->flags & CTL_LUN_DISABLED) {
11399 		mtx_unlock(&lun->lun_lock);
11400 		return;
11401 	}
11402 
11403 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11404 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11405 			/* We are master */
11406 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11407 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11408 					io->flags |= CTL_FLAG_ABORT;
11409 					io->flags |= CTL_FLAG_FAILOVER;
11410 				} else { /* This can be only due to DATAMOVE */
11411 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11412 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11413 					io->flags |= CTL_FLAG_IO_ACTIVE;
11414 					io->port_status = 31340;
11415 					ctl_enqueue_isc((union ctl_io *)io);
11416 				}
11417 			}
11418 			/* We are slave */
11419 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11420 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11421 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11422 					io->flags |= CTL_FLAG_FAILOVER;
11423 				} else {
11424 					ctl_set_busy(&((union ctl_io *)io)->
11425 					    scsiio);
11426 					ctl_done((union ctl_io *)io);
11427 				}
11428 			}
11429 		}
11430 	} else { /* SERIALIZE modes */
11431 		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11432 		    next_io) {
11433 			/* We are master */
11434 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11435 				TAILQ_REMOVE(&lun->blocked_queue, io,
11436 				    blocked_links);
11437 				io->flags &= ~CTL_FLAG_BLOCKED;
11438 				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11439 				ctl_free_io((union ctl_io *)io);
11440 			}
11441 		}
11442 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11443 			/* We are master */
11444 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11445 				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11446 				ctl_free_io((union ctl_io *)io);
11447 			}
11448 			/* We are slave */
11449 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11450 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11451 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11452 					ctl_set_busy(&((union ctl_io *)io)->
11453 					    scsiio);
11454 					ctl_done((union ctl_io *)io);
11455 				}
11456 			}
11457 		}
11458 		ctl_check_blocked(lun);
11459 	}
11460 	mtx_unlock(&lun->lun_lock);
11461 }
11462 
11463 static int
11464 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11465 {
11466 	struct ctl_lun *lun;
11467 	const struct ctl_cmd_entry *entry;
11468 	uint32_t initidx, targ_lun;
11469 	int retval = 0;
11470 
11471 	lun = NULL;
11472 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11473 	if (targ_lun < CTL_MAX_LUNS)
11474 		lun = softc->ctl_luns[targ_lun];
11475 	if (lun) {
11476 		/*
11477 		 * If the LUN is invalid, pretend that it doesn't exist.
11478 		 * It will go away as soon as all pending I/O has been
11479 		 * completed.
11480 		 */
11481 		mtx_lock(&lun->lun_lock);
11482 		if (lun->flags & CTL_LUN_DISABLED) {
11483 			mtx_unlock(&lun->lun_lock);
11484 			lun = NULL;
11485 		}
11486 	}
11487 	CTL_LUN(ctsio) = lun;
11488 	if (lun) {
11489 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11490 
11491 		/*
11492 		 * Every I/O goes into the OOA queue for a particular LUN,
11493 		 * and stays there until completion.
11494 		 */
11495 #ifdef CTL_TIME_IO
11496 		if (TAILQ_EMPTY(&lun->ooa_queue))
11497 			lun->idle_time += getsbinuptime() - lun->last_busy;
11498 #endif
11499 		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11500 	}
11501 
11502 	/* Get command entry and return error if it is unsuppotyed. */
11503 	entry = ctl_validate_command(ctsio);
11504 	if (entry == NULL) {
11505 		if (lun)
11506 			mtx_unlock(&lun->lun_lock);
11507 		return (retval);
11508 	}
11509 
11510 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11511 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11512 
11513 	/*
11514 	 * Check to see whether we can send this command to LUNs that don't
11515 	 * exist.  This should pretty much only be the case for inquiry
11516 	 * and request sense.  Further checks, below, really require having
11517 	 * a LUN, so we can't really check the command anymore.  Just put
11518 	 * it on the rtr queue.
11519 	 */
11520 	if (lun == NULL) {
11521 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11522 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11523 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11524 			return (retval);
11525 		}
11526 
11527 		ctl_set_unsupported_lun(ctsio);
11528 		ctl_done((union ctl_io *)ctsio);
11529 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11530 		return (retval);
11531 	} else {
11532 		/*
11533 		 * Make sure we support this particular command on this LUN.
11534 		 * e.g., we don't support writes to the control LUN.
11535 		 */
11536 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11537 			mtx_unlock(&lun->lun_lock);
11538 			ctl_set_invalid_opcode(ctsio);
11539 			ctl_done((union ctl_io *)ctsio);
11540 			return (retval);
11541 		}
11542 	}
11543 
11544 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11545 
11546 #ifdef CTL_WITH_CA
11547 	/*
11548 	 * If we've got a request sense, it'll clear the contingent
11549 	 * allegiance condition.  Otherwise, if we have a CA condition for
11550 	 * this initiator, clear it, because it sent down a command other
11551 	 * than request sense.
11552 	 */
11553 	if ((ctsio->cdb[0] != REQUEST_SENSE)
11554 	 && (ctl_is_set(lun->have_ca, initidx)))
11555 		ctl_clear_mask(lun->have_ca, initidx);
11556 #endif
11557 
11558 	/*
11559 	 * If the command has this flag set, it handles its own unit
11560 	 * attention reporting, we shouldn't do anything.  Otherwise we
11561 	 * check for any pending unit attentions, and send them back to the
11562 	 * initiator.  We only do this when a command initially comes in,
11563 	 * not when we pull it off the blocked queue.
11564 	 *
11565 	 * According to SAM-3, section 5.3.2, the order that things get
11566 	 * presented back to the host is basically unit attentions caused
11567 	 * by some sort of reset event, busy status, reservation conflicts
11568 	 * or task set full, and finally any other status.
11569 	 *
11570 	 * One issue here is that some of the unit attentions we report
11571 	 * don't fall into the "reset" category (e.g. "reported luns data
11572 	 * has changed").  So reporting it here, before the reservation
11573 	 * check, may be technically wrong.  I guess the only thing to do
11574 	 * would be to check for and report the reset events here, and then
11575 	 * check for the other unit attention types after we check for a
11576 	 * reservation conflict.
11577 	 *
11578 	 * XXX KDM need to fix this
11579 	 */
11580 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11581 		ctl_ua_type ua_type;
11582 		u_int sense_len = 0;
11583 
11584 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11585 		    &sense_len, SSD_TYPE_NONE);
11586 		if (ua_type != CTL_UA_NONE) {
11587 			mtx_unlock(&lun->lun_lock);
11588 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11589 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11590 			ctsio->sense_len = sense_len;
11591 			ctl_done((union ctl_io *)ctsio);
11592 			return (retval);
11593 		}
11594 	}
11595 
11596 
11597 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11598 		mtx_unlock(&lun->lun_lock);
11599 		ctl_done((union ctl_io *)ctsio);
11600 		return (retval);
11601 	}
11602 
11603 	/*
11604 	 * XXX CHD this is where we want to send IO to other side if
11605 	 * this LUN is secondary on this SC. We will need to make a copy
11606 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11607 	 * the copy we send as FROM_OTHER.
11608 	 * We also need to stuff the address of the original IO so we can
11609 	 * find it easily. Something similar will need be done on the other
11610 	 * side so when we are done we can find the copy.
11611 	 */
11612 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11613 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11614 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11615 		union ctl_ha_msg msg_info;
11616 		int isc_retval;
11617 
11618 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11619 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11620 		mtx_unlock(&lun->lun_lock);
11621 
11622 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11623 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11624 		msg_info.hdr.serializing_sc = NULL;
11625 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11626 		msg_info.scsi.tag_num = ctsio->tag_num;
11627 		msg_info.scsi.tag_type = ctsio->tag_type;
11628 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11629 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11630 
11631 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11632 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11633 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11634 			ctl_set_busy(ctsio);
11635 			ctl_done((union ctl_io *)ctsio);
11636 			return (retval);
11637 		}
11638 		return (retval);
11639 	}
11640 
11641 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11642 			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11643 			      ctl_ooaq, ooa_links))) {
11644 	case CTL_ACTION_BLOCK:
11645 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11646 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11647 				  blocked_links);
11648 		mtx_unlock(&lun->lun_lock);
11649 		return (retval);
11650 	case CTL_ACTION_PASS:
11651 	case CTL_ACTION_SKIP:
11652 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11653 		mtx_unlock(&lun->lun_lock);
11654 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11655 		break;
11656 	case CTL_ACTION_OVERLAP:
11657 		mtx_unlock(&lun->lun_lock);
11658 		ctl_set_overlapped_cmd(ctsio);
11659 		ctl_done((union ctl_io *)ctsio);
11660 		break;
11661 	case CTL_ACTION_OVERLAP_TAG:
11662 		mtx_unlock(&lun->lun_lock);
11663 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11664 		ctl_done((union ctl_io *)ctsio);
11665 		break;
11666 	case CTL_ACTION_ERROR:
11667 	default:
11668 		mtx_unlock(&lun->lun_lock);
11669 		ctl_set_internal_failure(ctsio,
11670 					 /*sks_valid*/ 0,
11671 					 /*retry_count*/ 0);
11672 		ctl_done((union ctl_io *)ctsio);
11673 		break;
11674 	}
11675 	return (retval);
11676 }
11677 
11678 const struct ctl_cmd_entry *
11679 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11680 {
11681 	const struct ctl_cmd_entry *entry;
11682 	int service_action;
11683 
11684 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11685 	if (sa)
11686 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11687 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11688 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11689 		entry = &((const struct ctl_cmd_entry *)
11690 		    entry->execute)[service_action];
11691 	}
11692 	return (entry);
11693 }
11694 
11695 const struct ctl_cmd_entry *
11696 ctl_validate_command(struct ctl_scsiio *ctsio)
11697 {
11698 	const struct ctl_cmd_entry *entry;
11699 	int i, sa;
11700 	uint8_t diff;
11701 
11702 	entry = ctl_get_cmd_entry(ctsio, &sa);
11703 	if (entry->execute == NULL) {
11704 		if (sa)
11705 			ctl_set_invalid_field(ctsio,
11706 					      /*sks_valid*/ 1,
11707 					      /*command*/ 1,
11708 					      /*field*/ 1,
11709 					      /*bit_valid*/ 1,
11710 					      /*bit*/ 4);
11711 		else
11712 			ctl_set_invalid_opcode(ctsio);
11713 		ctl_done((union ctl_io *)ctsio);
11714 		return (NULL);
11715 	}
11716 	KASSERT(entry->length > 0,
11717 	    ("Not defined length for command 0x%02x/0x%02x",
11718 	     ctsio->cdb[0], ctsio->cdb[1]));
11719 	for (i = 1; i < entry->length; i++) {
11720 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11721 		if (diff == 0)
11722 			continue;
11723 		ctl_set_invalid_field(ctsio,
11724 				      /*sks_valid*/ 1,
11725 				      /*command*/ 1,
11726 				      /*field*/ i,
11727 				      /*bit_valid*/ 1,
11728 				      /*bit*/ fls(diff) - 1);
11729 		ctl_done((union ctl_io *)ctsio);
11730 		return (NULL);
11731 	}
11732 	return (entry);
11733 }
11734 
11735 static int
11736 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11737 {
11738 
11739 	switch (lun_type) {
11740 	case T_DIRECT:
11741 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11742 			return (0);
11743 		break;
11744 	case T_PROCESSOR:
11745 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11746 			return (0);
11747 		break;
11748 	case T_CDROM:
11749 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11750 			return (0);
11751 		break;
11752 	default:
11753 		return (0);
11754 	}
11755 	return (1);
11756 }
11757 
11758 static int
11759 ctl_scsiio(struct ctl_scsiio *ctsio)
11760 {
11761 	int retval;
11762 	const struct ctl_cmd_entry *entry;
11763 
11764 	retval = CTL_RETVAL_COMPLETE;
11765 
11766 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11767 
11768 	entry = ctl_get_cmd_entry(ctsio, NULL);
11769 
11770 	/*
11771 	 * If this I/O has been aborted, just send it straight to
11772 	 * ctl_done() without executing it.
11773 	 */
11774 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11775 		ctl_done((union ctl_io *)ctsio);
11776 		goto bailout;
11777 	}
11778 
11779 	/*
11780 	 * All the checks should have been handled by ctl_scsiio_precheck().
11781 	 * We should be clear now to just execute the I/O.
11782 	 */
11783 	retval = entry->execute(ctsio);
11784 
11785 bailout:
11786 	return (retval);
11787 }
11788 
11789 /*
11790  * Since we only implement one target right now, a bus reset simply resets
11791  * our single target.
11792  */
11793 static int
11794 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11795 {
11796 	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11797 }
11798 
11799 static int
11800 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11801 		 ctl_ua_type ua_type)
11802 {
11803 	struct ctl_port *port = CTL_PORT(io);
11804 	struct ctl_lun *lun;
11805 	int retval;
11806 
11807 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11808 		union ctl_ha_msg msg_info;
11809 
11810 		msg_info.hdr.nexus = io->io_hdr.nexus;
11811 		if (ua_type==CTL_UA_TARG_RESET)
11812 			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11813 		else
11814 			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11815 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11816 		msg_info.hdr.original_sc = NULL;
11817 		msg_info.hdr.serializing_sc = NULL;
11818 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11819 		    sizeof(msg_info.task), M_WAITOK);
11820 	}
11821 	retval = 0;
11822 
11823 	mtx_lock(&softc->ctl_lock);
11824 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11825 		if (port != NULL &&
11826 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11827 			continue;
11828 		retval += ctl_do_lun_reset(lun, io, ua_type);
11829 	}
11830 	mtx_unlock(&softc->ctl_lock);
11831 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11832 	return (retval);
11833 }
11834 
11835 /*
11836  * The LUN should always be set.  The I/O is optional, and is used to
11837  * distinguish between I/Os sent by this initiator, and by other
11838  * initiators.  We set unit attention for initiators other than this one.
11839  * SAM-3 is vague on this point.  It does say that a unit attention should
11840  * be established for other initiators when a LUN is reset (see section
11841  * 5.7.3), but it doesn't specifically say that the unit attention should
11842  * be established for this particular initiator when a LUN is reset.  Here
11843  * is the relevant text, from SAM-3 rev 8:
11844  *
11845  * 5.7.2 When a SCSI initiator port aborts its own tasks
11846  *
11847  * When a SCSI initiator port causes its own task(s) to be aborted, no
11848  * notification that the task(s) have been aborted shall be returned to
11849  * the SCSI initiator port other than the completion response for the
11850  * command or task management function action that caused the task(s) to
11851  * be aborted and notification(s) associated with related effects of the
11852  * action (e.g., a reset unit attention condition).
11853  *
11854  * XXX KDM for now, we're setting unit attention for all initiators.
11855  */
11856 static int
11857 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11858 {
11859 	union ctl_io *xio;
11860 #if 0
11861 	uint32_t initidx;
11862 #endif
11863 	int i;
11864 
11865 	mtx_lock(&lun->lun_lock);
11866 	/*
11867 	 * Run through the OOA queue and abort each I/O.
11868 	 */
11869 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11870 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11871 		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11872 	}
11873 
11874 	/*
11875 	 * This version sets unit attention for every
11876 	 */
11877 #if 0
11878 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11879 	ctl_est_ua_all(lun, initidx, ua_type);
11880 #else
11881 	ctl_est_ua_all(lun, -1, ua_type);
11882 #endif
11883 
11884 	/*
11885 	 * A reset (any kind, really) clears reservations established with
11886 	 * RESERVE/RELEASE.  It does not clear reservations established
11887 	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11888 	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11889 	 * reservations made with the RESERVE/RELEASE commands, because
11890 	 * those commands are obsolete in SPC-3.
11891 	 */
11892 	lun->flags &= ~CTL_LUN_RESERVED;
11893 
11894 #ifdef CTL_WITH_CA
11895 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11896 		ctl_clear_mask(lun->have_ca, i);
11897 #endif
11898 	lun->prevent_count = 0;
11899 	if (lun->prevent) {
11900 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11901 			ctl_clear_mask(lun->prevent, i);
11902 	}
11903 	mtx_unlock(&lun->lun_lock);
11904 
11905 	return (0);
11906 }
11907 
11908 static int
11909 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11910 {
11911 	struct ctl_lun *lun;
11912 	uint32_t targ_lun;
11913 	int retval;
11914 
11915 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11916 	mtx_lock(&softc->ctl_lock);
11917 	if (targ_lun >= CTL_MAX_LUNS ||
11918 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11919 		mtx_unlock(&softc->ctl_lock);
11920 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11921 		return (1);
11922 	}
11923 	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11924 	mtx_unlock(&softc->ctl_lock);
11925 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11926 
11927 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11928 		union ctl_ha_msg msg_info;
11929 
11930 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11931 		msg_info.hdr.nexus = io->io_hdr.nexus;
11932 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11933 		msg_info.hdr.original_sc = NULL;
11934 		msg_info.hdr.serializing_sc = NULL;
11935 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11936 		    sizeof(msg_info.task), M_WAITOK);
11937 	}
11938 	return (retval);
11939 }
11940 
11941 static void
11942 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11943     int other_sc)
11944 {
11945 	union ctl_io *xio;
11946 
11947 	mtx_assert(&lun->lun_lock, MA_OWNED);
11948 
11949 	/*
11950 	 * Run through the OOA queue and attempt to find the given I/O.
11951 	 * The target port, initiator ID, tag type and tag number have to
11952 	 * match the values that we got from the initiator.  If we have an
11953 	 * untagged command to abort, simply abort the first untagged command
11954 	 * we come to.  We only allow one untagged command at a time of course.
11955 	 */
11956 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11957 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11958 
11959 		if ((targ_port == UINT32_MAX ||
11960 		     targ_port == xio->io_hdr.nexus.targ_port) &&
11961 		    (init_id == UINT32_MAX ||
11962 		     init_id == xio->io_hdr.nexus.initid)) {
11963 			if (targ_port != xio->io_hdr.nexus.targ_port ||
11964 			    init_id != xio->io_hdr.nexus.initid)
11965 				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11966 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11967 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11968 				union ctl_ha_msg msg_info;
11969 
11970 				msg_info.hdr.nexus = xio->io_hdr.nexus;
11971 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11972 				msg_info.task.tag_num = xio->scsiio.tag_num;
11973 				msg_info.task.tag_type = xio->scsiio.tag_type;
11974 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11975 				msg_info.hdr.original_sc = NULL;
11976 				msg_info.hdr.serializing_sc = NULL;
11977 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11978 				    sizeof(msg_info.task), M_NOWAIT);
11979 			}
11980 		}
11981 	}
11982 }
11983 
11984 static int
11985 ctl_abort_task_set(union ctl_io *io)
11986 {
11987 	struct ctl_softc *softc = CTL_SOFTC(io);
11988 	struct ctl_lun *lun;
11989 	uint32_t targ_lun;
11990 
11991 	/*
11992 	 * Look up the LUN.
11993 	 */
11994 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11995 	mtx_lock(&softc->ctl_lock);
11996 	if (targ_lun >= CTL_MAX_LUNS ||
11997 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11998 		mtx_unlock(&softc->ctl_lock);
11999 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12000 		return (1);
12001 	}
12002 
12003 	mtx_lock(&lun->lun_lock);
12004 	mtx_unlock(&softc->ctl_lock);
12005 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12006 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12007 		    io->io_hdr.nexus.initid,
12008 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12009 	} else { /* CTL_TASK_CLEAR_TASK_SET */
12010 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12011 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12012 	}
12013 	mtx_unlock(&lun->lun_lock);
12014 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12015 	return (0);
12016 }
12017 
12018 static int
12019 ctl_i_t_nexus_reset(union ctl_io *io)
12020 {
12021 	struct ctl_softc *softc = CTL_SOFTC(io);
12022 	struct ctl_lun *lun;
12023 	uint32_t initidx;
12024 
12025 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12026 		union ctl_ha_msg msg_info;
12027 
12028 		msg_info.hdr.nexus = io->io_hdr.nexus;
12029 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12030 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12031 		msg_info.hdr.original_sc = NULL;
12032 		msg_info.hdr.serializing_sc = NULL;
12033 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12034 		    sizeof(msg_info.task), M_WAITOK);
12035 	}
12036 
12037 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12038 	mtx_lock(&softc->ctl_lock);
12039 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12040 		mtx_lock(&lun->lun_lock);
12041 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12042 		    io->io_hdr.nexus.initid, 1);
12043 #ifdef CTL_WITH_CA
12044 		ctl_clear_mask(lun->have_ca, initidx);
12045 #endif
12046 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12047 			lun->flags &= ~CTL_LUN_RESERVED;
12048 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
12049 			ctl_clear_mask(lun->prevent, initidx);
12050 			lun->prevent_count--;
12051 		}
12052 		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12053 		mtx_unlock(&lun->lun_lock);
12054 	}
12055 	mtx_unlock(&softc->ctl_lock);
12056 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12057 	return (0);
12058 }
12059 
12060 static int
12061 ctl_abort_task(union ctl_io *io)
12062 {
12063 	struct ctl_softc *softc = CTL_SOFTC(io);
12064 	union ctl_io *xio;
12065 	struct ctl_lun *lun;
12066 #if 0
12067 	struct sbuf sb;
12068 	char printbuf[128];
12069 #endif
12070 	int found;
12071 	uint32_t targ_lun;
12072 
12073 	found = 0;
12074 
12075 	/*
12076 	 * Look up the LUN.
12077 	 */
12078 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12079 	mtx_lock(&softc->ctl_lock);
12080 	if (targ_lun >= CTL_MAX_LUNS ||
12081 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12082 		mtx_unlock(&softc->ctl_lock);
12083 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12084 		return (1);
12085 	}
12086 
12087 #if 0
12088 	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12089 	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12090 #endif
12091 
12092 	mtx_lock(&lun->lun_lock);
12093 	mtx_unlock(&softc->ctl_lock);
12094 	/*
12095 	 * Run through the OOA queue and attempt to find the given I/O.
12096 	 * The target port, initiator ID, tag type and tag number have to
12097 	 * match the values that we got from the initiator.  If we have an
12098 	 * untagged command to abort, simply abort the first untagged command
12099 	 * we come to.  We only allow one untagged command at a time of course.
12100 	 */
12101 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12102 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12103 #if 0
12104 		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12105 
12106 		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12107 			    lun->lun, xio->scsiio.tag_num,
12108 			    xio->scsiio.tag_type,
12109 			    (xio->io_hdr.blocked_links.tqe_prev
12110 			    == NULL) ? "" : " BLOCKED",
12111 			    (xio->io_hdr.flags &
12112 			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12113 			    (xio->io_hdr.flags &
12114 			    CTL_FLAG_ABORT) ? " ABORT" : "",
12115 			    (xio->io_hdr.flags &
12116 			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12117 		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12118 		sbuf_finish(&sb);
12119 		printf("%s\n", sbuf_data(&sb));
12120 #endif
12121 
12122 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12123 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12124 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12125 			continue;
12126 
12127 		/*
12128 		 * If the abort says that the task is untagged, the
12129 		 * task in the queue must be untagged.  Otherwise,
12130 		 * we just check to see whether the tag numbers
12131 		 * match.  This is because the QLogic firmware
12132 		 * doesn't pass back the tag type in an abort
12133 		 * request.
12134 		 */
12135 #if 0
12136 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12137 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12138 		 || (xio->scsiio.tag_num == io->taskio.tag_num))
12139 #endif
12140 		/*
12141 		 * XXX KDM we've got problems with FC, because it
12142 		 * doesn't send down a tag type with aborts.  So we
12143 		 * can only really go by the tag number...
12144 		 * This may cause problems with parallel SCSI.
12145 		 * Need to figure that out!!
12146 		 */
12147 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12148 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12149 			found = 1;
12150 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12151 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12152 				union ctl_ha_msg msg_info;
12153 
12154 				msg_info.hdr.nexus = io->io_hdr.nexus;
12155 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12156 				msg_info.task.tag_num = io->taskio.tag_num;
12157 				msg_info.task.tag_type = io->taskio.tag_type;
12158 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12159 				msg_info.hdr.original_sc = NULL;
12160 				msg_info.hdr.serializing_sc = NULL;
12161 #if 0
12162 				printf("Sent Abort to other side\n");
12163 #endif
12164 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12165 				    sizeof(msg_info.task), M_NOWAIT);
12166 			}
12167 #if 0
12168 			printf("ctl_abort_task: found I/O to abort\n");
12169 #endif
12170 		}
12171 	}
12172 	mtx_unlock(&lun->lun_lock);
12173 
12174 	if (found == 0) {
12175 		/*
12176 		 * This isn't really an error.  It's entirely possible for
12177 		 * the abort and command completion to cross on the wire.
12178 		 * This is more of an informative/diagnostic error.
12179 		 */
12180 #if 0
12181 		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12182 		       "%u:%u:%u tag %d type %d\n",
12183 		       io->io_hdr.nexus.initid,
12184 		       io->io_hdr.nexus.targ_port,
12185 		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12186 		       io->taskio.tag_type);
12187 #endif
12188 	}
12189 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12190 	return (0);
12191 }
12192 
12193 static int
12194 ctl_query_task(union ctl_io *io, int task_set)
12195 {
12196 	struct ctl_softc *softc = CTL_SOFTC(io);
12197 	union ctl_io *xio;
12198 	struct ctl_lun *lun;
12199 	int found = 0;
12200 	uint32_t targ_lun;
12201 
12202 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12203 	mtx_lock(&softc->ctl_lock);
12204 	if (targ_lun >= CTL_MAX_LUNS ||
12205 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12206 		mtx_unlock(&softc->ctl_lock);
12207 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12208 		return (1);
12209 	}
12210 	mtx_lock(&lun->lun_lock);
12211 	mtx_unlock(&softc->ctl_lock);
12212 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12213 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12214 
12215 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12216 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12217 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12218 			continue;
12219 
12220 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12221 			found = 1;
12222 			break;
12223 		}
12224 	}
12225 	mtx_unlock(&lun->lun_lock);
12226 	if (found)
12227 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12228 	else
12229 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12230 	return (0);
12231 }
12232 
12233 static int
12234 ctl_query_async_event(union ctl_io *io)
12235 {
12236 	struct ctl_softc *softc = CTL_SOFTC(io);
12237 	struct ctl_lun *lun;
12238 	ctl_ua_type ua;
12239 	uint32_t targ_lun, initidx;
12240 
12241 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12242 	mtx_lock(&softc->ctl_lock);
12243 	if (targ_lun >= CTL_MAX_LUNS ||
12244 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12245 		mtx_unlock(&softc->ctl_lock);
12246 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12247 		return (1);
12248 	}
12249 	mtx_lock(&lun->lun_lock);
12250 	mtx_unlock(&softc->ctl_lock);
12251 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12252 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12253 	mtx_unlock(&lun->lun_lock);
12254 	if (ua != CTL_UA_NONE)
12255 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12256 	else
12257 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12258 	return (0);
12259 }
12260 
12261 static void
12262 ctl_run_task(union ctl_io *io)
12263 {
12264 	struct ctl_softc *softc = CTL_SOFTC(io);
12265 	int retval = 1;
12266 
12267 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12268 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12269 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12270 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12271 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12272 	switch (io->taskio.task_action) {
12273 	case CTL_TASK_ABORT_TASK:
12274 		retval = ctl_abort_task(io);
12275 		break;
12276 	case CTL_TASK_ABORT_TASK_SET:
12277 	case CTL_TASK_CLEAR_TASK_SET:
12278 		retval = ctl_abort_task_set(io);
12279 		break;
12280 	case CTL_TASK_CLEAR_ACA:
12281 		break;
12282 	case CTL_TASK_I_T_NEXUS_RESET:
12283 		retval = ctl_i_t_nexus_reset(io);
12284 		break;
12285 	case CTL_TASK_LUN_RESET:
12286 		retval = ctl_lun_reset(softc, io);
12287 		break;
12288 	case CTL_TASK_TARGET_RESET:
12289 		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12290 		break;
12291 	case CTL_TASK_BUS_RESET:
12292 		retval = ctl_bus_reset(softc, io);
12293 		break;
12294 	case CTL_TASK_PORT_LOGIN:
12295 		break;
12296 	case CTL_TASK_PORT_LOGOUT:
12297 		break;
12298 	case CTL_TASK_QUERY_TASK:
12299 		retval = ctl_query_task(io, 0);
12300 		break;
12301 	case CTL_TASK_QUERY_TASK_SET:
12302 		retval = ctl_query_task(io, 1);
12303 		break;
12304 	case CTL_TASK_QUERY_ASYNC_EVENT:
12305 		retval = ctl_query_async_event(io);
12306 		break;
12307 	default:
12308 		printf("%s: got unknown task management event %d\n",
12309 		       __func__, io->taskio.task_action);
12310 		break;
12311 	}
12312 	if (retval == 0)
12313 		io->io_hdr.status = CTL_SUCCESS;
12314 	else
12315 		io->io_hdr.status = CTL_ERROR;
12316 	ctl_done(io);
12317 }
12318 
12319 /*
12320  * For HA operation.  Handle commands that come in from the other
12321  * controller.
12322  */
12323 static void
12324 ctl_handle_isc(union ctl_io *io)
12325 {
12326 	struct ctl_softc *softc = CTL_SOFTC(io);
12327 	struct ctl_lun *lun;
12328 	const struct ctl_cmd_entry *entry;
12329 	uint32_t targ_lun;
12330 
12331 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12332 	switch (io->io_hdr.msg_type) {
12333 	case CTL_MSG_SERIALIZE:
12334 		ctl_serialize_other_sc_cmd(&io->scsiio);
12335 		break;
12336 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12337 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12338 		if (targ_lun >= CTL_MAX_LUNS ||
12339 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12340 			ctl_done(io);
12341 			break;
12342 		}
12343 		mtx_lock(&lun->lun_lock);
12344 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12345 			mtx_unlock(&lun->lun_lock);
12346 			ctl_done(io);
12347 			break;
12348 		}
12349 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12350 		mtx_unlock(&lun->lun_lock);
12351 		ctl_enqueue_rtr(io);
12352 		break;
12353 	case CTL_MSG_FINISH_IO:
12354 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12355 			ctl_done(io);
12356 			break;
12357 		}
12358 		if (targ_lun >= CTL_MAX_LUNS ||
12359 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12360 			ctl_free_io(io);
12361 			break;
12362 		}
12363 		mtx_lock(&lun->lun_lock);
12364 		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12365 		ctl_check_blocked(lun);
12366 		mtx_unlock(&lun->lun_lock);
12367 		ctl_free_io(io);
12368 		break;
12369 	case CTL_MSG_PERS_ACTION:
12370 		ctl_hndl_per_res_out_on_other_sc(io);
12371 		ctl_free_io(io);
12372 		break;
12373 	case CTL_MSG_BAD_JUJU:
12374 		ctl_done(io);
12375 		break;
12376 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12377 		ctl_datamove_remote(io);
12378 		break;
12379 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12380 		io->scsiio.be_move_done(io);
12381 		break;
12382 	case CTL_MSG_FAILOVER:
12383 		ctl_failover_lun(io);
12384 		ctl_free_io(io);
12385 		break;
12386 	default:
12387 		printf("%s: Invalid message type %d\n",
12388 		       __func__, io->io_hdr.msg_type);
12389 		ctl_free_io(io);
12390 		break;
12391 	}
12392 
12393 }
12394 
12395 
12396 /*
12397  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12398  * there is no match.
12399  */
12400 static ctl_lun_error_pattern
12401 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12402 {
12403 	const struct ctl_cmd_entry *entry;
12404 	ctl_lun_error_pattern filtered_pattern, pattern;
12405 
12406 	pattern = desc->error_pattern;
12407 
12408 	/*
12409 	 * XXX KDM we need more data passed into this function to match a
12410 	 * custom pattern, and we actually need to implement custom pattern
12411 	 * matching.
12412 	 */
12413 	if (pattern & CTL_LUN_PAT_CMD)
12414 		return (CTL_LUN_PAT_CMD);
12415 
12416 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12417 		return (CTL_LUN_PAT_ANY);
12418 
12419 	entry = ctl_get_cmd_entry(ctsio, NULL);
12420 
12421 	filtered_pattern = entry->pattern & pattern;
12422 
12423 	/*
12424 	 * If the user requested specific flags in the pattern (e.g.
12425 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12426 	 * flags.
12427 	 *
12428 	 * If the user did not specify any flags, it doesn't matter whether
12429 	 * or not the command supports the flags.
12430 	 */
12431 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12432 	     (pattern & ~CTL_LUN_PAT_MASK))
12433 		return (CTL_LUN_PAT_NONE);
12434 
12435 	/*
12436 	 * If the user asked for a range check, see if the requested LBA
12437 	 * range overlaps with this command's LBA range.
12438 	 */
12439 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12440 		uint64_t lba1;
12441 		uint64_t len1;
12442 		ctl_action action;
12443 		int retval;
12444 
12445 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12446 		if (retval != 0)
12447 			return (CTL_LUN_PAT_NONE);
12448 
12449 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12450 					      desc->lba_range.len, FALSE);
12451 		/*
12452 		 * A "pass" means that the LBA ranges don't overlap, so
12453 		 * this doesn't match the user's range criteria.
12454 		 */
12455 		if (action == CTL_ACTION_PASS)
12456 			return (CTL_LUN_PAT_NONE);
12457 	}
12458 
12459 	return (filtered_pattern);
12460 }
12461 
12462 static void
12463 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12464 {
12465 	struct ctl_error_desc *desc, *desc2;
12466 
12467 	mtx_assert(&lun->lun_lock, MA_OWNED);
12468 
12469 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12470 		ctl_lun_error_pattern pattern;
12471 		/*
12472 		 * Check to see whether this particular command matches
12473 		 * the pattern in the descriptor.
12474 		 */
12475 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12476 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12477 			continue;
12478 
12479 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12480 		case CTL_LUN_INJ_ABORTED:
12481 			ctl_set_aborted(&io->scsiio);
12482 			break;
12483 		case CTL_LUN_INJ_MEDIUM_ERR:
12484 			ctl_set_medium_error(&io->scsiio,
12485 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12486 			     CTL_FLAG_DATA_OUT);
12487 			break;
12488 		case CTL_LUN_INJ_UA:
12489 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12490 			 * OCCURRED */
12491 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12492 			break;
12493 		case CTL_LUN_INJ_CUSTOM:
12494 			/*
12495 			 * We're assuming the user knows what he is doing.
12496 			 * Just copy the sense information without doing
12497 			 * checks.
12498 			 */
12499 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12500 			      MIN(sizeof(desc->custom_sense),
12501 				  sizeof(io->scsiio.sense_data)));
12502 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12503 			io->scsiio.sense_len = SSD_FULL_SIZE;
12504 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12505 			break;
12506 		case CTL_LUN_INJ_NONE:
12507 		default:
12508 			/*
12509 			 * If this is an error injection type we don't know
12510 			 * about, clear the continuous flag (if it is set)
12511 			 * so it will get deleted below.
12512 			 */
12513 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12514 			break;
12515 		}
12516 		/*
12517 		 * By default, each error injection action is a one-shot
12518 		 */
12519 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12520 			continue;
12521 
12522 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12523 
12524 		free(desc, M_CTL);
12525 	}
12526 }
12527 
12528 #ifdef CTL_IO_DELAY
12529 static void
12530 ctl_datamove_timer_wakeup(void *arg)
12531 {
12532 	union ctl_io *io;
12533 
12534 	io = (union ctl_io *)arg;
12535 
12536 	ctl_datamove(io);
12537 }
12538 #endif /* CTL_IO_DELAY */
12539 
12540 void
12541 ctl_datamove(union ctl_io *io)
12542 {
12543 	void (*fe_datamove)(union ctl_io *io);
12544 
12545 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12546 
12547 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12548 
12549 	/* No data transferred yet.  Frontend must update this when done. */
12550 	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12551 
12552 #ifdef CTL_TIME_IO
12553 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12554 		char str[256];
12555 		char path_str[64];
12556 		struct sbuf sb;
12557 
12558 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12559 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12560 
12561 		sbuf_cat(&sb, path_str);
12562 		switch (io->io_hdr.io_type) {
12563 		case CTL_IO_SCSI:
12564 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12565 			sbuf_printf(&sb, "\n");
12566 			sbuf_cat(&sb, path_str);
12567 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12568 				    io->scsiio.tag_num, io->scsiio.tag_type);
12569 			break;
12570 		case CTL_IO_TASK:
12571 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12572 				    "Tag Type: %d\n", io->taskio.task_action,
12573 				    io->taskio.tag_num, io->taskio.tag_type);
12574 			break;
12575 		default:
12576 			panic("%s: Invalid CTL I/O type %d\n",
12577 			    __func__, io->io_hdr.io_type);
12578 		}
12579 		sbuf_cat(&sb, path_str);
12580 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12581 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12582 		sbuf_finish(&sb);
12583 		printf("%s", sbuf_data(&sb));
12584 	}
12585 #endif /* CTL_TIME_IO */
12586 
12587 #ifdef CTL_IO_DELAY
12588 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12589 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12590 	} else {
12591 		if ((lun != NULL)
12592 		 && (lun->delay_info.datamove_delay > 0)) {
12593 
12594 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12595 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12596 			callout_reset(&io->io_hdr.delay_callout,
12597 				      lun->delay_info.datamove_delay * hz,
12598 				      ctl_datamove_timer_wakeup, io);
12599 			if (lun->delay_info.datamove_type ==
12600 			    CTL_DELAY_TYPE_ONESHOT)
12601 				lun->delay_info.datamove_delay = 0;
12602 			return;
12603 		}
12604 	}
12605 #endif
12606 
12607 	/*
12608 	 * This command has been aborted.  Set the port status, so we fail
12609 	 * the data move.
12610 	 */
12611 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12612 		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12613 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12614 		       io->io_hdr.nexus.targ_port,
12615 		       io->io_hdr.nexus.targ_lun);
12616 		io->io_hdr.port_status = 31337;
12617 		/*
12618 		 * Note that the backend, in this case, will get the
12619 		 * callback in its context.  In other cases it may get
12620 		 * called in the frontend's interrupt thread context.
12621 		 */
12622 		io->scsiio.be_move_done(io);
12623 		return;
12624 	}
12625 
12626 	/* Don't confuse frontend with zero length data move. */
12627 	if (io->scsiio.kern_data_len == 0) {
12628 		io->scsiio.be_move_done(io);
12629 		return;
12630 	}
12631 
12632 	fe_datamove = CTL_PORT(io)->fe_datamove;
12633 	fe_datamove(io);
12634 }
12635 
12636 static void
12637 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12638 {
12639 	union ctl_ha_msg msg;
12640 #ifdef CTL_TIME_IO
12641 	struct bintime cur_bt;
12642 #endif
12643 
12644 	memset(&msg, 0, sizeof(msg));
12645 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12646 	msg.hdr.original_sc = io;
12647 	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12648 	msg.hdr.nexus = io->io_hdr.nexus;
12649 	msg.hdr.status = io->io_hdr.status;
12650 	msg.scsi.tag_num = io->scsiio.tag_num;
12651 	msg.scsi.tag_type = io->scsiio.tag_type;
12652 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12653 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12654 	       io->scsiio.sense_len);
12655 	msg.scsi.sense_len = io->scsiio.sense_len;
12656 	msg.scsi.sense_residual = io->scsiio.sense_residual;
12657 	msg.scsi.fetd_status = io->io_hdr.port_status;
12658 	msg.scsi.residual = io->scsiio.residual;
12659 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12660 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12661 		ctl_failover_io(io, /*have_lock*/ have_lock);
12662 		return;
12663 	}
12664 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12665 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12666 	    msg.scsi.sense_len, M_WAITOK);
12667 
12668 #ifdef CTL_TIME_IO
12669 	getbinuptime(&cur_bt);
12670 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12671 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12672 #endif
12673 	io->io_hdr.num_dmas++;
12674 }
12675 
12676 /*
12677  * The DMA to the remote side is done, now we need to tell the other side
12678  * we're done so it can continue with its data movement.
12679  */
12680 static void
12681 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12682 {
12683 	union ctl_io *io;
12684 	uint32_t i;
12685 
12686 	io = rq->context;
12687 
12688 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12689 		printf("%s: ISC DMA write failed with error %d", __func__,
12690 		       rq->ret);
12691 		ctl_set_internal_failure(&io->scsiio,
12692 					 /*sks_valid*/ 1,
12693 					 /*retry_count*/ rq->ret);
12694 	}
12695 
12696 	ctl_dt_req_free(rq);
12697 
12698 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12699 		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12700 	free(io->io_hdr.remote_sglist, M_CTL);
12701 	io->io_hdr.remote_sglist = NULL;
12702 	io->io_hdr.local_sglist = NULL;
12703 
12704 	/*
12705 	 * The data is in local and remote memory, so now we need to send
12706 	 * status (good or back) back to the other side.
12707 	 */
12708 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12709 }
12710 
12711 /*
12712  * We've moved the data from the host/controller into local memory.  Now we
12713  * need to push it over to the remote controller's memory.
12714  */
12715 static int
12716 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12717 {
12718 	int retval;
12719 
12720 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12721 					  ctl_datamove_remote_write_cb);
12722 	return (retval);
12723 }
12724 
12725 static void
12726 ctl_datamove_remote_write(union ctl_io *io)
12727 {
12728 	int retval;
12729 	void (*fe_datamove)(union ctl_io *io);
12730 
12731 	/*
12732 	 * - Get the data from the host/HBA into local memory.
12733 	 * - DMA memory from the local controller to the remote controller.
12734 	 * - Send status back to the remote controller.
12735 	 */
12736 
12737 	retval = ctl_datamove_remote_sgl_setup(io);
12738 	if (retval != 0)
12739 		return;
12740 
12741 	/* Switch the pointer over so the FETD knows what to do */
12742 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12743 
12744 	/*
12745 	 * Use a custom move done callback, since we need to send completion
12746 	 * back to the other controller, not to the backend on this side.
12747 	 */
12748 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12749 
12750 	fe_datamove = CTL_PORT(io)->fe_datamove;
12751 	fe_datamove(io);
12752 }
12753 
12754 static int
12755 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12756 {
12757 #if 0
12758 	char str[256];
12759 	char path_str[64];
12760 	struct sbuf sb;
12761 #endif
12762 	uint32_t i;
12763 
12764 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12765 		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12766 	free(io->io_hdr.remote_sglist, M_CTL);
12767 	io->io_hdr.remote_sglist = NULL;
12768 	io->io_hdr.local_sglist = NULL;
12769 
12770 #if 0
12771 	scsi_path_string(io, path_str, sizeof(path_str));
12772 	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12773 	sbuf_cat(&sb, path_str);
12774 	scsi_command_string(&io->scsiio, NULL, &sb);
12775 	sbuf_printf(&sb, "\n");
12776 	sbuf_cat(&sb, path_str);
12777 	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12778 		    io->scsiio.tag_num, io->scsiio.tag_type);
12779 	sbuf_cat(&sb, path_str);
12780 	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12781 		    io->io_hdr.flags, io->io_hdr.status);
12782 	sbuf_finish(&sb);
12783 	printk("%s", sbuf_data(&sb));
12784 #endif
12785 
12786 
12787 	/*
12788 	 * The read is done, now we need to send status (good or bad) back
12789 	 * to the other side.
12790 	 */
12791 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12792 
12793 	return (0);
12794 }
12795 
12796 static void
12797 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12798 {
12799 	union ctl_io *io;
12800 	void (*fe_datamove)(union ctl_io *io);
12801 
12802 	io = rq->context;
12803 
12804 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12805 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12806 		       rq->ret);
12807 		ctl_set_internal_failure(&io->scsiio,
12808 					 /*sks_valid*/ 1,
12809 					 /*retry_count*/ rq->ret);
12810 	}
12811 
12812 	ctl_dt_req_free(rq);
12813 
12814 	/* Switch the pointer over so the FETD knows what to do */
12815 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12816 
12817 	/*
12818 	 * Use a custom move done callback, since we need to send completion
12819 	 * back to the other controller, not to the backend on this side.
12820 	 */
12821 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12822 
12823 	/* XXX KDM add checks like the ones in ctl_datamove? */
12824 
12825 	fe_datamove = CTL_PORT(io)->fe_datamove;
12826 	fe_datamove(io);
12827 }
12828 
12829 static int
12830 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12831 {
12832 	struct ctl_sg_entry *local_sglist;
12833 	uint32_t len_to_go;
12834 	int retval;
12835 	int i;
12836 
12837 	retval = 0;
12838 	local_sglist = io->io_hdr.local_sglist;
12839 	len_to_go = io->scsiio.kern_data_len;
12840 
12841 	/*
12842 	 * The difficult thing here is that the size of the various
12843 	 * S/G segments may be different than the size from the
12844 	 * remote controller.  That'll make it harder when DMAing
12845 	 * the data back to the other side.
12846 	 */
12847 	for (i = 0; len_to_go > 0; i++) {
12848 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12849 		local_sglist[i].addr =
12850 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12851 
12852 		len_to_go -= local_sglist[i].len;
12853 	}
12854 	/*
12855 	 * Reset the number of S/G entries accordingly.  The original
12856 	 * number of S/G entries is available in rem_sg_entries.
12857 	 */
12858 	io->scsiio.kern_sg_entries = i;
12859 
12860 #if 0
12861 	printf("%s: kern_sg_entries = %d\n", __func__,
12862 	       io->scsiio.kern_sg_entries);
12863 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12864 		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12865 		       local_sglist[i].addr, local_sglist[i].len);
12866 #endif
12867 
12868 	return (retval);
12869 }
12870 
12871 static int
12872 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12873 			 ctl_ha_dt_cb callback)
12874 {
12875 	struct ctl_ha_dt_req *rq;
12876 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12877 	uint32_t local_used, remote_used, total_used;
12878 	int i, j, isc_ret;
12879 
12880 	rq = ctl_dt_req_alloc();
12881 
12882 	/*
12883 	 * If we failed to allocate the request, and if the DMA didn't fail
12884 	 * anyway, set busy status.  This is just a resource allocation
12885 	 * failure.
12886 	 */
12887 	if ((rq == NULL)
12888 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12889 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12890 		ctl_set_busy(&io->scsiio);
12891 
12892 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12893 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12894 
12895 		if (rq != NULL)
12896 			ctl_dt_req_free(rq);
12897 
12898 		/*
12899 		 * The data move failed.  We need to return status back
12900 		 * to the other controller.  No point in trying to DMA
12901 		 * data to the remote controller.
12902 		 */
12903 
12904 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12905 
12906 		return (1);
12907 	}
12908 
12909 	local_sglist = io->io_hdr.local_sglist;
12910 	remote_sglist = io->io_hdr.remote_sglist;
12911 	local_used = 0;
12912 	remote_used = 0;
12913 	total_used = 0;
12914 
12915 	/*
12916 	 * Pull/push the data over the wire from/to the other controller.
12917 	 * This takes into account the possibility that the local and
12918 	 * remote sglists may not be identical in terms of the size of
12919 	 * the elements and the number of elements.
12920 	 *
12921 	 * One fundamental assumption here is that the length allocated for
12922 	 * both the local and remote sglists is identical.  Otherwise, we've
12923 	 * essentially got a coding error of some sort.
12924 	 */
12925 	isc_ret = CTL_HA_STATUS_SUCCESS;
12926 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12927 		uint32_t cur_len;
12928 		uint8_t *tmp_ptr;
12929 
12930 		rq->command = command;
12931 		rq->context = io;
12932 
12933 		/*
12934 		 * Both pointers should be aligned.  But it is possible
12935 		 * that the allocation length is not.  They should both
12936 		 * also have enough slack left over at the end, though,
12937 		 * to round up to the next 8 byte boundary.
12938 		 */
12939 		cur_len = MIN(local_sglist[i].len - local_used,
12940 			      remote_sglist[j].len - remote_used);
12941 		rq->size = cur_len;
12942 
12943 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12944 		tmp_ptr += local_used;
12945 
12946 #if 0
12947 		/* Use physical addresses when talking to ISC hardware */
12948 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12949 			/* XXX KDM use busdma */
12950 			rq->local = vtophys(tmp_ptr);
12951 		} else
12952 			rq->local = tmp_ptr;
12953 #else
12954 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12955 		    ("HA does not support BUS_ADDR"));
12956 		rq->local = tmp_ptr;
12957 #endif
12958 
12959 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12960 		tmp_ptr += remote_used;
12961 		rq->remote = tmp_ptr;
12962 
12963 		rq->callback = NULL;
12964 
12965 		local_used += cur_len;
12966 		if (local_used >= local_sglist[i].len) {
12967 			i++;
12968 			local_used = 0;
12969 		}
12970 
12971 		remote_used += cur_len;
12972 		if (remote_used >= remote_sglist[j].len) {
12973 			j++;
12974 			remote_used = 0;
12975 		}
12976 		total_used += cur_len;
12977 
12978 		if (total_used >= io->scsiio.kern_data_len)
12979 			rq->callback = callback;
12980 
12981 #if 0
12982 		printf("%s: %s: local %p remote %p size %d\n", __func__,
12983 		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12984 		       rq->local, rq->remote, rq->size);
12985 #endif
12986 
12987 		isc_ret = ctl_dt_single(rq);
12988 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12989 			break;
12990 	}
12991 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12992 		rq->ret = isc_ret;
12993 		callback(rq);
12994 	}
12995 
12996 	return (0);
12997 }
12998 
12999 static void
13000 ctl_datamove_remote_read(union ctl_io *io)
13001 {
13002 	int retval;
13003 	uint32_t i;
13004 
13005 	/*
13006 	 * This will send an error to the other controller in the case of a
13007 	 * failure.
13008 	 */
13009 	retval = ctl_datamove_remote_sgl_setup(io);
13010 	if (retval != 0)
13011 		return;
13012 
13013 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13014 					  ctl_datamove_remote_read_cb);
13015 	if (retval != 0) {
13016 		/*
13017 		 * Make sure we free memory if there was an error..  The
13018 		 * ctl_datamove_remote_xfer() function will send the
13019 		 * datamove done message, or call the callback with an
13020 		 * error if there is a problem.
13021 		 */
13022 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13023 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13024 		free(io->io_hdr.remote_sglist, M_CTL);
13025 		io->io_hdr.remote_sglist = NULL;
13026 		io->io_hdr.local_sglist = NULL;
13027 	}
13028 }
13029 
13030 /*
13031  * Process a datamove request from the other controller.  This is used for
13032  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13033  * first.  Once that is complete, the data gets DMAed into the remote
13034  * controller's memory.  For reads, we DMA from the remote controller's
13035  * memory into our memory first, and then move it out to the FETD.
13036  */
13037 static void
13038 ctl_datamove_remote(union ctl_io *io)
13039 {
13040 
13041 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
13042 
13043 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13044 		ctl_failover_io(io, /*have_lock*/ 0);
13045 		return;
13046 	}
13047 
13048 	/*
13049 	 * Note that we look for an aborted I/O here, but don't do some of
13050 	 * the other checks that ctl_datamove() normally does.
13051 	 * We don't need to run the datamove delay code, since that should
13052 	 * have been done if need be on the other controller.
13053 	 */
13054 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13055 		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13056 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13057 		       io->io_hdr.nexus.targ_port,
13058 		       io->io_hdr.nexus.targ_lun);
13059 		io->io_hdr.port_status = 31338;
13060 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13061 		return;
13062 	}
13063 
13064 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13065 		ctl_datamove_remote_write(io);
13066 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13067 		ctl_datamove_remote_read(io);
13068 	else {
13069 		io->io_hdr.port_status = 31339;
13070 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13071 	}
13072 }
13073 
13074 static void
13075 ctl_process_done(union ctl_io *io)
13076 {
13077 	struct ctl_softc *softc = CTL_SOFTC(io);
13078 	struct ctl_port *port = CTL_PORT(io);
13079 	struct ctl_lun *lun = CTL_LUN(io);
13080 	void (*fe_done)(union ctl_io *io);
13081 	union ctl_ha_msg msg;
13082 
13083 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13084 	fe_done = port->fe_done;
13085 
13086 #ifdef CTL_TIME_IO
13087 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13088 		char str[256];
13089 		char path_str[64];
13090 		struct sbuf sb;
13091 
13092 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13093 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13094 
13095 		sbuf_cat(&sb, path_str);
13096 		switch (io->io_hdr.io_type) {
13097 		case CTL_IO_SCSI:
13098 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13099 			sbuf_printf(&sb, "\n");
13100 			sbuf_cat(&sb, path_str);
13101 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13102 				    io->scsiio.tag_num, io->scsiio.tag_type);
13103 			break;
13104 		case CTL_IO_TASK:
13105 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13106 				    "Tag Type: %d\n", io->taskio.task_action,
13107 				    io->taskio.tag_num, io->taskio.tag_type);
13108 			break;
13109 		default:
13110 			panic("%s: Invalid CTL I/O type %d\n",
13111 			    __func__, io->io_hdr.io_type);
13112 		}
13113 		sbuf_cat(&sb, path_str);
13114 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13115 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13116 		sbuf_finish(&sb);
13117 		printf("%s", sbuf_data(&sb));
13118 	}
13119 #endif /* CTL_TIME_IO */
13120 
13121 	switch (io->io_hdr.io_type) {
13122 	case CTL_IO_SCSI:
13123 		break;
13124 	case CTL_IO_TASK:
13125 		if (ctl_debug & CTL_DEBUG_INFO)
13126 			ctl_io_error_print(io, NULL);
13127 		fe_done(io);
13128 		return;
13129 	default:
13130 		panic("%s: Invalid CTL I/O type %d\n",
13131 		    __func__, io->io_hdr.io_type);
13132 	}
13133 
13134 	if (lun == NULL) {
13135 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13136 				 io->io_hdr.nexus.targ_mapped_lun));
13137 		goto bailout;
13138 	}
13139 
13140 	mtx_lock(&lun->lun_lock);
13141 
13142 	/*
13143 	 * Check to see if we have any informational exception and status
13144 	 * of this command can be modified to report it in form of either
13145 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13146 	 */
13147 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13148 	    io->io_hdr.status == CTL_SUCCESS &&
13149 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13150 		uint8_t mrie = lun->MODE_IE.mrie;
13151 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13152 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13153 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13154 		     mrie == SIEP_MRIE_REC_UNCOND ||
13155 		     mrie == SIEP_MRIE_NO_SENSE) &&
13156 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13157 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13158 			ctl_set_sense(&io->scsiio,
13159 			      /*current_error*/ 1,
13160 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13161 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13162 			      /*asc*/ lun->ie_asc,
13163 			      /*ascq*/ lun->ie_ascq,
13164 			      SSD_ELEM_NONE);
13165 			lun->ie_reported = 1;
13166 		}
13167 	} else if (lun->ie_reported < 0)
13168 		lun->ie_reported = 0;
13169 
13170 	/*
13171 	 * Check to see if we have any errors to inject here.  We only
13172 	 * inject errors for commands that don't already have errors set.
13173 	 */
13174 	if (!STAILQ_EMPTY(&lun->error_list) &&
13175 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13176 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13177 		ctl_inject_error(lun, io);
13178 
13179 	/*
13180 	 * XXX KDM how do we treat commands that aren't completed
13181 	 * successfully?
13182 	 *
13183 	 * XXX KDM should we also track I/O latency?
13184 	 */
13185 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13186 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13187 		int type;
13188 #ifdef CTL_TIME_IO
13189 		struct bintime bt;
13190 
13191 		getbinuptime(&bt);
13192 		bintime_sub(&bt, &io->io_hdr.start_bt);
13193 #endif
13194 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13195 		    CTL_FLAG_DATA_IN)
13196 			type = CTL_STATS_READ;
13197 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13198 		    CTL_FLAG_DATA_OUT)
13199 			type = CTL_STATS_WRITE;
13200 		else
13201 			type = CTL_STATS_NO_IO;
13202 
13203 #ifdef CTL_LEGACY_STATS
13204 		uint32_t targ_port = port->targ_port;
13205 		lun->legacy_stats.ports[targ_port].bytes[type] +=
13206 		    io->scsiio.kern_total_len;
13207 		lun->legacy_stats.ports[targ_port].operations[type] ++;
13208 		lun->legacy_stats.ports[targ_port].num_dmas[type] +=
13209 		    io->io_hdr.num_dmas;
13210 #ifdef CTL_TIME_IO
13211 		bintime_add(&lun->legacy_stats.ports[targ_port].dma_time[type],
13212 		   &io->io_hdr.dma_bt);
13213 		bintime_add(&lun->legacy_stats.ports[targ_port].time[type],
13214 		    &bt);
13215 #endif
13216 #endif /* CTL_LEGACY_STATS */
13217 
13218 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
13219 		lun->stats.operations[type] ++;
13220 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13221 #ifdef CTL_TIME_IO
13222 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13223 		bintime_add(&lun->stats.time[type], &bt);
13224 #endif
13225 
13226 		mtx_lock(&port->port_lock);
13227 		port->stats.bytes[type] += io->scsiio.kern_total_len;
13228 		port->stats.operations[type] ++;
13229 		port->stats.dmas[type] += io->io_hdr.num_dmas;
13230 #ifdef CTL_TIME_IO
13231 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13232 		bintime_add(&port->stats.time[type], &bt);
13233 #endif
13234 		mtx_unlock(&port->port_lock);
13235 	}
13236 
13237 	/*
13238 	 * Remove this from the OOA queue.
13239 	 */
13240 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13241 #ifdef CTL_TIME_IO
13242 	if (TAILQ_EMPTY(&lun->ooa_queue))
13243 		lun->last_busy = getsbinuptime();
13244 #endif
13245 
13246 	/*
13247 	 * Run through the blocked queue on this LUN and see if anything
13248 	 * has become unblocked, now that this transaction is done.
13249 	 */
13250 	ctl_check_blocked(lun);
13251 
13252 	/*
13253 	 * If the LUN has been invalidated, free it if there is nothing
13254 	 * left on its OOA queue.
13255 	 */
13256 	if ((lun->flags & CTL_LUN_INVALID)
13257 	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13258 		mtx_unlock(&lun->lun_lock);
13259 		mtx_lock(&softc->ctl_lock);
13260 		ctl_free_lun(lun);
13261 		mtx_unlock(&softc->ctl_lock);
13262 	} else
13263 		mtx_unlock(&lun->lun_lock);
13264 
13265 bailout:
13266 
13267 	/*
13268 	 * If this command has been aborted, make sure we set the status
13269 	 * properly.  The FETD is responsible for freeing the I/O and doing
13270 	 * whatever it needs to do to clean up its state.
13271 	 */
13272 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13273 		ctl_set_task_aborted(&io->scsiio);
13274 
13275 	/*
13276 	 * If enabled, print command error status.
13277 	 */
13278 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13279 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13280 		ctl_io_error_print(io, NULL);
13281 
13282 	/*
13283 	 * Tell the FETD or the other shelf controller we're done with this
13284 	 * command.  Note that only SCSI commands get to this point.  Task
13285 	 * management commands are completed above.
13286 	 */
13287 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13288 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13289 		memset(&msg, 0, sizeof(msg));
13290 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13291 		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13292 		msg.hdr.nexus = io->io_hdr.nexus;
13293 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13294 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13295 		    M_WAITOK);
13296 	}
13297 
13298 	fe_done(io);
13299 }
13300 
13301 #ifdef CTL_WITH_CA
13302 /*
13303  * Front end should call this if it doesn't do autosense.  When the request
13304  * sense comes back in from the initiator, we'll dequeue this and send it.
13305  */
13306 int
13307 ctl_queue_sense(union ctl_io *io)
13308 {
13309 	struct ctl_softc *softc = CTL_SOFTC(io);
13310 	struct ctl_port *port = CTL_PORT(io);
13311 	struct ctl_lun *lun;
13312 	uint32_t initidx, targ_lun;
13313 
13314 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13315 
13316 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13317 
13318 	/*
13319 	 * LUN lookup will likely move to the ctl_work_thread() once we
13320 	 * have our new queueing infrastructure (that doesn't put things on
13321 	 * a per-LUN queue initially).  That is so that we can handle
13322 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13323 	 * can't deal with that right now.
13324 	 * If we don't have a LUN for this, just toss the sense information.
13325 	 */
13326 	mtx_lock(&softc->ctl_lock);
13327 	if (targ_lun >= CTL_MAX_LUNS ||
13328 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13329 		mtx_unlock(&softc->ctl_lock);
13330 		goto bailout;
13331 	}
13332 	mtx_lock(&lun->lun_lock);
13333 	mtx_unlock(&softc->ctl_lock);
13334 
13335 	/*
13336 	 * Already have CA set for this LUN...toss the sense information.
13337 	 */
13338 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13339 	if (ctl_is_set(lun->have_ca, initidx)) {
13340 		mtx_unlock(&lun->lun_lock);
13341 		goto bailout;
13342 	}
13343 
13344 	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13345 	       MIN(sizeof(lun->pending_sense[initidx]),
13346 	       sizeof(io->scsiio.sense_data)));
13347 	ctl_set_mask(lun->have_ca, initidx);
13348 	mtx_unlock(&lun->lun_lock);
13349 
13350 bailout:
13351 	ctl_free_io(io);
13352 	return (CTL_RETVAL_COMPLETE);
13353 }
13354 #endif
13355 
13356 /*
13357  * Primary command inlet from frontend ports.  All SCSI and task I/O
13358  * requests must go through this function.
13359  */
13360 int
13361 ctl_queue(union ctl_io *io)
13362 {
13363 	struct ctl_port *port = CTL_PORT(io);
13364 
13365 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13366 
13367 #ifdef CTL_TIME_IO
13368 	io->io_hdr.start_time = time_uptime;
13369 	getbinuptime(&io->io_hdr.start_bt);
13370 #endif /* CTL_TIME_IO */
13371 
13372 	/* Map FE-specific LUN ID into global one. */
13373 	io->io_hdr.nexus.targ_mapped_lun =
13374 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13375 
13376 	switch (io->io_hdr.io_type) {
13377 	case CTL_IO_SCSI:
13378 	case CTL_IO_TASK:
13379 		if (ctl_debug & CTL_DEBUG_CDB)
13380 			ctl_io_print(io);
13381 		ctl_enqueue_incoming(io);
13382 		break;
13383 	default:
13384 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13385 		return (EINVAL);
13386 	}
13387 
13388 	return (CTL_RETVAL_COMPLETE);
13389 }
13390 
13391 #ifdef CTL_IO_DELAY
13392 static void
13393 ctl_done_timer_wakeup(void *arg)
13394 {
13395 	union ctl_io *io;
13396 
13397 	io = (union ctl_io *)arg;
13398 	ctl_done(io);
13399 }
13400 #endif /* CTL_IO_DELAY */
13401 
13402 void
13403 ctl_serseq_done(union ctl_io *io)
13404 {
13405 	struct ctl_lun *lun = CTL_LUN(io);;
13406 
13407 	if (lun->be_lun == NULL ||
13408 	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13409 		return;
13410 	mtx_lock(&lun->lun_lock);
13411 	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13412 	ctl_check_blocked(lun);
13413 	mtx_unlock(&lun->lun_lock);
13414 }
13415 
13416 void
13417 ctl_done(union ctl_io *io)
13418 {
13419 
13420 	/*
13421 	 * Enable this to catch duplicate completion issues.
13422 	 */
13423 #if 0
13424 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13425 		printf("%s: type %d msg %d cdb %x iptl: "
13426 		       "%u:%u:%u tag 0x%04x "
13427 		       "flag %#x status %x\n",
13428 			__func__,
13429 			io->io_hdr.io_type,
13430 			io->io_hdr.msg_type,
13431 			io->scsiio.cdb[0],
13432 			io->io_hdr.nexus.initid,
13433 			io->io_hdr.nexus.targ_port,
13434 			io->io_hdr.nexus.targ_lun,
13435 			(io->io_hdr.io_type ==
13436 			CTL_IO_TASK) ?
13437 			io->taskio.tag_num :
13438 			io->scsiio.tag_num,
13439 		        io->io_hdr.flags,
13440 			io->io_hdr.status);
13441 	} else
13442 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13443 #endif
13444 
13445 	/*
13446 	 * This is an internal copy of an I/O, and should not go through
13447 	 * the normal done processing logic.
13448 	 */
13449 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13450 		return;
13451 
13452 #ifdef CTL_IO_DELAY
13453 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13454 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13455 	} else {
13456 		struct ctl_lun *lun = CTL_LUN(io);
13457 
13458 		if ((lun != NULL)
13459 		 && (lun->delay_info.done_delay > 0)) {
13460 
13461 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13462 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13463 			callout_reset(&io->io_hdr.delay_callout,
13464 				      lun->delay_info.done_delay * hz,
13465 				      ctl_done_timer_wakeup, io);
13466 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13467 				lun->delay_info.done_delay = 0;
13468 			return;
13469 		}
13470 	}
13471 #endif /* CTL_IO_DELAY */
13472 
13473 	ctl_enqueue_done(io);
13474 }
13475 
13476 static void
13477 ctl_work_thread(void *arg)
13478 {
13479 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13480 	struct ctl_softc *softc = thr->ctl_softc;
13481 	union ctl_io *io;
13482 	int retval;
13483 
13484 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13485 
13486 	for (;;) {
13487 		/*
13488 		 * We handle the queues in this order:
13489 		 * - ISC
13490 		 * - done queue (to free up resources, unblock other commands)
13491 		 * - RtR queue
13492 		 * - incoming queue
13493 		 *
13494 		 * If those queues are empty, we break out of the loop and
13495 		 * go to sleep.
13496 		 */
13497 		mtx_lock(&thr->queue_lock);
13498 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13499 		if (io != NULL) {
13500 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13501 			mtx_unlock(&thr->queue_lock);
13502 			ctl_handle_isc(io);
13503 			continue;
13504 		}
13505 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13506 		if (io != NULL) {
13507 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13508 			/* clear any blocked commands, call fe_done */
13509 			mtx_unlock(&thr->queue_lock);
13510 			ctl_process_done(io);
13511 			continue;
13512 		}
13513 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13514 		if (io != NULL) {
13515 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13516 			mtx_unlock(&thr->queue_lock);
13517 			if (io->io_hdr.io_type == CTL_IO_TASK)
13518 				ctl_run_task(io);
13519 			else
13520 				ctl_scsiio_precheck(softc, &io->scsiio);
13521 			continue;
13522 		}
13523 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13524 		if (io != NULL) {
13525 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13526 			mtx_unlock(&thr->queue_lock);
13527 			retval = ctl_scsiio(&io->scsiio);
13528 			if (retval != CTL_RETVAL_COMPLETE)
13529 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13530 			continue;
13531 		}
13532 
13533 		/* Sleep until we have something to do. */
13534 		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13535 	}
13536 }
13537 
13538 static void
13539 ctl_lun_thread(void *arg)
13540 {
13541 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13542 	struct ctl_be_lun *be_lun;
13543 
13544 	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13545 
13546 	for (;;) {
13547 		mtx_lock(&softc->ctl_lock);
13548 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13549 		if (be_lun != NULL) {
13550 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13551 			mtx_unlock(&softc->ctl_lock);
13552 			ctl_create_lun(be_lun);
13553 			continue;
13554 		}
13555 
13556 		/* Sleep until we have something to do. */
13557 		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13558 		    PDROP | PRIBIO, "-", 0);
13559 	}
13560 }
13561 
13562 static void
13563 ctl_thresh_thread(void *arg)
13564 {
13565 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13566 	struct ctl_lun *lun;
13567 	struct ctl_logical_block_provisioning_page *page;
13568 	const char *attr;
13569 	union ctl_ha_msg msg;
13570 	uint64_t thres, val;
13571 	int i, e, set;
13572 
13573 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13574 
13575 	for (;;) {
13576 		mtx_lock(&softc->ctl_lock);
13577 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13578 			if ((lun->flags & CTL_LUN_DISABLED) ||
13579 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13580 			    lun->backend->lun_attr == NULL)
13581 				continue;
13582 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13583 			    softc->ha_mode == CTL_HA_MODE_XFER)
13584 				continue;
13585 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13586 				continue;
13587 			e = 0;
13588 			page = &lun->MODE_LBP;
13589 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13590 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13591 					continue;
13592 				thres = scsi_4btoul(page->descr[i].count);
13593 				thres <<= CTL_LBP_EXPONENT;
13594 				switch (page->descr[i].resource) {
13595 				case 0x01:
13596 					attr = "blocksavail";
13597 					break;
13598 				case 0x02:
13599 					attr = "blocksused";
13600 					break;
13601 				case 0xf1:
13602 					attr = "poolblocksavail";
13603 					break;
13604 				case 0xf2:
13605 					attr = "poolblocksused";
13606 					break;
13607 				default:
13608 					continue;
13609 				}
13610 				mtx_unlock(&softc->ctl_lock); // XXX
13611 				val = lun->backend->lun_attr(
13612 				    lun->be_lun->be_lun, attr);
13613 				mtx_lock(&softc->ctl_lock);
13614 				if (val == UINT64_MAX)
13615 					continue;
13616 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13617 				    == SLBPPD_ARMING_INC)
13618 					e = (val >= thres);
13619 				else
13620 					e = (val <= thres);
13621 				if (e)
13622 					break;
13623 			}
13624 			mtx_lock(&lun->lun_lock);
13625 			if (e) {
13626 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13627 				    (uint8_t *)page, lun->ua_tpt_info);
13628 				if (lun->lasttpt == 0 ||
13629 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13630 					lun->lasttpt = time_uptime;
13631 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13632 					set = 1;
13633 				} else
13634 					set = 0;
13635 			} else {
13636 				lun->lasttpt = 0;
13637 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13638 				set = -1;
13639 			}
13640 			mtx_unlock(&lun->lun_lock);
13641 			if (set != 0 &&
13642 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13643 				/* Send msg to other side. */
13644 				bzero(&msg.ua, sizeof(msg.ua));
13645 				msg.hdr.msg_type = CTL_MSG_UA;
13646 				msg.hdr.nexus.initid = -1;
13647 				msg.hdr.nexus.targ_port = -1;
13648 				msg.hdr.nexus.targ_lun = lun->lun;
13649 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13650 				msg.ua.ua_all = 1;
13651 				msg.ua.ua_set = (set > 0);
13652 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13653 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13654 				mtx_unlock(&softc->ctl_lock); // XXX
13655 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13656 				    sizeof(msg.ua), M_WAITOK);
13657 				mtx_lock(&softc->ctl_lock);
13658 			}
13659 		}
13660 		mtx_unlock(&softc->ctl_lock);
13661 		pause("-", CTL_LBP_PERIOD * hz);
13662 	}
13663 }
13664 
13665 static void
13666 ctl_enqueue_incoming(union ctl_io *io)
13667 {
13668 	struct ctl_softc *softc = CTL_SOFTC(io);
13669 	struct ctl_thread *thr;
13670 	u_int idx;
13671 
13672 	idx = (io->io_hdr.nexus.targ_port * 127 +
13673 	       io->io_hdr.nexus.initid) % worker_threads;
13674 	thr = &softc->threads[idx];
13675 	mtx_lock(&thr->queue_lock);
13676 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13677 	mtx_unlock(&thr->queue_lock);
13678 	wakeup(thr);
13679 }
13680 
13681 static void
13682 ctl_enqueue_rtr(union ctl_io *io)
13683 {
13684 	struct ctl_softc *softc = CTL_SOFTC(io);
13685 	struct ctl_thread *thr;
13686 
13687 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13688 	mtx_lock(&thr->queue_lock);
13689 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13690 	mtx_unlock(&thr->queue_lock);
13691 	wakeup(thr);
13692 }
13693 
13694 static void
13695 ctl_enqueue_done(union ctl_io *io)
13696 {
13697 	struct ctl_softc *softc = CTL_SOFTC(io);
13698 	struct ctl_thread *thr;
13699 
13700 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13701 	mtx_lock(&thr->queue_lock);
13702 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13703 	mtx_unlock(&thr->queue_lock);
13704 	wakeup(thr);
13705 }
13706 
13707 static void
13708 ctl_enqueue_isc(union ctl_io *io)
13709 {
13710 	struct ctl_softc *softc = CTL_SOFTC(io);
13711 	struct ctl_thread *thr;
13712 
13713 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13714 	mtx_lock(&thr->queue_lock);
13715 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13716 	mtx_unlock(&thr->queue_lock);
13717 	wakeup(thr);
13718 }
13719 
13720 /*
13721  *  vim: ts=8
13722  */
13723