xref: /freebsd/sys/cam/ctl/ctl.c (revision 63d1fd5970ec814904aa0f4580b10a0d302d08b2)
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 		/*
5057 		 * For hardware error sense keys, the sense key
5058 		 * specific value is defined to be a retry count,
5059 		 * but we use it to pass back an internal FETD
5060 		 * error code.  XXX KDM  Hopefully the FETD is only
5061 		 * using 16 bits for an error code, since that's
5062 		 * all the space we have in the sks field.
5063 		 */
5064 		ctl_set_internal_failure(&io->scsiio,
5065 					 /*sks_valid*/ 1,
5066 					 /*retry_count*/
5067 					 io->io_hdr.port_status);
5068 	}
5069 
5070 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5071 		ctl_data_print(io);
5072 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5073 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5074 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5075 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5076 		/*
5077 		 * XXX KDM just assuming a single pointer here, and not a
5078 		 * S/G list.  If we start using S/G lists for config data,
5079 		 * we'll need to know how to clean them up here as well.
5080 		 */
5081 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5082 			free(io->scsiio.kern_data_ptr, M_CTL);
5083 		ctl_done(io);
5084 		retval = CTL_RETVAL_COMPLETE;
5085 	} else {
5086 		/*
5087 		 * XXX KDM now we need to continue data movement.  Some
5088 		 * options:
5089 		 * - call ctl_scsiio() again?  We don't do this for data
5090 		 *   writes, because for those at least we know ahead of
5091 		 *   time where the write will go and how long it is.  For
5092 		 *   config writes, though, that information is largely
5093 		 *   contained within the write itself, thus we need to
5094 		 *   parse out the data again.
5095 		 *
5096 		 * - Call some other function once the data is in?
5097 		 */
5098 
5099 		/*
5100 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5101 		 * bits to see whether we're allocated or not.
5102 		 */
5103 		retval = ctl_scsiio(&io->scsiio);
5104 	}
5105 	return (retval);
5106 }
5107 
5108 /*
5109  * This gets called by a backend driver when it is done with a
5110  * data_submit method.
5111  */
5112 void
5113 ctl_data_submit_done(union ctl_io *io)
5114 {
5115 	/*
5116 	 * If the IO_CONT flag is set, we need to call the supplied
5117 	 * function to continue processing the I/O, instead of completing
5118 	 * the I/O just yet.
5119 	 *
5120 	 * If there is an error, though, we don't want to keep processing.
5121 	 * Instead, just send status back to the initiator.
5122 	 */
5123 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5124 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5125 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5126 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5127 		io->scsiio.io_cont(io);
5128 		return;
5129 	}
5130 	ctl_done(io);
5131 }
5132 
5133 /*
5134  * This gets called by a backend driver when it is done with a
5135  * configuration write.
5136  */
5137 void
5138 ctl_config_write_done(union ctl_io *io)
5139 {
5140 	uint8_t *buf;
5141 
5142 	/*
5143 	 * If the IO_CONT flag is set, we need to call the supplied
5144 	 * function to continue processing the I/O, instead of completing
5145 	 * the I/O just yet.
5146 	 *
5147 	 * If there is an error, though, we don't want to keep processing.
5148 	 * Instead, just send status back to the initiator.
5149 	 */
5150 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5151 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5152 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5153 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5154 		io->scsiio.io_cont(io);
5155 		return;
5156 	}
5157 	/*
5158 	 * Since a configuration write can be done for commands that actually
5159 	 * have data allocated, like write buffer, and commands that have
5160 	 * no data, like start/stop unit, we need to check here.
5161 	 */
5162 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5163 		buf = io->scsiio.kern_data_ptr;
5164 	else
5165 		buf = NULL;
5166 	ctl_done(io);
5167 	if (buf)
5168 		free(buf, M_CTL);
5169 }
5170 
5171 void
5172 ctl_config_read_done(union ctl_io *io)
5173 {
5174 	uint8_t *buf;
5175 
5176 	/*
5177 	 * If there is some error -- we are done, skip data transfer.
5178 	 */
5179 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5180 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5181 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5182 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5183 			buf = io->scsiio.kern_data_ptr;
5184 		else
5185 			buf = NULL;
5186 		ctl_done(io);
5187 		if (buf)
5188 			free(buf, M_CTL);
5189 		return;
5190 	}
5191 
5192 	/*
5193 	 * If the IO_CONT flag is set, we need to call the supplied
5194 	 * function to continue processing the I/O, instead of completing
5195 	 * the I/O just yet.
5196 	 */
5197 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5198 		io->scsiio.io_cont(io);
5199 		return;
5200 	}
5201 
5202 	ctl_datamove(io);
5203 }
5204 
5205 /*
5206  * SCSI release command.
5207  */
5208 int
5209 ctl_scsi_release(struct ctl_scsiio *ctsio)
5210 {
5211 	struct ctl_lun *lun = CTL_LUN(ctsio);
5212 	uint32_t residx;
5213 
5214 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5215 
5216 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5217 
5218 	/*
5219 	 * XXX KDM right now, we only support LUN reservation.  We don't
5220 	 * support 3rd party reservations, or extent reservations, which
5221 	 * might actually need the parameter list.  If we've gotten this
5222 	 * far, we've got a LUN reservation.  Anything else got kicked out
5223 	 * above.  So, according to SPC, ignore the length.
5224 	 */
5225 
5226 	mtx_lock(&lun->lun_lock);
5227 
5228 	/*
5229 	 * According to SPC, it is not an error for an intiator to attempt
5230 	 * to release a reservation on a LUN that isn't reserved, or that
5231 	 * is reserved by another initiator.  The reservation can only be
5232 	 * released, though, by the initiator who made it or by one of
5233 	 * several reset type events.
5234 	 */
5235 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5236 			lun->flags &= ~CTL_LUN_RESERVED;
5237 
5238 	mtx_unlock(&lun->lun_lock);
5239 
5240 	ctl_set_success(ctsio);
5241 	ctl_done((union ctl_io *)ctsio);
5242 	return (CTL_RETVAL_COMPLETE);
5243 }
5244 
5245 int
5246 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5247 {
5248 	struct ctl_lun *lun = CTL_LUN(ctsio);
5249 	uint32_t residx;
5250 
5251 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5252 
5253 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5254 
5255 	/*
5256 	 * XXX KDM right now, we only support LUN reservation.  We don't
5257 	 * support 3rd party reservations, or extent reservations, which
5258 	 * might actually need the parameter list.  If we've gotten this
5259 	 * far, we've got a LUN reservation.  Anything else got kicked out
5260 	 * above.  So, according to SPC, ignore the length.
5261 	 */
5262 
5263 	mtx_lock(&lun->lun_lock);
5264 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5265 		ctl_set_reservation_conflict(ctsio);
5266 		goto bailout;
5267 	}
5268 
5269 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5270 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5271 		ctl_set_success(ctsio);
5272 		goto bailout;
5273 	}
5274 
5275 	lun->flags |= CTL_LUN_RESERVED;
5276 	lun->res_idx = residx;
5277 	ctl_set_success(ctsio);
5278 
5279 bailout:
5280 	mtx_unlock(&lun->lun_lock);
5281 	ctl_done((union ctl_io *)ctsio);
5282 	return (CTL_RETVAL_COMPLETE);
5283 }
5284 
5285 int
5286 ctl_start_stop(struct ctl_scsiio *ctsio)
5287 {
5288 	struct ctl_lun *lun = CTL_LUN(ctsio);
5289 	struct scsi_start_stop_unit *cdb;
5290 	int retval;
5291 
5292 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5293 
5294 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5295 
5296 	if ((cdb->how & SSS_PC_MASK) == 0) {
5297 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5298 		    (cdb->how & SSS_START) == 0) {
5299 			uint32_t residx;
5300 
5301 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5302 			if (ctl_get_prkey(lun, residx) == 0 ||
5303 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5304 
5305 				ctl_set_reservation_conflict(ctsio);
5306 				ctl_done((union ctl_io *)ctsio);
5307 				return (CTL_RETVAL_COMPLETE);
5308 			}
5309 		}
5310 
5311 		if ((cdb->how & SSS_LOEJ) &&
5312 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5313 			ctl_set_invalid_field(ctsio,
5314 					      /*sks_valid*/ 1,
5315 					      /*command*/ 1,
5316 					      /*field*/ 4,
5317 					      /*bit_valid*/ 1,
5318 					      /*bit*/ 1);
5319 			ctl_done((union ctl_io *)ctsio);
5320 			return (CTL_RETVAL_COMPLETE);
5321 		}
5322 
5323 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5324 		    lun->prevent_count > 0) {
5325 			/* "Medium removal prevented" */
5326 			ctl_set_sense(ctsio, /*current_error*/ 1,
5327 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5328 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5329 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5330 			ctl_done((union ctl_io *)ctsio);
5331 			return (CTL_RETVAL_COMPLETE);
5332 		}
5333 	}
5334 
5335 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5336 	return (retval);
5337 }
5338 
5339 int
5340 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5341 {
5342 	struct ctl_lun *lun = CTL_LUN(ctsio);
5343 	struct scsi_prevent *cdb;
5344 	int retval;
5345 	uint32_t initidx;
5346 
5347 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5348 
5349 	cdb = (struct scsi_prevent *)ctsio->cdb;
5350 
5351 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5352 		ctl_set_invalid_opcode(ctsio);
5353 		ctl_done((union ctl_io *)ctsio);
5354 		return (CTL_RETVAL_COMPLETE);
5355 	}
5356 
5357 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5358 	mtx_lock(&lun->lun_lock);
5359 	if ((cdb->how & PR_PREVENT) &&
5360 	    ctl_is_set(lun->prevent, initidx) == 0) {
5361 		ctl_set_mask(lun->prevent, initidx);
5362 		lun->prevent_count++;
5363 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5364 	    ctl_is_set(lun->prevent, initidx)) {
5365 		ctl_clear_mask(lun->prevent, initidx);
5366 		lun->prevent_count--;
5367 	}
5368 	mtx_unlock(&lun->lun_lock);
5369 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5370 	return (retval);
5371 }
5372 
5373 /*
5374  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5375  * we don't really do anything with the LBA and length fields if the user
5376  * passes them in.  Instead we'll just flush out the cache for the entire
5377  * LUN.
5378  */
5379 int
5380 ctl_sync_cache(struct ctl_scsiio *ctsio)
5381 {
5382 	struct ctl_lun *lun = CTL_LUN(ctsio);
5383 	struct ctl_lba_len_flags *lbalen;
5384 	uint64_t starting_lba;
5385 	uint32_t block_count;
5386 	int retval;
5387 	uint8_t byte2;
5388 
5389 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5390 
5391 	retval = 0;
5392 
5393 	switch (ctsio->cdb[0]) {
5394 	case SYNCHRONIZE_CACHE: {
5395 		struct scsi_sync_cache *cdb;
5396 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5397 
5398 		starting_lba = scsi_4btoul(cdb->begin_lba);
5399 		block_count = scsi_2btoul(cdb->lb_count);
5400 		byte2 = cdb->byte2;
5401 		break;
5402 	}
5403 	case SYNCHRONIZE_CACHE_16: {
5404 		struct scsi_sync_cache_16 *cdb;
5405 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5406 
5407 		starting_lba = scsi_8btou64(cdb->begin_lba);
5408 		block_count = scsi_4btoul(cdb->lb_count);
5409 		byte2 = cdb->byte2;
5410 		break;
5411 	}
5412 	default:
5413 		ctl_set_invalid_opcode(ctsio);
5414 		ctl_done((union ctl_io *)ctsio);
5415 		goto bailout;
5416 		break; /* NOTREACHED */
5417 	}
5418 
5419 	/*
5420 	 * We check the LBA and length, but don't do anything with them.
5421 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5422 	 * get flushed.  This check will just help satisfy anyone who wants
5423 	 * to see an error for an out of range LBA.
5424 	 */
5425 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5426 		ctl_set_lba_out_of_range(ctsio,
5427 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5428 		ctl_done((union ctl_io *)ctsio);
5429 		goto bailout;
5430 	}
5431 
5432 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5433 	lbalen->lba = starting_lba;
5434 	lbalen->len = block_count;
5435 	lbalen->flags = byte2;
5436 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5437 
5438 bailout:
5439 	return (retval);
5440 }
5441 
5442 int
5443 ctl_format(struct ctl_scsiio *ctsio)
5444 {
5445 	struct scsi_format *cdb;
5446 	int length, defect_list_len;
5447 
5448 	CTL_DEBUG_PRINT(("ctl_format\n"));
5449 
5450 	cdb = (struct scsi_format *)ctsio->cdb;
5451 
5452 	length = 0;
5453 	if (cdb->byte2 & SF_FMTDATA) {
5454 		if (cdb->byte2 & SF_LONGLIST)
5455 			length = sizeof(struct scsi_format_header_long);
5456 		else
5457 			length = sizeof(struct scsi_format_header_short);
5458 	}
5459 
5460 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5461 	 && (length > 0)) {
5462 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5463 		ctsio->kern_data_len = length;
5464 		ctsio->kern_total_len = length;
5465 		ctsio->kern_data_resid = 0;
5466 		ctsio->kern_rel_offset = 0;
5467 		ctsio->kern_sg_entries = 0;
5468 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5469 		ctsio->be_move_done = ctl_config_move_done;
5470 		ctl_datamove((union ctl_io *)ctsio);
5471 
5472 		return (CTL_RETVAL_COMPLETE);
5473 	}
5474 
5475 	defect_list_len = 0;
5476 
5477 	if (cdb->byte2 & SF_FMTDATA) {
5478 		if (cdb->byte2 & SF_LONGLIST) {
5479 			struct scsi_format_header_long *header;
5480 
5481 			header = (struct scsi_format_header_long *)
5482 				ctsio->kern_data_ptr;
5483 
5484 			defect_list_len = scsi_4btoul(header->defect_list_len);
5485 			if (defect_list_len != 0) {
5486 				ctl_set_invalid_field(ctsio,
5487 						      /*sks_valid*/ 1,
5488 						      /*command*/ 0,
5489 						      /*field*/ 2,
5490 						      /*bit_valid*/ 0,
5491 						      /*bit*/ 0);
5492 				goto bailout;
5493 			}
5494 		} else {
5495 			struct scsi_format_header_short *header;
5496 
5497 			header = (struct scsi_format_header_short *)
5498 				ctsio->kern_data_ptr;
5499 
5500 			defect_list_len = scsi_2btoul(header->defect_list_len);
5501 			if (defect_list_len != 0) {
5502 				ctl_set_invalid_field(ctsio,
5503 						      /*sks_valid*/ 1,
5504 						      /*command*/ 0,
5505 						      /*field*/ 2,
5506 						      /*bit_valid*/ 0,
5507 						      /*bit*/ 0);
5508 				goto bailout;
5509 			}
5510 		}
5511 	}
5512 
5513 	ctl_set_success(ctsio);
5514 bailout:
5515 
5516 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5517 		free(ctsio->kern_data_ptr, M_CTL);
5518 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5519 	}
5520 
5521 	ctl_done((union ctl_io *)ctsio);
5522 	return (CTL_RETVAL_COMPLETE);
5523 }
5524 
5525 int
5526 ctl_read_buffer(struct ctl_scsiio *ctsio)
5527 {
5528 	struct ctl_lun *lun = CTL_LUN(ctsio);
5529 	uint64_t buffer_offset;
5530 	uint32_t len;
5531 	uint8_t byte2;
5532 	static uint8_t descr[4];
5533 	static uint8_t echo_descr[4] = { 0 };
5534 
5535 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5536 
5537 	switch (ctsio->cdb[0]) {
5538 	case READ_BUFFER: {
5539 		struct scsi_read_buffer *cdb;
5540 
5541 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5542 		buffer_offset = scsi_3btoul(cdb->offset);
5543 		len = scsi_3btoul(cdb->length);
5544 		byte2 = cdb->byte2;
5545 		break;
5546 	}
5547 	case READ_BUFFER_16: {
5548 		struct scsi_read_buffer_16 *cdb;
5549 
5550 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5551 		buffer_offset = scsi_8btou64(cdb->offset);
5552 		len = scsi_4btoul(cdb->length);
5553 		byte2 = cdb->byte2;
5554 		break;
5555 	}
5556 	default: /* This shouldn't happen. */
5557 		ctl_set_invalid_opcode(ctsio);
5558 		ctl_done((union ctl_io *)ctsio);
5559 		return (CTL_RETVAL_COMPLETE);
5560 	}
5561 
5562 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5563 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5564 		ctl_set_invalid_field(ctsio,
5565 				      /*sks_valid*/ 1,
5566 				      /*command*/ 1,
5567 				      /*field*/ 6,
5568 				      /*bit_valid*/ 0,
5569 				      /*bit*/ 0);
5570 		ctl_done((union ctl_io *)ctsio);
5571 		return (CTL_RETVAL_COMPLETE);
5572 	}
5573 
5574 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5575 		descr[0] = 0;
5576 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5577 		ctsio->kern_data_ptr = descr;
5578 		len = min(len, sizeof(descr));
5579 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5580 		ctsio->kern_data_ptr = echo_descr;
5581 		len = min(len, sizeof(echo_descr));
5582 	} else {
5583 		if (lun->write_buffer == NULL) {
5584 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5585 			    M_CTL, M_WAITOK);
5586 		}
5587 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5588 	}
5589 	ctsio->kern_data_len = len;
5590 	ctsio->kern_total_len = len;
5591 	ctsio->kern_data_resid = 0;
5592 	ctsio->kern_rel_offset = 0;
5593 	ctsio->kern_sg_entries = 0;
5594 	ctl_set_success(ctsio);
5595 	ctsio->be_move_done = ctl_config_move_done;
5596 	ctl_datamove((union ctl_io *)ctsio);
5597 	return (CTL_RETVAL_COMPLETE);
5598 }
5599 
5600 int
5601 ctl_write_buffer(struct ctl_scsiio *ctsio)
5602 {
5603 	struct ctl_lun *lun = CTL_LUN(ctsio);
5604 	struct scsi_write_buffer *cdb;
5605 	int buffer_offset, len;
5606 
5607 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5608 
5609 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5610 
5611 	len = scsi_3btoul(cdb->length);
5612 	buffer_offset = scsi_3btoul(cdb->offset);
5613 
5614 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5615 		ctl_set_invalid_field(ctsio,
5616 				      /*sks_valid*/ 1,
5617 				      /*command*/ 1,
5618 				      /*field*/ 6,
5619 				      /*bit_valid*/ 0,
5620 				      /*bit*/ 0);
5621 		ctl_done((union ctl_io *)ctsio);
5622 		return (CTL_RETVAL_COMPLETE);
5623 	}
5624 
5625 	/*
5626 	 * If we've got a kernel request that hasn't been malloced yet,
5627 	 * malloc it and tell the caller the data buffer is here.
5628 	 */
5629 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5630 		if (lun->write_buffer == NULL) {
5631 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5632 			    M_CTL, M_WAITOK);
5633 		}
5634 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5635 		ctsio->kern_data_len = len;
5636 		ctsio->kern_total_len = len;
5637 		ctsio->kern_data_resid = 0;
5638 		ctsio->kern_rel_offset = 0;
5639 		ctsio->kern_sg_entries = 0;
5640 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5641 		ctsio->be_move_done = ctl_config_move_done;
5642 		ctl_datamove((union ctl_io *)ctsio);
5643 
5644 		return (CTL_RETVAL_COMPLETE);
5645 	}
5646 
5647 	ctl_set_success(ctsio);
5648 	ctl_done((union ctl_io *)ctsio);
5649 	return (CTL_RETVAL_COMPLETE);
5650 }
5651 
5652 int
5653 ctl_write_same(struct ctl_scsiio *ctsio)
5654 {
5655 	struct ctl_lun *lun = CTL_LUN(ctsio);
5656 	struct ctl_lba_len_flags *lbalen;
5657 	uint64_t lba;
5658 	uint32_t num_blocks;
5659 	int len, retval;
5660 	uint8_t byte2;
5661 
5662 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5663 
5664 	switch (ctsio->cdb[0]) {
5665 	case WRITE_SAME_10: {
5666 		struct scsi_write_same_10 *cdb;
5667 
5668 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5669 
5670 		lba = scsi_4btoul(cdb->addr);
5671 		num_blocks = scsi_2btoul(cdb->length);
5672 		byte2 = cdb->byte2;
5673 		break;
5674 	}
5675 	case WRITE_SAME_16: {
5676 		struct scsi_write_same_16 *cdb;
5677 
5678 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5679 
5680 		lba = scsi_8btou64(cdb->addr);
5681 		num_blocks = scsi_4btoul(cdb->length);
5682 		byte2 = cdb->byte2;
5683 		break;
5684 	}
5685 	default:
5686 		/*
5687 		 * We got a command we don't support.  This shouldn't
5688 		 * happen, commands should be filtered out above us.
5689 		 */
5690 		ctl_set_invalid_opcode(ctsio);
5691 		ctl_done((union ctl_io *)ctsio);
5692 
5693 		return (CTL_RETVAL_COMPLETE);
5694 		break; /* NOTREACHED */
5695 	}
5696 
5697 	/* ANCHOR flag can be used only together with UNMAP */
5698 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5699 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5700 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5701 		ctl_done((union ctl_io *)ctsio);
5702 		return (CTL_RETVAL_COMPLETE);
5703 	}
5704 
5705 	/*
5706 	 * The first check is to make sure we're in bounds, the second
5707 	 * check is to catch wrap-around problems.  If the lba + num blocks
5708 	 * is less than the lba, then we've wrapped around and the block
5709 	 * range is invalid anyway.
5710 	 */
5711 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5712 	 || ((lba + num_blocks) < lba)) {
5713 		ctl_set_lba_out_of_range(ctsio,
5714 		    MAX(lba, lun->be_lun->maxlba + 1));
5715 		ctl_done((union ctl_io *)ctsio);
5716 		return (CTL_RETVAL_COMPLETE);
5717 	}
5718 
5719 	/* Zero number of blocks means "to the last logical block" */
5720 	if (num_blocks == 0) {
5721 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5722 			ctl_set_invalid_field(ctsio,
5723 					      /*sks_valid*/ 0,
5724 					      /*command*/ 1,
5725 					      /*field*/ 0,
5726 					      /*bit_valid*/ 0,
5727 					      /*bit*/ 0);
5728 			ctl_done((union ctl_io *)ctsio);
5729 			return (CTL_RETVAL_COMPLETE);
5730 		}
5731 		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5732 	}
5733 
5734 	len = lun->be_lun->blocksize;
5735 
5736 	/*
5737 	 * If we've got a kernel request that hasn't been malloced yet,
5738 	 * malloc it and tell the caller the data buffer is here.
5739 	 */
5740 	if ((byte2 & SWS_NDOB) == 0 &&
5741 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5742 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5743 		ctsio->kern_data_len = len;
5744 		ctsio->kern_total_len = len;
5745 		ctsio->kern_data_resid = 0;
5746 		ctsio->kern_rel_offset = 0;
5747 		ctsio->kern_sg_entries = 0;
5748 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5749 		ctsio->be_move_done = ctl_config_move_done;
5750 		ctl_datamove((union ctl_io *)ctsio);
5751 
5752 		return (CTL_RETVAL_COMPLETE);
5753 	}
5754 
5755 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5756 	lbalen->lba = lba;
5757 	lbalen->len = num_blocks;
5758 	lbalen->flags = byte2;
5759 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5760 
5761 	return (retval);
5762 }
5763 
5764 int
5765 ctl_unmap(struct ctl_scsiio *ctsio)
5766 {
5767 	struct ctl_lun *lun = CTL_LUN(ctsio);
5768 	struct scsi_unmap *cdb;
5769 	struct ctl_ptr_len_flags *ptrlen;
5770 	struct scsi_unmap_header *hdr;
5771 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5772 	uint64_t lba;
5773 	uint32_t num_blocks;
5774 	int len, retval;
5775 	uint8_t byte2;
5776 
5777 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5778 
5779 	cdb = (struct scsi_unmap *)ctsio->cdb;
5780 	len = scsi_2btoul(cdb->length);
5781 	byte2 = cdb->byte2;
5782 
5783 	/*
5784 	 * If we've got a kernel request that hasn't been malloced yet,
5785 	 * malloc it and tell the caller the data buffer is here.
5786 	 */
5787 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5788 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5789 		ctsio->kern_data_len = len;
5790 		ctsio->kern_total_len = len;
5791 		ctsio->kern_data_resid = 0;
5792 		ctsio->kern_rel_offset = 0;
5793 		ctsio->kern_sg_entries = 0;
5794 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5795 		ctsio->be_move_done = ctl_config_move_done;
5796 		ctl_datamove((union ctl_io *)ctsio);
5797 
5798 		return (CTL_RETVAL_COMPLETE);
5799 	}
5800 
5801 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5802 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5803 	if (len < sizeof (*hdr) ||
5804 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5805 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5806 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5807 		ctl_set_invalid_field(ctsio,
5808 				      /*sks_valid*/ 0,
5809 				      /*command*/ 0,
5810 				      /*field*/ 0,
5811 				      /*bit_valid*/ 0,
5812 				      /*bit*/ 0);
5813 		goto done;
5814 	}
5815 	len = scsi_2btoul(hdr->desc_length);
5816 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5817 	end = buf + len / sizeof(*buf);
5818 
5819 	endnz = buf;
5820 	for (range = buf; range < end; range++) {
5821 		lba = scsi_8btou64(range->lba);
5822 		num_blocks = scsi_4btoul(range->length);
5823 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5824 		 || ((lba + num_blocks) < lba)) {
5825 			ctl_set_lba_out_of_range(ctsio,
5826 			    MAX(lba, lun->be_lun->maxlba + 1));
5827 			ctl_done((union ctl_io *)ctsio);
5828 			return (CTL_RETVAL_COMPLETE);
5829 		}
5830 		if (num_blocks != 0)
5831 			endnz = range + 1;
5832 	}
5833 
5834 	/*
5835 	 * Block backend can not handle zero last range.
5836 	 * Filter it out and return if there is nothing left.
5837 	 */
5838 	len = (uint8_t *)endnz - (uint8_t *)buf;
5839 	if (len == 0) {
5840 		ctl_set_success(ctsio);
5841 		goto done;
5842 	}
5843 
5844 	mtx_lock(&lun->lun_lock);
5845 	ptrlen = (struct ctl_ptr_len_flags *)
5846 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5847 	ptrlen->ptr = (void *)buf;
5848 	ptrlen->len = len;
5849 	ptrlen->flags = byte2;
5850 	ctl_check_blocked(lun);
5851 	mtx_unlock(&lun->lun_lock);
5852 
5853 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5854 	return (retval);
5855 
5856 done:
5857 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5858 		free(ctsio->kern_data_ptr, M_CTL);
5859 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5860 	}
5861 	ctl_done((union ctl_io *)ctsio);
5862 	return (CTL_RETVAL_COMPLETE);
5863 }
5864 
5865 int
5866 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5867 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5868 {
5869 	struct ctl_lun *lun = CTL_LUN(ctsio);
5870 	uint8_t *current_cp;
5871 	int set_ua;
5872 	uint32_t initidx;
5873 
5874 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5875 	set_ua = 0;
5876 
5877 	current_cp = (page_index->page_data + (page_index->page_len *
5878 	    CTL_PAGE_CURRENT));
5879 
5880 	mtx_lock(&lun->lun_lock);
5881 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5882 		memcpy(current_cp, page_ptr, page_index->page_len);
5883 		set_ua = 1;
5884 	}
5885 	if (set_ua != 0)
5886 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5887 	mtx_unlock(&lun->lun_lock);
5888 	if (set_ua) {
5889 		ctl_isc_announce_mode(lun,
5890 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5891 		    page_index->page_code, page_index->subpage);
5892 	}
5893 	return (CTL_RETVAL_COMPLETE);
5894 }
5895 
5896 static void
5897 ctl_ie_timer(void *arg)
5898 {
5899 	struct ctl_lun *lun = arg;
5900 	uint64_t t;
5901 
5902 	if (lun->ie_asc == 0)
5903 		return;
5904 
5905 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5906 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5907 	else
5908 		lun->ie_reported = 0;
5909 
5910 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5911 		lun->ie_reportcnt++;
5912 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5913 		if (t == 0 || t == UINT32_MAX)
5914 			t = 3000;  /* 5 min */
5915 		callout_schedule(&lun->ie_callout, t * hz / 10);
5916 	}
5917 }
5918 
5919 int
5920 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5921 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5922 {
5923 	struct ctl_lun *lun = CTL_LUN(ctsio);
5924 	struct scsi_info_exceptions_page *pg;
5925 	uint64_t t;
5926 
5927 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5928 
5929 	pg = (struct scsi_info_exceptions_page *)page_ptr;
5930 	mtx_lock(&lun->lun_lock);
5931 	if (pg->info_flags & SIEP_FLAGS_TEST) {
5932 		lun->ie_asc = 0x5d;
5933 		lun->ie_ascq = 0xff;
5934 		if (pg->mrie == SIEP_MRIE_UA) {
5935 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5936 			lun->ie_reported = 1;
5937 		} else {
5938 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5939 			lun->ie_reported = -1;
5940 		}
5941 		lun->ie_reportcnt = 1;
5942 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5943 			lun->ie_reportcnt++;
5944 			t = scsi_4btoul(pg->interval_timer);
5945 			if (t == 0 || t == UINT32_MAX)
5946 				t = 3000;  /* 5 min */
5947 			callout_reset(&lun->ie_callout, t * hz / 10,
5948 			    ctl_ie_timer, lun);
5949 		}
5950 	} else {
5951 		lun->ie_asc = 0;
5952 		lun->ie_ascq = 0;
5953 		lun->ie_reported = 1;
5954 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5955 		lun->ie_reportcnt = UINT32_MAX;
5956 		callout_stop(&lun->ie_callout);
5957 	}
5958 	mtx_unlock(&lun->lun_lock);
5959 	return (CTL_RETVAL_COMPLETE);
5960 }
5961 
5962 static int
5963 ctl_do_mode_select(union ctl_io *io)
5964 {
5965 	struct ctl_lun *lun = CTL_LUN(io);
5966 	struct scsi_mode_page_header *page_header;
5967 	struct ctl_page_index *page_index;
5968 	struct ctl_scsiio *ctsio;
5969 	int page_len, page_len_offset, page_len_size;
5970 	union ctl_modepage_info *modepage_info;
5971 	uint16_t *len_left, *len_used;
5972 	int retval, i;
5973 
5974 	ctsio = &io->scsiio;
5975 	page_index = NULL;
5976 	page_len = 0;
5977 
5978 	modepage_info = (union ctl_modepage_info *)
5979 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5980 	len_left = &modepage_info->header.len_left;
5981 	len_used = &modepage_info->header.len_used;
5982 
5983 do_next_page:
5984 
5985 	page_header = (struct scsi_mode_page_header *)
5986 		(ctsio->kern_data_ptr + *len_used);
5987 
5988 	if (*len_left == 0) {
5989 		free(ctsio->kern_data_ptr, M_CTL);
5990 		ctl_set_success(ctsio);
5991 		ctl_done((union ctl_io *)ctsio);
5992 		return (CTL_RETVAL_COMPLETE);
5993 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5994 
5995 		free(ctsio->kern_data_ptr, M_CTL);
5996 		ctl_set_param_len_error(ctsio);
5997 		ctl_done((union ctl_io *)ctsio);
5998 		return (CTL_RETVAL_COMPLETE);
5999 
6000 	} else if ((page_header->page_code & SMPH_SPF)
6001 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6002 
6003 		free(ctsio->kern_data_ptr, M_CTL);
6004 		ctl_set_param_len_error(ctsio);
6005 		ctl_done((union ctl_io *)ctsio);
6006 		return (CTL_RETVAL_COMPLETE);
6007 	}
6008 
6009 
6010 	/*
6011 	 * XXX KDM should we do something with the block descriptor?
6012 	 */
6013 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6014 		page_index = &lun->mode_pages.index[i];
6015 		if (lun->be_lun->lun_type == T_DIRECT &&
6016 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6017 			continue;
6018 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6019 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6020 			continue;
6021 		if (lun->be_lun->lun_type == T_CDROM &&
6022 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6023 			continue;
6024 
6025 		if ((page_index->page_code & SMPH_PC_MASK) !=
6026 		    (page_header->page_code & SMPH_PC_MASK))
6027 			continue;
6028 
6029 		/*
6030 		 * If neither page has a subpage code, then we've got a
6031 		 * match.
6032 		 */
6033 		if (((page_index->page_code & SMPH_SPF) == 0)
6034 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6035 			page_len = page_header->page_length;
6036 			break;
6037 		}
6038 
6039 		/*
6040 		 * If both pages have subpages, then the subpage numbers
6041 		 * have to match.
6042 		 */
6043 		if ((page_index->page_code & SMPH_SPF)
6044 		  && (page_header->page_code & SMPH_SPF)) {
6045 			struct scsi_mode_page_header_sp *sph;
6046 
6047 			sph = (struct scsi_mode_page_header_sp *)page_header;
6048 			if (page_index->subpage == sph->subpage) {
6049 				page_len = scsi_2btoul(sph->page_length);
6050 				break;
6051 			}
6052 		}
6053 	}
6054 
6055 	/*
6056 	 * If we couldn't find the page, or if we don't have a mode select
6057 	 * handler for it, send back an error to the user.
6058 	 */
6059 	if ((i >= CTL_NUM_MODE_PAGES)
6060 	 || (page_index->select_handler == NULL)) {
6061 		ctl_set_invalid_field(ctsio,
6062 				      /*sks_valid*/ 1,
6063 				      /*command*/ 0,
6064 				      /*field*/ *len_used,
6065 				      /*bit_valid*/ 0,
6066 				      /*bit*/ 0);
6067 		free(ctsio->kern_data_ptr, M_CTL);
6068 		ctl_done((union ctl_io *)ctsio);
6069 		return (CTL_RETVAL_COMPLETE);
6070 	}
6071 
6072 	if (page_index->page_code & SMPH_SPF) {
6073 		page_len_offset = 2;
6074 		page_len_size = 2;
6075 	} else {
6076 		page_len_size = 1;
6077 		page_len_offset = 1;
6078 	}
6079 
6080 	/*
6081 	 * If the length the initiator gives us isn't the one we specify in
6082 	 * the mode page header, or if they didn't specify enough data in
6083 	 * the CDB to avoid truncating this page, kick out the request.
6084 	 */
6085 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6086 		ctl_set_invalid_field(ctsio,
6087 				      /*sks_valid*/ 1,
6088 				      /*command*/ 0,
6089 				      /*field*/ *len_used + page_len_offset,
6090 				      /*bit_valid*/ 0,
6091 				      /*bit*/ 0);
6092 		free(ctsio->kern_data_ptr, M_CTL);
6093 		ctl_done((union ctl_io *)ctsio);
6094 		return (CTL_RETVAL_COMPLETE);
6095 	}
6096 	if (*len_left < page_index->page_len) {
6097 		free(ctsio->kern_data_ptr, M_CTL);
6098 		ctl_set_param_len_error(ctsio);
6099 		ctl_done((union ctl_io *)ctsio);
6100 		return (CTL_RETVAL_COMPLETE);
6101 	}
6102 
6103 	/*
6104 	 * Run through the mode page, checking to make sure that the bits
6105 	 * the user changed are actually legal for him to change.
6106 	 */
6107 	for (i = 0; i < page_index->page_len; i++) {
6108 		uint8_t *user_byte, *change_mask, *current_byte;
6109 		int bad_bit;
6110 		int j;
6111 
6112 		user_byte = (uint8_t *)page_header + i;
6113 		change_mask = page_index->page_data +
6114 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6115 		current_byte = page_index->page_data +
6116 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6117 
6118 		/*
6119 		 * Check to see whether the user set any bits in this byte
6120 		 * that he is not allowed to set.
6121 		 */
6122 		if ((*user_byte & ~(*change_mask)) ==
6123 		    (*current_byte & ~(*change_mask)))
6124 			continue;
6125 
6126 		/*
6127 		 * Go through bit by bit to determine which one is illegal.
6128 		 */
6129 		bad_bit = 0;
6130 		for (j = 7; j >= 0; j--) {
6131 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6132 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6133 				bad_bit = i;
6134 				break;
6135 			}
6136 		}
6137 		ctl_set_invalid_field(ctsio,
6138 				      /*sks_valid*/ 1,
6139 				      /*command*/ 0,
6140 				      /*field*/ *len_used + i,
6141 				      /*bit_valid*/ 1,
6142 				      /*bit*/ bad_bit);
6143 		free(ctsio->kern_data_ptr, M_CTL);
6144 		ctl_done((union ctl_io *)ctsio);
6145 		return (CTL_RETVAL_COMPLETE);
6146 	}
6147 
6148 	/*
6149 	 * Decrement these before we call the page handler, since we may
6150 	 * end up getting called back one way or another before the handler
6151 	 * returns to this context.
6152 	 */
6153 	*len_left -= page_index->page_len;
6154 	*len_used += page_index->page_len;
6155 
6156 	retval = page_index->select_handler(ctsio, page_index,
6157 					    (uint8_t *)page_header);
6158 
6159 	/*
6160 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6161 	 * wait until this queued command completes to finish processing
6162 	 * the mode page.  If it returns anything other than
6163 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6164 	 * already set the sense information, freed the data pointer, and
6165 	 * completed the io for us.
6166 	 */
6167 	if (retval != CTL_RETVAL_COMPLETE)
6168 		goto bailout_no_done;
6169 
6170 	/*
6171 	 * If the initiator sent us more than one page, parse the next one.
6172 	 */
6173 	if (*len_left > 0)
6174 		goto do_next_page;
6175 
6176 	ctl_set_success(ctsio);
6177 	free(ctsio->kern_data_ptr, M_CTL);
6178 	ctl_done((union ctl_io *)ctsio);
6179 
6180 bailout_no_done:
6181 
6182 	return (CTL_RETVAL_COMPLETE);
6183 
6184 }
6185 
6186 int
6187 ctl_mode_select(struct ctl_scsiio *ctsio)
6188 {
6189 	struct ctl_lun *lun = CTL_LUN(ctsio);
6190 	union ctl_modepage_info *modepage_info;
6191 	int bd_len, i, header_size, param_len, pf, rtd, sp;
6192 	uint32_t initidx;
6193 
6194 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6195 	switch (ctsio->cdb[0]) {
6196 	case MODE_SELECT_6: {
6197 		struct scsi_mode_select_6 *cdb;
6198 
6199 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6200 
6201 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6202 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6203 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6204 		param_len = cdb->length;
6205 		header_size = sizeof(struct scsi_mode_header_6);
6206 		break;
6207 	}
6208 	case MODE_SELECT_10: {
6209 		struct scsi_mode_select_10 *cdb;
6210 
6211 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6212 
6213 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6214 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6215 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6216 		param_len = scsi_2btoul(cdb->length);
6217 		header_size = sizeof(struct scsi_mode_header_10);
6218 		break;
6219 	}
6220 	default:
6221 		ctl_set_invalid_opcode(ctsio);
6222 		ctl_done((union ctl_io *)ctsio);
6223 		return (CTL_RETVAL_COMPLETE);
6224 	}
6225 
6226 	if (rtd) {
6227 		if (param_len != 0) {
6228 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6229 			    /*command*/ 1, /*field*/ 0,
6230 			    /*bit_valid*/ 0, /*bit*/ 0);
6231 			ctl_done((union ctl_io *)ctsio);
6232 			return (CTL_RETVAL_COMPLETE);
6233 		}
6234 
6235 		/* Revert to defaults. */
6236 		ctl_init_page_index(lun);
6237 		mtx_lock(&lun->lun_lock);
6238 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6239 		mtx_unlock(&lun->lun_lock);
6240 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6241 			ctl_isc_announce_mode(lun, -1,
6242 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6243 			    lun->mode_pages.index[i].subpage);
6244 		}
6245 		ctl_set_success(ctsio);
6246 		ctl_done((union ctl_io *)ctsio);
6247 		return (CTL_RETVAL_COMPLETE);
6248 	}
6249 
6250 	/*
6251 	 * From SPC-3:
6252 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6253 	 * shall be empty. This condition shall not be considered as an error."
6254 	 */
6255 	if (param_len == 0) {
6256 		ctl_set_success(ctsio);
6257 		ctl_done((union ctl_io *)ctsio);
6258 		return (CTL_RETVAL_COMPLETE);
6259 	}
6260 
6261 	/*
6262 	 * Since we'll hit this the first time through, prior to
6263 	 * allocation, we don't need to free a data buffer here.
6264 	 */
6265 	if (param_len < header_size) {
6266 		ctl_set_param_len_error(ctsio);
6267 		ctl_done((union ctl_io *)ctsio);
6268 		return (CTL_RETVAL_COMPLETE);
6269 	}
6270 
6271 	/*
6272 	 * Allocate the data buffer and grab the user's data.  In theory,
6273 	 * we shouldn't have to sanity check the parameter list length here
6274 	 * because the maximum size is 64K.  We should be able to malloc
6275 	 * that much without too many problems.
6276 	 */
6277 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6278 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6279 		ctsio->kern_data_len = param_len;
6280 		ctsio->kern_total_len = param_len;
6281 		ctsio->kern_data_resid = 0;
6282 		ctsio->kern_rel_offset = 0;
6283 		ctsio->kern_sg_entries = 0;
6284 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6285 		ctsio->be_move_done = ctl_config_move_done;
6286 		ctl_datamove((union ctl_io *)ctsio);
6287 
6288 		return (CTL_RETVAL_COMPLETE);
6289 	}
6290 
6291 	switch (ctsio->cdb[0]) {
6292 	case MODE_SELECT_6: {
6293 		struct scsi_mode_header_6 *mh6;
6294 
6295 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6296 		bd_len = mh6->blk_desc_len;
6297 		break;
6298 	}
6299 	case MODE_SELECT_10: {
6300 		struct scsi_mode_header_10 *mh10;
6301 
6302 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6303 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6304 		break;
6305 	}
6306 	default:
6307 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6308 	}
6309 
6310 	if (param_len < (header_size + bd_len)) {
6311 		free(ctsio->kern_data_ptr, M_CTL);
6312 		ctl_set_param_len_error(ctsio);
6313 		ctl_done((union ctl_io *)ctsio);
6314 		return (CTL_RETVAL_COMPLETE);
6315 	}
6316 
6317 	/*
6318 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6319 	 * ctl_config_write_done(), it'll get passed back to
6320 	 * ctl_do_mode_select() for further processing, or completion if
6321 	 * we're all done.
6322 	 */
6323 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6324 	ctsio->io_cont = ctl_do_mode_select;
6325 
6326 	modepage_info = (union ctl_modepage_info *)
6327 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6328 	memset(modepage_info, 0, sizeof(*modepage_info));
6329 	modepage_info->header.len_left = param_len - header_size - bd_len;
6330 	modepage_info->header.len_used = header_size + bd_len;
6331 
6332 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6333 }
6334 
6335 int
6336 ctl_mode_sense(struct ctl_scsiio *ctsio)
6337 {
6338 	struct ctl_lun *lun = CTL_LUN(ctsio);
6339 	int pc, page_code, dbd, llba, subpage;
6340 	int alloc_len, page_len, header_len, total_len;
6341 	struct scsi_mode_block_descr *block_desc;
6342 	struct ctl_page_index *page_index;
6343 
6344 	dbd = 0;
6345 	llba = 0;
6346 	block_desc = NULL;
6347 
6348 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6349 
6350 	switch (ctsio->cdb[0]) {
6351 	case MODE_SENSE_6: {
6352 		struct scsi_mode_sense_6 *cdb;
6353 
6354 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6355 
6356 		header_len = sizeof(struct scsi_mode_hdr_6);
6357 		if (cdb->byte2 & SMS_DBD)
6358 			dbd = 1;
6359 		else
6360 			header_len += sizeof(struct scsi_mode_block_descr);
6361 
6362 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6363 		page_code = cdb->page & SMS_PAGE_CODE;
6364 		subpage = cdb->subpage;
6365 		alloc_len = cdb->length;
6366 		break;
6367 	}
6368 	case MODE_SENSE_10: {
6369 		struct scsi_mode_sense_10 *cdb;
6370 
6371 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6372 
6373 		header_len = sizeof(struct scsi_mode_hdr_10);
6374 
6375 		if (cdb->byte2 & SMS_DBD)
6376 			dbd = 1;
6377 		else
6378 			header_len += sizeof(struct scsi_mode_block_descr);
6379 		if (cdb->byte2 & SMS10_LLBAA)
6380 			llba = 1;
6381 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6382 		page_code = cdb->page & SMS_PAGE_CODE;
6383 		subpage = cdb->subpage;
6384 		alloc_len = scsi_2btoul(cdb->length);
6385 		break;
6386 	}
6387 	default:
6388 		ctl_set_invalid_opcode(ctsio);
6389 		ctl_done((union ctl_io *)ctsio);
6390 		return (CTL_RETVAL_COMPLETE);
6391 		break; /* NOTREACHED */
6392 	}
6393 
6394 	/*
6395 	 * We have to make a first pass through to calculate the size of
6396 	 * the pages that match the user's query.  Then we allocate enough
6397 	 * memory to hold it, and actually copy the data into the buffer.
6398 	 */
6399 	switch (page_code) {
6400 	case SMS_ALL_PAGES_PAGE: {
6401 		u_int i;
6402 
6403 		page_len = 0;
6404 
6405 		/*
6406 		 * At the moment, values other than 0 and 0xff here are
6407 		 * reserved according to SPC-3.
6408 		 */
6409 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6410 		 && (subpage != SMS_SUBPAGE_ALL)) {
6411 			ctl_set_invalid_field(ctsio,
6412 					      /*sks_valid*/ 1,
6413 					      /*command*/ 1,
6414 					      /*field*/ 3,
6415 					      /*bit_valid*/ 0,
6416 					      /*bit*/ 0);
6417 			ctl_done((union ctl_io *)ctsio);
6418 			return (CTL_RETVAL_COMPLETE);
6419 		}
6420 
6421 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6422 			page_index = &lun->mode_pages.index[i];
6423 
6424 			/* Make sure the page is supported for this dev type */
6425 			if (lun->be_lun->lun_type == T_DIRECT &&
6426 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6427 				continue;
6428 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6429 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6430 				continue;
6431 			if (lun->be_lun->lun_type == T_CDROM &&
6432 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6433 				continue;
6434 
6435 			/*
6436 			 * We don't use this subpage if the user didn't
6437 			 * request all subpages.
6438 			 */
6439 			if ((page_index->subpage != 0)
6440 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6441 				continue;
6442 
6443 #if 0
6444 			printf("found page %#x len %d\n",
6445 			       page_index->page_code & SMPH_PC_MASK,
6446 			       page_index->page_len);
6447 #endif
6448 			page_len += page_index->page_len;
6449 		}
6450 		break;
6451 	}
6452 	default: {
6453 		u_int i;
6454 
6455 		page_len = 0;
6456 
6457 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6458 			page_index = &lun->mode_pages.index[i];
6459 
6460 			/* Make sure the page is supported for this dev type */
6461 			if (lun->be_lun->lun_type == T_DIRECT &&
6462 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6463 				continue;
6464 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6465 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6466 				continue;
6467 			if (lun->be_lun->lun_type == T_CDROM &&
6468 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6469 				continue;
6470 
6471 			/* Look for the right page code */
6472 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6473 				continue;
6474 
6475 			/* Look for the right subpage or the subpage wildcard*/
6476 			if ((page_index->subpage != subpage)
6477 			 && (subpage != SMS_SUBPAGE_ALL))
6478 				continue;
6479 
6480 #if 0
6481 			printf("found page %#x len %d\n",
6482 			       page_index->page_code & SMPH_PC_MASK,
6483 			       page_index->page_len);
6484 #endif
6485 
6486 			page_len += page_index->page_len;
6487 		}
6488 
6489 		if (page_len == 0) {
6490 			ctl_set_invalid_field(ctsio,
6491 					      /*sks_valid*/ 1,
6492 					      /*command*/ 1,
6493 					      /*field*/ 2,
6494 					      /*bit_valid*/ 1,
6495 					      /*bit*/ 5);
6496 			ctl_done((union ctl_io *)ctsio);
6497 			return (CTL_RETVAL_COMPLETE);
6498 		}
6499 		break;
6500 	}
6501 	}
6502 
6503 	total_len = header_len + page_len;
6504 #if 0
6505 	printf("header_len = %d, page_len = %d, total_len = %d\n",
6506 	       header_len, page_len, total_len);
6507 #endif
6508 
6509 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6510 	ctsio->kern_sg_entries = 0;
6511 	ctsio->kern_data_resid = 0;
6512 	ctsio->kern_rel_offset = 0;
6513 	if (total_len < alloc_len) {
6514 		ctsio->residual = alloc_len - total_len;
6515 		ctsio->kern_data_len = total_len;
6516 		ctsio->kern_total_len = total_len;
6517 	} else {
6518 		ctsio->residual = 0;
6519 		ctsio->kern_data_len = alloc_len;
6520 		ctsio->kern_total_len = alloc_len;
6521 	}
6522 
6523 	switch (ctsio->cdb[0]) {
6524 	case MODE_SENSE_6: {
6525 		struct scsi_mode_hdr_6 *header;
6526 
6527 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6528 
6529 		header->datalen = MIN(total_len - 1, 254);
6530 		if (lun->be_lun->lun_type == T_DIRECT) {
6531 			header->dev_specific = 0x10; /* DPOFUA */
6532 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6533 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6534 				header->dev_specific |= 0x80; /* WP */
6535 		}
6536 		if (dbd)
6537 			header->block_descr_len = 0;
6538 		else
6539 			header->block_descr_len =
6540 				sizeof(struct scsi_mode_block_descr);
6541 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6542 		break;
6543 	}
6544 	case MODE_SENSE_10: {
6545 		struct scsi_mode_hdr_10 *header;
6546 		int datalen;
6547 
6548 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6549 
6550 		datalen = MIN(total_len - 2, 65533);
6551 		scsi_ulto2b(datalen, header->datalen);
6552 		if (lun->be_lun->lun_type == T_DIRECT) {
6553 			header->dev_specific = 0x10; /* DPOFUA */
6554 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6555 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6556 				header->dev_specific |= 0x80; /* WP */
6557 		}
6558 		if (dbd)
6559 			scsi_ulto2b(0, header->block_descr_len);
6560 		else
6561 			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6562 				    header->block_descr_len);
6563 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6564 		break;
6565 	}
6566 	default:
6567 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6568 	}
6569 
6570 	/*
6571 	 * If we've got a disk, use its blocksize in the block
6572 	 * descriptor.  Otherwise, just set it to 0.
6573 	 */
6574 	if (dbd == 0) {
6575 		if (lun->be_lun->lun_type == T_DIRECT)
6576 			scsi_ulto3b(lun->be_lun->blocksize,
6577 				    block_desc->block_len);
6578 		else
6579 			scsi_ulto3b(0, block_desc->block_len);
6580 	}
6581 
6582 	switch (page_code) {
6583 	case SMS_ALL_PAGES_PAGE: {
6584 		int i, data_used;
6585 
6586 		data_used = header_len;
6587 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6588 			struct ctl_page_index *page_index;
6589 
6590 			page_index = &lun->mode_pages.index[i];
6591 			if (lun->be_lun->lun_type == T_DIRECT &&
6592 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6593 				continue;
6594 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6595 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6596 				continue;
6597 			if (lun->be_lun->lun_type == T_CDROM &&
6598 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6599 				continue;
6600 
6601 			/*
6602 			 * We don't use this subpage if the user didn't
6603 			 * request all subpages.  We already checked (above)
6604 			 * to make sure the user only specified a subpage
6605 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6606 			 */
6607 			if ((page_index->subpage != 0)
6608 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6609 				continue;
6610 
6611 			/*
6612 			 * Call the handler, if it exists, to update the
6613 			 * page to the latest values.
6614 			 */
6615 			if (page_index->sense_handler != NULL)
6616 				page_index->sense_handler(ctsio, page_index,pc);
6617 
6618 			memcpy(ctsio->kern_data_ptr + data_used,
6619 			       page_index->page_data +
6620 			       (page_index->page_len * pc),
6621 			       page_index->page_len);
6622 			data_used += page_index->page_len;
6623 		}
6624 		break;
6625 	}
6626 	default: {
6627 		int i, data_used;
6628 
6629 		data_used = header_len;
6630 
6631 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6632 			struct ctl_page_index *page_index;
6633 
6634 			page_index = &lun->mode_pages.index[i];
6635 
6636 			/* Look for the right page code */
6637 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6638 				continue;
6639 
6640 			/* Look for the right subpage or the subpage wildcard*/
6641 			if ((page_index->subpage != subpage)
6642 			 && (subpage != SMS_SUBPAGE_ALL))
6643 				continue;
6644 
6645 			/* Make sure the page is supported for this dev type */
6646 			if (lun->be_lun->lun_type == T_DIRECT &&
6647 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6648 				continue;
6649 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6650 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6651 				continue;
6652 			if (lun->be_lun->lun_type == T_CDROM &&
6653 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6654 				continue;
6655 
6656 			/*
6657 			 * Call the handler, if it exists, to update the
6658 			 * page to the latest values.
6659 			 */
6660 			if (page_index->sense_handler != NULL)
6661 				page_index->sense_handler(ctsio, page_index,pc);
6662 
6663 			memcpy(ctsio->kern_data_ptr + data_used,
6664 			       page_index->page_data +
6665 			       (page_index->page_len * pc),
6666 			       page_index->page_len);
6667 			data_used += page_index->page_len;
6668 		}
6669 		break;
6670 	}
6671 	}
6672 
6673 	ctl_set_success(ctsio);
6674 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6675 	ctsio->be_move_done = ctl_config_move_done;
6676 	ctl_datamove((union ctl_io *)ctsio);
6677 	return (CTL_RETVAL_COMPLETE);
6678 }
6679 
6680 int
6681 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6682 			       struct ctl_page_index *page_index,
6683 			       int pc)
6684 {
6685 	struct ctl_lun *lun = CTL_LUN(ctsio);
6686 	struct scsi_log_param_header *phdr;
6687 	uint8_t *data;
6688 	uint64_t val;
6689 
6690 	data = page_index->page_data;
6691 
6692 	if (lun->backend->lun_attr != NULL &&
6693 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6694 	     != UINT64_MAX) {
6695 		phdr = (struct scsi_log_param_header *)data;
6696 		scsi_ulto2b(0x0001, phdr->param_code);
6697 		phdr->param_control = SLP_LBIN | SLP_LP;
6698 		phdr->param_len = 8;
6699 		data = (uint8_t *)(phdr + 1);
6700 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6701 		data[4] = 0x02; /* per-pool */
6702 		data += phdr->param_len;
6703 	}
6704 
6705 	if (lun->backend->lun_attr != NULL &&
6706 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6707 	     != UINT64_MAX) {
6708 		phdr = (struct scsi_log_param_header *)data;
6709 		scsi_ulto2b(0x0002, phdr->param_code);
6710 		phdr->param_control = SLP_LBIN | SLP_LP;
6711 		phdr->param_len = 8;
6712 		data = (uint8_t *)(phdr + 1);
6713 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6714 		data[4] = 0x01; /* per-LUN */
6715 		data += phdr->param_len;
6716 	}
6717 
6718 	if (lun->backend->lun_attr != NULL &&
6719 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6720 	     != UINT64_MAX) {
6721 		phdr = (struct scsi_log_param_header *)data;
6722 		scsi_ulto2b(0x00f1, phdr->param_code);
6723 		phdr->param_control = SLP_LBIN | SLP_LP;
6724 		phdr->param_len = 8;
6725 		data = (uint8_t *)(phdr + 1);
6726 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6727 		data[4] = 0x02; /* per-pool */
6728 		data += phdr->param_len;
6729 	}
6730 
6731 	if (lun->backend->lun_attr != NULL &&
6732 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6733 	     != UINT64_MAX) {
6734 		phdr = (struct scsi_log_param_header *)data;
6735 		scsi_ulto2b(0x00f2, phdr->param_code);
6736 		phdr->param_control = SLP_LBIN | SLP_LP;
6737 		phdr->param_len = 8;
6738 		data = (uint8_t *)(phdr + 1);
6739 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6740 		data[4] = 0x02; /* per-pool */
6741 		data += phdr->param_len;
6742 	}
6743 
6744 	page_index->page_len = data - page_index->page_data;
6745 	return (0);
6746 }
6747 
6748 int
6749 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6750 			       struct ctl_page_index *page_index,
6751 			       int pc)
6752 {
6753 	struct ctl_lun *lun = CTL_LUN(ctsio);
6754 	struct stat_page *data;
6755 	struct bintime *t;
6756 
6757 	data = (struct stat_page *)page_index->page_data;
6758 
6759 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6760 	data->sap.hdr.param_control = SLP_LBIN;
6761 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6762 	    sizeof(struct scsi_log_param_header);
6763 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6764 	    data->sap.read_num);
6765 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6766 	    data->sap.write_num);
6767 	if (lun->be_lun->blocksize > 0) {
6768 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6769 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6770 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6771 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6772 	}
6773 	t = &lun->stats.time[CTL_STATS_READ];
6774 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6775 	    data->sap.read_int);
6776 	t = &lun->stats.time[CTL_STATS_WRITE];
6777 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6778 	    data->sap.write_int);
6779 	scsi_u64to8b(0, data->sap.weighted_num);
6780 	scsi_u64to8b(0, data->sap.weighted_int);
6781 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6782 	data->it.hdr.param_control = SLP_LBIN;
6783 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6784 	    sizeof(struct scsi_log_param_header);
6785 #ifdef CTL_TIME_IO
6786 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6787 #endif
6788 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6789 	data->it.hdr.param_control = SLP_LBIN;
6790 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6791 	    sizeof(struct scsi_log_param_header);
6792 	scsi_ulto4b(3, data->ti.exponent);
6793 	scsi_ulto4b(1, data->ti.integer);
6794 	return (0);
6795 }
6796 
6797 int
6798 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6799 			       struct ctl_page_index *page_index,
6800 			       int pc)
6801 {
6802 	struct ctl_lun *lun = CTL_LUN(ctsio);
6803 	struct scsi_log_informational_exceptions *data;
6804 
6805 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6806 
6807 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6808 	data->hdr.param_control = SLP_LBIN;
6809 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6810 	    sizeof(struct scsi_log_param_header);
6811 	data->ie_asc = lun->ie_asc;
6812 	data->ie_ascq = lun->ie_ascq;
6813 	data->temperature = 0xff;
6814 	return (0);
6815 }
6816 
6817 int
6818 ctl_log_sense(struct ctl_scsiio *ctsio)
6819 {
6820 	struct ctl_lun *lun = CTL_LUN(ctsio);
6821 	int i, pc, page_code, subpage;
6822 	int alloc_len, total_len;
6823 	struct ctl_page_index *page_index;
6824 	struct scsi_log_sense *cdb;
6825 	struct scsi_log_header *header;
6826 
6827 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6828 
6829 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6830 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6831 	page_code = cdb->page & SLS_PAGE_CODE;
6832 	subpage = cdb->subpage;
6833 	alloc_len = scsi_2btoul(cdb->length);
6834 
6835 	page_index = NULL;
6836 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6837 		page_index = &lun->log_pages.index[i];
6838 
6839 		/* Look for the right page code */
6840 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6841 			continue;
6842 
6843 		/* Look for the right subpage or the subpage wildcard*/
6844 		if (page_index->subpage != subpage)
6845 			continue;
6846 
6847 		break;
6848 	}
6849 	if (i >= CTL_NUM_LOG_PAGES) {
6850 		ctl_set_invalid_field(ctsio,
6851 				      /*sks_valid*/ 1,
6852 				      /*command*/ 1,
6853 				      /*field*/ 2,
6854 				      /*bit_valid*/ 0,
6855 				      /*bit*/ 0);
6856 		ctl_done((union ctl_io *)ctsio);
6857 		return (CTL_RETVAL_COMPLETE);
6858 	}
6859 
6860 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6861 
6862 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6863 	ctsio->kern_sg_entries = 0;
6864 	ctsio->kern_data_resid = 0;
6865 	ctsio->kern_rel_offset = 0;
6866 	if (total_len < alloc_len) {
6867 		ctsio->residual = alloc_len - total_len;
6868 		ctsio->kern_data_len = total_len;
6869 		ctsio->kern_total_len = total_len;
6870 	} else {
6871 		ctsio->residual = 0;
6872 		ctsio->kern_data_len = alloc_len;
6873 		ctsio->kern_total_len = alloc_len;
6874 	}
6875 
6876 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6877 	header->page = page_index->page_code;
6878 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6879 		header->page |= SL_DS;
6880 	if (page_index->subpage) {
6881 		header->page |= SL_SPF;
6882 		header->subpage = page_index->subpage;
6883 	}
6884 	scsi_ulto2b(page_index->page_len, header->datalen);
6885 
6886 	/*
6887 	 * Call the handler, if it exists, to update the
6888 	 * page to the latest values.
6889 	 */
6890 	if (page_index->sense_handler != NULL)
6891 		page_index->sense_handler(ctsio, page_index, pc);
6892 
6893 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6894 
6895 	ctl_set_success(ctsio);
6896 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6897 	ctsio->be_move_done = ctl_config_move_done;
6898 	ctl_datamove((union ctl_io *)ctsio);
6899 	return (CTL_RETVAL_COMPLETE);
6900 }
6901 
6902 int
6903 ctl_read_capacity(struct ctl_scsiio *ctsio)
6904 {
6905 	struct ctl_lun *lun = CTL_LUN(ctsio);
6906 	struct scsi_read_capacity *cdb;
6907 	struct scsi_read_capacity_data *data;
6908 	uint32_t lba;
6909 
6910 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6911 
6912 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6913 
6914 	lba = scsi_4btoul(cdb->addr);
6915 	if (((cdb->pmi & SRC_PMI) == 0)
6916 	 && (lba != 0)) {
6917 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6918 				      /*sks_valid*/ 1,
6919 				      /*command*/ 1,
6920 				      /*field*/ 2,
6921 				      /*bit_valid*/ 0,
6922 				      /*bit*/ 0);
6923 		ctl_done((union ctl_io *)ctsio);
6924 		return (CTL_RETVAL_COMPLETE);
6925 	}
6926 
6927 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6928 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6929 	ctsio->residual = 0;
6930 	ctsio->kern_data_len = sizeof(*data);
6931 	ctsio->kern_total_len = sizeof(*data);
6932 	ctsio->kern_data_resid = 0;
6933 	ctsio->kern_rel_offset = 0;
6934 	ctsio->kern_sg_entries = 0;
6935 
6936 	/*
6937 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6938 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6939 	 * serivce action set.
6940 	 */
6941 	if (lun->be_lun->maxlba > 0xfffffffe)
6942 		scsi_ulto4b(0xffffffff, data->addr);
6943 	else
6944 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6945 
6946 	/*
6947 	 * XXX KDM this may not be 512 bytes...
6948 	 */
6949 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6950 
6951 	ctl_set_success(ctsio);
6952 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6953 	ctsio->be_move_done = ctl_config_move_done;
6954 	ctl_datamove((union ctl_io *)ctsio);
6955 	return (CTL_RETVAL_COMPLETE);
6956 }
6957 
6958 int
6959 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6960 {
6961 	struct ctl_lun *lun = CTL_LUN(ctsio);
6962 	struct scsi_read_capacity_16 *cdb;
6963 	struct scsi_read_capacity_data_long *data;
6964 	uint64_t lba;
6965 	uint32_t alloc_len;
6966 
6967 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6968 
6969 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6970 
6971 	alloc_len = scsi_4btoul(cdb->alloc_len);
6972 	lba = scsi_8btou64(cdb->addr);
6973 
6974 	if ((cdb->reladr & SRC16_PMI)
6975 	 && (lba != 0)) {
6976 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6977 				      /*sks_valid*/ 1,
6978 				      /*command*/ 1,
6979 				      /*field*/ 2,
6980 				      /*bit_valid*/ 0,
6981 				      /*bit*/ 0);
6982 		ctl_done((union ctl_io *)ctsio);
6983 		return (CTL_RETVAL_COMPLETE);
6984 	}
6985 
6986 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6987 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6988 
6989 	if (sizeof(*data) < alloc_len) {
6990 		ctsio->residual = alloc_len - sizeof(*data);
6991 		ctsio->kern_data_len = sizeof(*data);
6992 		ctsio->kern_total_len = sizeof(*data);
6993 	} else {
6994 		ctsio->residual = 0;
6995 		ctsio->kern_data_len = alloc_len;
6996 		ctsio->kern_total_len = alloc_len;
6997 	}
6998 	ctsio->kern_data_resid = 0;
6999 	ctsio->kern_rel_offset = 0;
7000 	ctsio->kern_sg_entries = 0;
7001 
7002 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7003 	/* XXX KDM this may not be 512 bytes... */
7004 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7005 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7006 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7007 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7008 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7009 
7010 	ctl_set_success(ctsio);
7011 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7012 	ctsio->be_move_done = ctl_config_move_done;
7013 	ctl_datamove((union ctl_io *)ctsio);
7014 	return (CTL_RETVAL_COMPLETE);
7015 }
7016 
7017 int
7018 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7019 {
7020 	struct ctl_lun *lun = CTL_LUN(ctsio);
7021 	struct scsi_get_lba_status *cdb;
7022 	struct scsi_get_lba_status_data *data;
7023 	struct ctl_lba_len_flags *lbalen;
7024 	uint64_t lba;
7025 	uint32_t alloc_len, total_len;
7026 	int retval;
7027 
7028 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7029 
7030 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7031 	lba = scsi_8btou64(cdb->addr);
7032 	alloc_len = scsi_4btoul(cdb->alloc_len);
7033 
7034 	if (lba > lun->be_lun->maxlba) {
7035 		ctl_set_lba_out_of_range(ctsio, lba);
7036 		ctl_done((union ctl_io *)ctsio);
7037 		return (CTL_RETVAL_COMPLETE);
7038 	}
7039 
7040 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7041 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7042 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7043 
7044 	if (total_len < alloc_len) {
7045 		ctsio->residual = alloc_len - total_len;
7046 		ctsio->kern_data_len = total_len;
7047 		ctsio->kern_total_len = total_len;
7048 	} else {
7049 		ctsio->residual = 0;
7050 		ctsio->kern_data_len = alloc_len;
7051 		ctsio->kern_total_len = alloc_len;
7052 	}
7053 	ctsio->kern_data_resid = 0;
7054 	ctsio->kern_rel_offset = 0;
7055 	ctsio->kern_sg_entries = 0;
7056 
7057 	/* Fill dummy data in case backend can't tell anything. */
7058 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7059 	scsi_u64to8b(lba, data->descr[0].addr);
7060 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7061 	    data->descr[0].length);
7062 	data->descr[0].status = 0; /* Mapped or unknown. */
7063 
7064 	ctl_set_success(ctsio);
7065 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7066 	ctsio->be_move_done = ctl_config_move_done;
7067 
7068 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7069 	lbalen->lba = lba;
7070 	lbalen->len = total_len;
7071 	lbalen->flags = 0;
7072 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7073 	return (CTL_RETVAL_COMPLETE);
7074 }
7075 
7076 int
7077 ctl_read_defect(struct ctl_scsiio *ctsio)
7078 {
7079 	struct scsi_read_defect_data_10 *ccb10;
7080 	struct scsi_read_defect_data_12 *ccb12;
7081 	struct scsi_read_defect_data_hdr_10 *data10;
7082 	struct scsi_read_defect_data_hdr_12 *data12;
7083 	uint32_t alloc_len, data_len;
7084 	uint8_t format;
7085 
7086 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7087 
7088 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7089 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7090 		format = ccb10->format;
7091 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7092 		data_len = sizeof(*data10);
7093 	} else {
7094 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7095 		format = ccb12->format;
7096 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7097 		data_len = sizeof(*data12);
7098 	}
7099 	if (alloc_len == 0) {
7100 		ctl_set_success(ctsio);
7101 		ctl_done((union ctl_io *)ctsio);
7102 		return (CTL_RETVAL_COMPLETE);
7103 	}
7104 
7105 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7106 	if (data_len < alloc_len) {
7107 		ctsio->residual = alloc_len - data_len;
7108 		ctsio->kern_data_len = data_len;
7109 		ctsio->kern_total_len = data_len;
7110 	} else {
7111 		ctsio->residual = 0;
7112 		ctsio->kern_data_len = alloc_len;
7113 		ctsio->kern_total_len = alloc_len;
7114 	}
7115 	ctsio->kern_data_resid = 0;
7116 	ctsio->kern_rel_offset = 0;
7117 	ctsio->kern_sg_entries = 0;
7118 
7119 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7120 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7121 		    ctsio->kern_data_ptr;
7122 		data10->format = format;
7123 		scsi_ulto2b(0, data10->length);
7124 	} else {
7125 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7126 		    ctsio->kern_data_ptr;
7127 		data12->format = format;
7128 		scsi_ulto2b(0, data12->generation);
7129 		scsi_ulto4b(0, data12->length);
7130 	}
7131 
7132 	ctl_set_success(ctsio);
7133 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7134 	ctsio->be_move_done = ctl_config_move_done;
7135 	ctl_datamove((union ctl_io *)ctsio);
7136 	return (CTL_RETVAL_COMPLETE);
7137 }
7138 
7139 int
7140 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7141 {
7142 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7143 	struct ctl_lun *lun = CTL_LUN(ctsio);
7144 	struct scsi_maintenance_in *cdb;
7145 	int retval;
7146 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7147 	int num_ha_groups, num_target_ports, shared_group;
7148 	struct ctl_port *port;
7149 	struct scsi_target_group_data *rtg_ptr;
7150 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7151 	struct scsi_target_port_group_descriptor *tpg_desc;
7152 
7153 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7154 
7155 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7156 	retval = CTL_RETVAL_COMPLETE;
7157 
7158 	switch (cdb->byte2 & STG_PDF_MASK) {
7159 	case STG_PDF_LENGTH:
7160 		ext = 0;
7161 		break;
7162 	case STG_PDF_EXTENDED:
7163 		ext = 1;
7164 		break;
7165 	default:
7166 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7167 				      /*sks_valid*/ 1,
7168 				      /*command*/ 1,
7169 				      /*field*/ 2,
7170 				      /*bit_valid*/ 1,
7171 				      /*bit*/ 5);
7172 		ctl_done((union ctl_io *)ctsio);
7173 		return(retval);
7174 	}
7175 
7176 	num_target_ports = 0;
7177 	shared_group = (softc->is_single != 0);
7178 	mtx_lock(&softc->ctl_lock);
7179 	STAILQ_FOREACH(port, &softc->port_list, links) {
7180 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7181 			continue;
7182 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7183 			continue;
7184 		num_target_ports++;
7185 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7186 			shared_group = 1;
7187 	}
7188 	mtx_unlock(&softc->ctl_lock);
7189 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7190 
7191 	if (ext)
7192 		total_len = sizeof(struct scsi_target_group_data_extended);
7193 	else
7194 		total_len = sizeof(struct scsi_target_group_data);
7195 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7196 		(shared_group + num_ha_groups) +
7197 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7198 
7199 	alloc_len = scsi_4btoul(cdb->length);
7200 
7201 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7202 
7203 	ctsio->kern_sg_entries = 0;
7204 
7205 	if (total_len < alloc_len) {
7206 		ctsio->residual = alloc_len - total_len;
7207 		ctsio->kern_data_len = total_len;
7208 		ctsio->kern_total_len = total_len;
7209 	} else {
7210 		ctsio->residual = 0;
7211 		ctsio->kern_data_len = alloc_len;
7212 		ctsio->kern_total_len = alloc_len;
7213 	}
7214 	ctsio->kern_data_resid = 0;
7215 	ctsio->kern_rel_offset = 0;
7216 
7217 	if (ext) {
7218 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7219 		    ctsio->kern_data_ptr;
7220 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7221 		rtg_ext_ptr->format_type = 0x10;
7222 		rtg_ext_ptr->implicit_transition_time = 0;
7223 		tpg_desc = &rtg_ext_ptr->groups[0];
7224 	} else {
7225 		rtg_ptr = (struct scsi_target_group_data *)
7226 		    ctsio->kern_data_ptr;
7227 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7228 		tpg_desc = &rtg_ptr->groups[0];
7229 	}
7230 
7231 	mtx_lock(&softc->ctl_lock);
7232 	pg = softc->port_min / softc->port_cnt;
7233 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7234 		/* Some shelf is known to be primary. */
7235 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7236 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7237 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7238 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7239 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7240 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7241 		else
7242 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7243 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7244 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7245 		} else {
7246 			ts = os;
7247 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7248 		}
7249 	} else {
7250 		/* No known primary shelf. */
7251 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7252 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7253 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7254 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7255 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7256 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7257 		} else {
7258 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7259 		}
7260 	}
7261 	if (shared_group) {
7262 		tpg_desc->pref_state = ts;
7263 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7264 		    TPG_U_SUP | TPG_T_SUP;
7265 		scsi_ulto2b(1, tpg_desc->target_port_group);
7266 		tpg_desc->status = TPG_IMPLICIT;
7267 		pc = 0;
7268 		STAILQ_FOREACH(port, &softc->port_list, links) {
7269 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7270 				continue;
7271 			if (!softc->is_single &&
7272 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7273 				continue;
7274 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7275 				continue;
7276 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7277 			    relative_target_port_identifier);
7278 			pc++;
7279 		}
7280 		tpg_desc->target_port_count = pc;
7281 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7282 		    &tpg_desc->descriptors[pc];
7283 	}
7284 	for (g = 0; g < num_ha_groups; g++) {
7285 		tpg_desc->pref_state = (g == pg) ? ts : os;
7286 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7287 		    TPG_U_SUP | TPG_T_SUP;
7288 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7289 		tpg_desc->status = TPG_IMPLICIT;
7290 		pc = 0;
7291 		STAILQ_FOREACH(port, &softc->port_list, links) {
7292 			if (port->targ_port < g * softc->port_cnt ||
7293 			    port->targ_port >= (g + 1) * softc->port_cnt)
7294 				continue;
7295 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7296 				continue;
7297 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7298 				continue;
7299 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7300 				continue;
7301 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7302 			    relative_target_port_identifier);
7303 			pc++;
7304 		}
7305 		tpg_desc->target_port_count = pc;
7306 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7307 		    &tpg_desc->descriptors[pc];
7308 	}
7309 	mtx_unlock(&softc->ctl_lock);
7310 
7311 	ctl_set_success(ctsio);
7312 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7313 	ctsio->be_move_done = ctl_config_move_done;
7314 	ctl_datamove((union ctl_io *)ctsio);
7315 	return(retval);
7316 }
7317 
7318 int
7319 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7320 {
7321 	struct ctl_lun *lun = CTL_LUN(ctsio);
7322 	struct scsi_report_supported_opcodes *cdb;
7323 	const struct ctl_cmd_entry *entry, *sentry;
7324 	struct scsi_report_supported_opcodes_all *all;
7325 	struct scsi_report_supported_opcodes_descr *descr;
7326 	struct scsi_report_supported_opcodes_one *one;
7327 	int retval;
7328 	int alloc_len, total_len;
7329 	int opcode, service_action, i, j, num;
7330 
7331 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7332 
7333 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7334 	retval = CTL_RETVAL_COMPLETE;
7335 
7336 	opcode = cdb->requested_opcode;
7337 	service_action = scsi_2btoul(cdb->requested_service_action);
7338 	switch (cdb->options & RSO_OPTIONS_MASK) {
7339 	case RSO_OPTIONS_ALL:
7340 		num = 0;
7341 		for (i = 0; i < 256; i++) {
7342 			entry = &ctl_cmd_table[i];
7343 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7344 				for (j = 0; j < 32; j++) {
7345 					sentry = &((const struct ctl_cmd_entry *)
7346 					    entry->execute)[j];
7347 					if (ctl_cmd_applicable(
7348 					    lun->be_lun->lun_type, sentry))
7349 						num++;
7350 				}
7351 			} else {
7352 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7353 				    entry))
7354 					num++;
7355 			}
7356 		}
7357 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7358 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7359 		break;
7360 	case RSO_OPTIONS_OC:
7361 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7362 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7363 					      /*sks_valid*/ 1,
7364 					      /*command*/ 1,
7365 					      /*field*/ 2,
7366 					      /*bit_valid*/ 1,
7367 					      /*bit*/ 2);
7368 			ctl_done((union ctl_io *)ctsio);
7369 			return (CTL_RETVAL_COMPLETE);
7370 		}
7371 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7372 		break;
7373 	case RSO_OPTIONS_OC_SA:
7374 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7375 		    service_action >= 32) {
7376 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7377 					      /*sks_valid*/ 1,
7378 					      /*command*/ 1,
7379 					      /*field*/ 2,
7380 					      /*bit_valid*/ 1,
7381 					      /*bit*/ 2);
7382 			ctl_done((union ctl_io *)ctsio);
7383 			return (CTL_RETVAL_COMPLETE);
7384 		}
7385 		/* FALLTHROUGH */
7386 	case RSO_OPTIONS_OC_ASA:
7387 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7388 		break;
7389 	default:
7390 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7391 				      /*sks_valid*/ 1,
7392 				      /*command*/ 1,
7393 				      /*field*/ 2,
7394 				      /*bit_valid*/ 1,
7395 				      /*bit*/ 2);
7396 		ctl_done((union ctl_io *)ctsio);
7397 		return (CTL_RETVAL_COMPLETE);
7398 	}
7399 
7400 	alloc_len = scsi_4btoul(cdb->length);
7401 
7402 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7403 
7404 	ctsio->kern_sg_entries = 0;
7405 
7406 	if (total_len < alloc_len) {
7407 		ctsio->residual = alloc_len - total_len;
7408 		ctsio->kern_data_len = total_len;
7409 		ctsio->kern_total_len = total_len;
7410 	} else {
7411 		ctsio->residual = 0;
7412 		ctsio->kern_data_len = alloc_len;
7413 		ctsio->kern_total_len = alloc_len;
7414 	}
7415 	ctsio->kern_data_resid = 0;
7416 	ctsio->kern_rel_offset = 0;
7417 
7418 	switch (cdb->options & RSO_OPTIONS_MASK) {
7419 	case RSO_OPTIONS_ALL:
7420 		all = (struct scsi_report_supported_opcodes_all *)
7421 		    ctsio->kern_data_ptr;
7422 		num = 0;
7423 		for (i = 0; i < 256; i++) {
7424 			entry = &ctl_cmd_table[i];
7425 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7426 				for (j = 0; j < 32; j++) {
7427 					sentry = &((const struct ctl_cmd_entry *)
7428 					    entry->execute)[j];
7429 					if (!ctl_cmd_applicable(
7430 					    lun->be_lun->lun_type, sentry))
7431 						continue;
7432 					descr = &all->descr[num++];
7433 					descr->opcode = i;
7434 					scsi_ulto2b(j, descr->service_action);
7435 					descr->flags = RSO_SERVACTV;
7436 					scsi_ulto2b(sentry->length,
7437 					    descr->cdb_length);
7438 				}
7439 			} else {
7440 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7441 				    entry))
7442 					continue;
7443 				descr = &all->descr[num++];
7444 				descr->opcode = i;
7445 				scsi_ulto2b(0, descr->service_action);
7446 				descr->flags = 0;
7447 				scsi_ulto2b(entry->length, descr->cdb_length);
7448 			}
7449 		}
7450 		scsi_ulto4b(
7451 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7452 		    all->length);
7453 		break;
7454 	case RSO_OPTIONS_OC:
7455 		one = (struct scsi_report_supported_opcodes_one *)
7456 		    ctsio->kern_data_ptr;
7457 		entry = &ctl_cmd_table[opcode];
7458 		goto fill_one;
7459 	case RSO_OPTIONS_OC_SA:
7460 		one = (struct scsi_report_supported_opcodes_one *)
7461 		    ctsio->kern_data_ptr;
7462 		entry = &ctl_cmd_table[opcode];
7463 		entry = &((const struct ctl_cmd_entry *)
7464 		    entry->execute)[service_action];
7465 fill_one:
7466 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7467 			one->support = 3;
7468 			scsi_ulto2b(entry->length, one->cdb_length);
7469 			one->cdb_usage[0] = opcode;
7470 			memcpy(&one->cdb_usage[1], entry->usage,
7471 			    entry->length - 1);
7472 		} else
7473 			one->support = 1;
7474 		break;
7475 	case RSO_OPTIONS_OC_ASA:
7476 		one = (struct scsi_report_supported_opcodes_one *)
7477 		    ctsio->kern_data_ptr;
7478 		entry = &ctl_cmd_table[opcode];
7479 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7480 			entry = &((const struct ctl_cmd_entry *)
7481 			    entry->execute)[service_action];
7482 		} else if (service_action != 0) {
7483 			one->support = 1;
7484 			break;
7485 		}
7486 		goto fill_one;
7487 	}
7488 
7489 	ctl_set_success(ctsio);
7490 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7491 	ctsio->be_move_done = ctl_config_move_done;
7492 	ctl_datamove((union ctl_io *)ctsio);
7493 	return(retval);
7494 }
7495 
7496 int
7497 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7498 {
7499 	struct scsi_report_supported_tmf *cdb;
7500 	struct scsi_report_supported_tmf_ext_data *data;
7501 	int retval;
7502 	int alloc_len, total_len;
7503 
7504 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7505 
7506 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7507 
7508 	retval = CTL_RETVAL_COMPLETE;
7509 
7510 	if (cdb->options & RST_REPD)
7511 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7512 	else
7513 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7514 	alloc_len = scsi_4btoul(cdb->length);
7515 
7516 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7517 
7518 	ctsio->kern_sg_entries = 0;
7519 
7520 	if (total_len < alloc_len) {
7521 		ctsio->residual = alloc_len - total_len;
7522 		ctsio->kern_data_len = total_len;
7523 		ctsio->kern_total_len = total_len;
7524 	} else {
7525 		ctsio->residual = 0;
7526 		ctsio->kern_data_len = alloc_len;
7527 		ctsio->kern_total_len = alloc_len;
7528 	}
7529 	ctsio->kern_data_resid = 0;
7530 	ctsio->kern_rel_offset = 0;
7531 
7532 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7533 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7534 	    RST_TRS;
7535 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7536 	data->length = total_len - 4;
7537 
7538 	ctl_set_success(ctsio);
7539 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7540 	ctsio->be_move_done = ctl_config_move_done;
7541 	ctl_datamove((union ctl_io *)ctsio);
7542 	return (retval);
7543 }
7544 
7545 int
7546 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7547 {
7548 	struct scsi_report_timestamp *cdb;
7549 	struct scsi_report_timestamp_data *data;
7550 	struct timeval tv;
7551 	int64_t timestamp;
7552 	int retval;
7553 	int alloc_len, total_len;
7554 
7555 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7556 
7557 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7558 
7559 	retval = CTL_RETVAL_COMPLETE;
7560 
7561 	total_len = sizeof(struct scsi_report_timestamp_data);
7562 	alloc_len = scsi_4btoul(cdb->length);
7563 
7564 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7565 
7566 	ctsio->kern_sg_entries = 0;
7567 
7568 	if (total_len < alloc_len) {
7569 		ctsio->residual = alloc_len - total_len;
7570 		ctsio->kern_data_len = total_len;
7571 		ctsio->kern_total_len = total_len;
7572 	} else {
7573 		ctsio->residual = 0;
7574 		ctsio->kern_data_len = alloc_len;
7575 		ctsio->kern_total_len = alloc_len;
7576 	}
7577 	ctsio->kern_data_resid = 0;
7578 	ctsio->kern_rel_offset = 0;
7579 
7580 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7581 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7582 	data->origin = RTS_ORIG_OUTSIDE;
7583 	getmicrotime(&tv);
7584 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7585 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7586 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7587 
7588 	ctl_set_success(ctsio);
7589 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7590 	ctsio->be_move_done = ctl_config_move_done;
7591 	ctl_datamove((union ctl_io *)ctsio);
7592 	return (retval);
7593 }
7594 
7595 int
7596 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7597 {
7598 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7599 	struct ctl_lun *lun = CTL_LUN(ctsio);
7600 	struct scsi_per_res_in *cdb;
7601 	int alloc_len, total_len = 0;
7602 	/* struct scsi_per_res_in_rsrv in_data; */
7603 	uint64_t key;
7604 
7605 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7606 
7607 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7608 
7609 	alloc_len = scsi_2btoul(cdb->length);
7610 
7611 retry:
7612 	mtx_lock(&lun->lun_lock);
7613 	switch (cdb->action) {
7614 	case SPRI_RK: /* read keys */
7615 		total_len = sizeof(struct scsi_per_res_in_keys) +
7616 			lun->pr_key_count *
7617 			sizeof(struct scsi_per_res_key);
7618 		break;
7619 	case SPRI_RR: /* read reservation */
7620 		if (lun->flags & CTL_LUN_PR_RESERVED)
7621 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7622 		else
7623 			total_len = sizeof(struct scsi_per_res_in_header);
7624 		break;
7625 	case SPRI_RC: /* report capabilities */
7626 		total_len = sizeof(struct scsi_per_res_cap);
7627 		break;
7628 	case SPRI_RS: /* read full status */
7629 		total_len = sizeof(struct scsi_per_res_in_header) +
7630 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7631 		    lun->pr_key_count;
7632 		break;
7633 	default:
7634 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7635 	}
7636 	mtx_unlock(&lun->lun_lock);
7637 
7638 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7639 
7640 	if (total_len < alloc_len) {
7641 		ctsio->residual = alloc_len - total_len;
7642 		ctsio->kern_data_len = total_len;
7643 		ctsio->kern_total_len = total_len;
7644 	} else {
7645 		ctsio->residual = 0;
7646 		ctsio->kern_data_len = alloc_len;
7647 		ctsio->kern_total_len = alloc_len;
7648 	}
7649 
7650 	ctsio->kern_data_resid = 0;
7651 	ctsio->kern_rel_offset = 0;
7652 	ctsio->kern_sg_entries = 0;
7653 
7654 	mtx_lock(&lun->lun_lock);
7655 	switch (cdb->action) {
7656 	case SPRI_RK: { // read keys
7657         struct scsi_per_res_in_keys *res_keys;
7658 		int i, key_count;
7659 
7660 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7661 
7662 		/*
7663 		 * We had to drop the lock to allocate our buffer, which
7664 		 * leaves time for someone to come in with another
7665 		 * persistent reservation.  (That is unlikely, though,
7666 		 * since this should be the only persistent reservation
7667 		 * command active right now.)
7668 		 */
7669 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7670 		    (lun->pr_key_count *
7671 		     sizeof(struct scsi_per_res_key)))){
7672 			mtx_unlock(&lun->lun_lock);
7673 			free(ctsio->kern_data_ptr, M_CTL);
7674 			printf("%s: reservation length changed, retrying\n",
7675 			       __func__);
7676 			goto retry;
7677 		}
7678 
7679 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7680 
7681 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7682 			     lun->pr_key_count, res_keys->header.length);
7683 
7684 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7685 			if ((key = ctl_get_prkey(lun, i)) == 0)
7686 				continue;
7687 
7688 			/*
7689 			 * We used lun->pr_key_count to calculate the
7690 			 * size to allocate.  If it turns out the number of
7691 			 * initiators with the registered flag set is
7692 			 * larger than that (i.e. they haven't been kept in
7693 			 * sync), we've got a problem.
7694 			 */
7695 			if (key_count >= lun->pr_key_count) {
7696 				key_count++;
7697 				continue;
7698 			}
7699 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7700 			key_count++;
7701 		}
7702 		break;
7703 	}
7704 	case SPRI_RR: { // read reservation
7705 		struct scsi_per_res_in_rsrv *res;
7706 		int tmp_len, header_only;
7707 
7708 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7709 
7710 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7711 
7712 		if (lun->flags & CTL_LUN_PR_RESERVED)
7713 		{
7714 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7715 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7716 				    res->header.length);
7717 			header_only = 0;
7718 		} else {
7719 			tmp_len = sizeof(struct scsi_per_res_in_header);
7720 			scsi_ulto4b(0, res->header.length);
7721 			header_only = 1;
7722 		}
7723 
7724 		/*
7725 		 * We had to drop the lock to allocate our buffer, which
7726 		 * leaves time for someone to come in with another
7727 		 * persistent reservation.  (That is unlikely, though,
7728 		 * since this should be the only persistent reservation
7729 		 * command active right now.)
7730 		 */
7731 		if (tmp_len != total_len) {
7732 			mtx_unlock(&lun->lun_lock);
7733 			free(ctsio->kern_data_ptr, M_CTL);
7734 			printf("%s: reservation status changed, retrying\n",
7735 			       __func__);
7736 			goto retry;
7737 		}
7738 
7739 		/*
7740 		 * No reservation held, so we're done.
7741 		 */
7742 		if (header_only != 0)
7743 			break;
7744 
7745 		/*
7746 		 * If the registration is an All Registrants type, the key
7747 		 * is 0, since it doesn't really matter.
7748 		 */
7749 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7750 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7751 			    res->data.reservation);
7752 		}
7753 		res->data.scopetype = lun->pr_res_type;
7754 		break;
7755 	}
7756 	case SPRI_RC:     //report capabilities
7757 	{
7758 		struct scsi_per_res_cap *res_cap;
7759 		uint16_t type_mask;
7760 
7761 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7762 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7763 		res_cap->flags1 = SPRI_CRH;
7764 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7765 		type_mask = SPRI_TM_WR_EX_AR |
7766 			    SPRI_TM_EX_AC_RO |
7767 			    SPRI_TM_WR_EX_RO |
7768 			    SPRI_TM_EX_AC |
7769 			    SPRI_TM_WR_EX |
7770 			    SPRI_TM_EX_AC_AR;
7771 		scsi_ulto2b(type_mask, res_cap->type_mask);
7772 		break;
7773 	}
7774 	case SPRI_RS: { // read full status
7775 		struct scsi_per_res_in_full *res_status;
7776 		struct scsi_per_res_in_full_desc *res_desc;
7777 		struct ctl_port *port;
7778 		int i, len;
7779 
7780 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7781 
7782 		/*
7783 		 * We had to drop the lock to allocate our buffer, which
7784 		 * leaves time for someone to come in with another
7785 		 * persistent reservation.  (That is unlikely, though,
7786 		 * since this should be the only persistent reservation
7787 		 * command active right now.)
7788 		 */
7789 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7790 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7791 		     lun->pr_key_count)){
7792 			mtx_unlock(&lun->lun_lock);
7793 			free(ctsio->kern_data_ptr, M_CTL);
7794 			printf("%s: reservation length changed, retrying\n",
7795 			       __func__);
7796 			goto retry;
7797 		}
7798 
7799 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7800 
7801 		res_desc = &res_status->desc[0];
7802 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7803 			if ((key = ctl_get_prkey(lun, i)) == 0)
7804 				continue;
7805 
7806 			scsi_u64to8b(key, res_desc->res_key.key);
7807 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7808 			    (lun->pr_res_idx == i ||
7809 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7810 				res_desc->flags = SPRI_FULL_R_HOLDER;
7811 				res_desc->scopetype = lun->pr_res_type;
7812 			}
7813 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7814 			    res_desc->rel_trgt_port_id);
7815 			len = 0;
7816 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7817 			if (port != NULL)
7818 				len = ctl_create_iid(port,
7819 				    i % CTL_MAX_INIT_PER_PORT,
7820 				    res_desc->transport_id);
7821 			scsi_ulto4b(len, res_desc->additional_length);
7822 			res_desc = (struct scsi_per_res_in_full_desc *)
7823 			    &res_desc->transport_id[len];
7824 		}
7825 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7826 		    res_status->header.length);
7827 		break;
7828 	}
7829 	default:
7830 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7831 	}
7832 	mtx_unlock(&lun->lun_lock);
7833 
7834 	ctl_set_success(ctsio);
7835 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7836 	ctsio->be_move_done = ctl_config_move_done;
7837 	ctl_datamove((union ctl_io *)ctsio);
7838 	return (CTL_RETVAL_COMPLETE);
7839 }
7840 
7841 /*
7842  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7843  * it should return.
7844  */
7845 static int
7846 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7847 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7848 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7849 		struct scsi_per_res_out_parms* param)
7850 {
7851 	union ctl_ha_msg persis_io;
7852 	int i;
7853 
7854 	mtx_lock(&lun->lun_lock);
7855 	if (sa_res_key == 0) {
7856 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7857 			/* validate scope and type */
7858 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7859 			     SPR_LU_SCOPE) {
7860 				mtx_unlock(&lun->lun_lock);
7861 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7862 						      /*sks_valid*/ 1,
7863 						      /*command*/ 1,
7864 						      /*field*/ 2,
7865 						      /*bit_valid*/ 1,
7866 						      /*bit*/ 4);
7867 				ctl_done((union ctl_io *)ctsio);
7868 				return (1);
7869 			}
7870 
7871 		        if (type>8 || type==2 || type==4 || type==0) {
7872 				mtx_unlock(&lun->lun_lock);
7873 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7874        	           				      /*sks_valid*/ 1,
7875 						      /*command*/ 1,
7876 						      /*field*/ 2,
7877 						      /*bit_valid*/ 1,
7878 						      /*bit*/ 0);
7879 				ctl_done((union ctl_io *)ctsio);
7880 				return (1);
7881 		        }
7882 
7883 			/*
7884 			 * Unregister everybody else and build UA for
7885 			 * them
7886 			 */
7887 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7888 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7889 					continue;
7890 
7891 				ctl_clr_prkey(lun, i);
7892 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7893 			}
7894 			lun->pr_key_count = 1;
7895 			lun->pr_res_type = type;
7896 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7897 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7898 				lun->pr_res_idx = residx;
7899 			lun->pr_generation++;
7900 			mtx_unlock(&lun->lun_lock);
7901 
7902 			/* send msg to other side */
7903 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7904 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7905 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7906 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7907 			persis_io.pr.pr_info.res_type = type;
7908 			memcpy(persis_io.pr.pr_info.sa_res_key,
7909 			       param->serv_act_res_key,
7910 			       sizeof(param->serv_act_res_key));
7911 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7912 			    sizeof(persis_io.pr), M_WAITOK);
7913 		} else {
7914 			/* not all registrants */
7915 			mtx_unlock(&lun->lun_lock);
7916 			free(ctsio->kern_data_ptr, M_CTL);
7917 			ctl_set_invalid_field(ctsio,
7918 					      /*sks_valid*/ 1,
7919 					      /*command*/ 0,
7920 					      /*field*/ 8,
7921 					      /*bit_valid*/ 0,
7922 					      /*bit*/ 0);
7923 			ctl_done((union ctl_io *)ctsio);
7924 			return (1);
7925 		}
7926 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7927 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7928 		int found = 0;
7929 
7930 		if (res_key == sa_res_key) {
7931 			/* special case */
7932 			/*
7933 			 * The spec implies this is not good but doesn't
7934 			 * say what to do. There are two choices either
7935 			 * generate a res conflict or check condition
7936 			 * with illegal field in parameter data. Since
7937 			 * that is what is done when the sa_res_key is
7938 			 * zero I'll take that approach since this has
7939 			 * to do with the sa_res_key.
7940 			 */
7941 			mtx_unlock(&lun->lun_lock);
7942 			free(ctsio->kern_data_ptr, M_CTL);
7943 			ctl_set_invalid_field(ctsio,
7944 					      /*sks_valid*/ 1,
7945 					      /*command*/ 0,
7946 					      /*field*/ 8,
7947 					      /*bit_valid*/ 0,
7948 					      /*bit*/ 0);
7949 			ctl_done((union ctl_io *)ctsio);
7950 			return (1);
7951 		}
7952 
7953 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7954 			if (ctl_get_prkey(lun, i) != sa_res_key)
7955 				continue;
7956 
7957 			found = 1;
7958 			ctl_clr_prkey(lun, i);
7959 			lun->pr_key_count--;
7960 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7961 		}
7962 		if (!found) {
7963 			mtx_unlock(&lun->lun_lock);
7964 			free(ctsio->kern_data_ptr, M_CTL);
7965 			ctl_set_reservation_conflict(ctsio);
7966 			ctl_done((union ctl_io *)ctsio);
7967 			return (CTL_RETVAL_COMPLETE);
7968 		}
7969 		lun->pr_generation++;
7970 		mtx_unlock(&lun->lun_lock);
7971 
7972 		/* send msg to other side */
7973 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7974 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7975 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7976 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7977 		persis_io.pr.pr_info.res_type = type;
7978 		memcpy(persis_io.pr.pr_info.sa_res_key,
7979 		       param->serv_act_res_key,
7980 		       sizeof(param->serv_act_res_key));
7981 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7982 		    sizeof(persis_io.pr), M_WAITOK);
7983 	} else {
7984 		/* Reserved but not all registrants */
7985 		/* sa_res_key is res holder */
7986 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7987 			/* validate scope and type */
7988 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7989 			     SPR_LU_SCOPE) {
7990 				mtx_unlock(&lun->lun_lock);
7991 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7992 						      /*sks_valid*/ 1,
7993 						      /*command*/ 1,
7994 						      /*field*/ 2,
7995 						      /*bit_valid*/ 1,
7996 						      /*bit*/ 4);
7997 				ctl_done((union ctl_io *)ctsio);
7998 				return (1);
7999 			}
8000 
8001 			if (type>8 || type==2 || type==4 || type==0) {
8002 				mtx_unlock(&lun->lun_lock);
8003 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8004 						      /*sks_valid*/ 1,
8005 						      /*command*/ 1,
8006 						      /*field*/ 2,
8007 						      /*bit_valid*/ 1,
8008 						      /*bit*/ 0);
8009 				ctl_done((union ctl_io *)ctsio);
8010 				return (1);
8011 			}
8012 
8013 			/*
8014 			 * Do the following:
8015 			 * if sa_res_key != res_key remove all
8016 			 * registrants w/sa_res_key and generate UA
8017 			 * for these registrants(Registrations
8018 			 * Preempted) if it wasn't an exclusive
8019 			 * reservation generate UA(Reservations
8020 			 * Preempted) for all other registered nexuses
8021 			 * if the type has changed. Establish the new
8022 			 * reservation and holder. If res_key and
8023 			 * sa_res_key are the same do the above
8024 			 * except don't unregister the res holder.
8025 			 */
8026 
8027 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8028 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8029 					continue;
8030 
8031 				if (sa_res_key == ctl_get_prkey(lun, i)) {
8032 					ctl_clr_prkey(lun, i);
8033 					lun->pr_key_count--;
8034 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8035 				} else if (type != lun->pr_res_type &&
8036 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8037 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8038 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8039 				}
8040 			}
8041 			lun->pr_res_type = type;
8042 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8043 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8044 				lun->pr_res_idx = residx;
8045 			else
8046 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8047 			lun->pr_generation++;
8048 			mtx_unlock(&lun->lun_lock);
8049 
8050 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8051 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8052 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8053 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8054 			persis_io.pr.pr_info.res_type = type;
8055 			memcpy(persis_io.pr.pr_info.sa_res_key,
8056 			       param->serv_act_res_key,
8057 			       sizeof(param->serv_act_res_key));
8058 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8059 			    sizeof(persis_io.pr), M_WAITOK);
8060 		} else {
8061 			/*
8062 			 * sa_res_key is not the res holder just
8063 			 * remove registrants
8064 			 */
8065 			int found=0;
8066 
8067 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8068 				if (sa_res_key != ctl_get_prkey(lun, i))
8069 					continue;
8070 
8071 				found = 1;
8072 				ctl_clr_prkey(lun, i);
8073 				lun->pr_key_count--;
8074 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8075 			}
8076 
8077 			if (!found) {
8078 				mtx_unlock(&lun->lun_lock);
8079 				free(ctsio->kern_data_ptr, M_CTL);
8080 				ctl_set_reservation_conflict(ctsio);
8081 				ctl_done((union ctl_io *)ctsio);
8082 		        	return (1);
8083 			}
8084 			lun->pr_generation++;
8085 			mtx_unlock(&lun->lun_lock);
8086 
8087 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8088 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8089 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8090 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8091 			persis_io.pr.pr_info.res_type = type;
8092 			memcpy(persis_io.pr.pr_info.sa_res_key,
8093 			       param->serv_act_res_key,
8094 			       sizeof(param->serv_act_res_key));
8095 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8096 			    sizeof(persis_io.pr), M_WAITOK);
8097 		}
8098 	}
8099 	return (0);
8100 }
8101 
8102 static void
8103 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8104 {
8105 	uint64_t sa_res_key;
8106 	int i;
8107 
8108 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8109 
8110 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8111 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8112 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8113 		if (sa_res_key == 0) {
8114 			/*
8115 			 * Unregister everybody else and build UA for
8116 			 * them
8117 			 */
8118 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8119 				if (i == msg->pr.pr_info.residx ||
8120 				    ctl_get_prkey(lun, i) == 0)
8121 					continue;
8122 
8123 				ctl_clr_prkey(lun, i);
8124 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8125 			}
8126 
8127 			lun->pr_key_count = 1;
8128 			lun->pr_res_type = msg->pr.pr_info.res_type;
8129 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8130 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8131 				lun->pr_res_idx = msg->pr.pr_info.residx;
8132 		} else {
8133 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8134 				if (sa_res_key == ctl_get_prkey(lun, i))
8135 					continue;
8136 
8137 				ctl_clr_prkey(lun, i);
8138 				lun->pr_key_count--;
8139 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8140 			}
8141 		}
8142 	} else {
8143 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8144 			if (i == msg->pr.pr_info.residx ||
8145 			    ctl_get_prkey(lun, i) == 0)
8146 				continue;
8147 
8148 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8149 				ctl_clr_prkey(lun, i);
8150 				lun->pr_key_count--;
8151 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8152 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8153 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8154 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8155 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8156 			}
8157 		}
8158 		lun->pr_res_type = msg->pr.pr_info.res_type;
8159 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8160 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8161 			lun->pr_res_idx = msg->pr.pr_info.residx;
8162 		else
8163 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8164 	}
8165 	lun->pr_generation++;
8166 
8167 }
8168 
8169 
8170 int
8171 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8172 {
8173 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8174 	struct ctl_lun *lun = CTL_LUN(ctsio);
8175 	int retval;
8176 	u_int32_t param_len;
8177 	struct scsi_per_res_out *cdb;
8178 	struct scsi_per_res_out_parms* param;
8179 	uint32_t residx;
8180 	uint64_t res_key, sa_res_key, key;
8181 	uint8_t type;
8182 	union ctl_ha_msg persis_io;
8183 	int    i;
8184 
8185 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8186 
8187 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8188 	retval = CTL_RETVAL_COMPLETE;
8189 
8190 	/*
8191 	 * We only support whole-LUN scope.  The scope & type are ignored for
8192 	 * register, register and ignore existing key and clear.
8193 	 * We sometimes ignore scope and type on preempts too!!
8194 	 * Verify reservation type here as well.
8195 	 */
8196 	type = cdb->scope_type & SPR_TYPE_MASK;
8197 	if ((cdb->action == SPRO_RESERVE)
8198 	 || (cdb->action == SPRO_RELEASE)) {
8199 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8200 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8201 					      /*sks_valid*/ 1,
8202 					      /*command*/ 1,
8203 					      /*field*/ 2,
8204 					      /*bit_valid*/ 1,
8205 					      /*bit*/ 4);
8206 			ctl_done((union ctl_io *)ctsio);
8207 			return (CTL_RETVAL_COMPLETE);
8208 		}
8209 
8210 		if (type>8 || type==2 || type==4 || type==0) {
8211 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8212 					      /*sks_valid*/ 1,
8213 					      /*command*/ 1,
8214 					      /*field*/ 2,
8215 					      /*bit_valid*/ 1,
8216 					      /*bit*/ 0);
8217 			ctl_done((union ctl_io *)ctsio);
8218 			return (CTL_RETVAL_COMPLETE);
8219 		}
8220 	}
8221 
8222 	param_len = scsi_4btoul(cdb->length);
8223 
8224 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8225 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8226 		ctsio->kern_data_len = param_len;
8227 		ctsio->kern_total_len = param_len;
8228 		ctsio->kern_data_resid = 0;
8229 		ctsio->kern_rel_offset = 0;
8230 		ctsio->kern_sg_entries = 0;
8231 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8232 		ctsio->be_move_done = ctl_config_move_done;
8233 		ctl_datamove((union ctl_io *)ctsio);
8234 
8235 		return (CTL_RETVAL_COMPLETE);
8236 	}
8237 
8238 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8239 
8240 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8241 	res_key = scsi_8btou64(param->res_key.key);
8242 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8243 
8244 	/*
8245 	 * Validate the reservation key here except for SPRO_REG_IGNO
8246 	 * This must be done for all other service actions
8247 	 */
8248 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8249 		mtx_lock(&lun->lun_lock);
8250 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8251 			if (res_key != key) {
8252 				/*
8253 				 * The current key passed in doesn't match
8254 				 * the one the initiator previously
8255 				 * registered.
8256 				 */
8257 				mtx_unlock(&lun->lun_lock);
8258 				free(ctsio->kern_data_ptr, M_CTL);
8259 				ctl_set_reservation_conflict(ctsio);
8260 				ctl_done((union ctl_io *)ctsio);
8261 				return (CTL_RETVAL_COMPLETE);
8262 			}
8263 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8264 			/*
8265 			 * We are not registered
8266 			 */
8267 			mtx_unlock(&lun->lun_lock);
8268 			free(ctsio->kern_data_ptr, M_CTL);
8269 			ctl_set_reservation_conflict(ctsio);
8270 			ctl_done((union ctl_io *)ctsio);
8271 			return (CTL_RETVAL_COMPLETE);
8272 		} else if (res_key != 0) {
8273 			/*
8274 			 * We are not registered and trying to register but
8275 			 * the register key isn't zero.
8276 			 */
8277 			mtx_unlock(&lun->lun_lock);
8278 			free(ctsio->kern_data_ptr, M_CTL);
8279 			ctl_set_reservation_conflict(ctsio);
8280 			ctl_done((union ctl_io *)ctsio);
8281 			return (CTL_RETVAL_COMPLETE);
8282 		}
8283 		mtx_unlock(&lun->lun_lock);
8284 	}
8285 
8286 	switch (cdb->action & SPRO_ACTION_MASK) {
8287 	case SPRO_REGISTER:
8288 	case SPRO_REG_IGNO: {
8289 
8290 #if 0
8291 		printf("Registration received\n");
8292 #endif
8293 
8294 		/*
8295 		 * We don't support any of these options, as we report in
8296 		 * the read capabilities request (see
8297 		 * ctl_persistent_reserve_in(), above).
8298 		 */
8299 		if ((param->flags & SPR_SPEC_I_PT)
8300 		 || (param->flags & SPR_ALL_TG_PT)
8301 		 || (param->flags & SPR_APTPL)) {
8302 			int bit_ptr;
8303 
8304 			if (param->flags & SPR_APTPL)
8305 				bit_ptr = 0;
8306 			else if (param->flags & SPR_ALL_TG_PT)
8307 				bit_ptr = 2;
8308 			else /* SPR_SPEC_I_PT */
8309 				bit_ptr = 3;
8310 
8311 			free(ctsio->kern_data_ptr, M_CTL);
8312 			ctl_set_invalid_field(ctsio,
8313 					      /*sks_valid*/ 1,
8314 					      /*command*/ 0,
8315 					      /*field*/ 20,
8316 					      /*bit_valid*/ 1,
8317 					      /*bit*/ bit_ptr);
8318 			ctl_done((union ctl_io *)ctsio);
8319 			return (CTL_RETVAL_COMPLETE);
8320 		}
8321 
8322 		mtx_lock(&lun->lun_lock);
8323 
8324 		/*
8325 		 * The initiator wants to clear the
8326 		 * key/unregister.
8327 		 */
8328 		if (sa_res_key == 0) {
8329 			if ((res_key == 0
8330 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8331 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8332 			  && ctl_get_prkey(lun, residx) == 0)) {
8333 				mtx_unlock(&lun->lun_lock);
8334 				goto done;
8335 			}
8336 
8337 			ctl_clr_prkey(lun, residx);
8338 			lun->pr_key_count--;
8339 
8340 			if (residx == lun->pr_res_idx) {
8341 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8342 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8343 
8344 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8345 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8346 				    lun->pr_key_count) {
8347 					/*
8348 					 * If the reservation is a registrants
8349 					 * only type we need to generate a UA
8350 					 * for other registered inits.  The
8351 					 * sense code should be RESERVATIONS
8352 					 * RELEASED
8353 					 */
8354 
8355 					for (i = softc->init_min; i < softc->init_max; i++){
8356 						if (ctl_get_prkey(lun, i) == 0)
8357 							continue;
8358 						ctl_est_ua(lun, i,
8359 						    CTL_UA_RES_RELEASE);
8360 					}
8361 				}
8362 				lun->pr_res_type = 0;
8363 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8364 				if (lun->pr_key_count==0) {
8365 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8366 					lun->pr_res_type = 0;
8367 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8368 				}
8369 			}
8370 			lun->pr_generation++;
8371 			mtx_unlock(&lun->lun_lock);
8372 
8373 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8374 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8375 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8376 			persis_io.pr.pr_info.residx = residx;
8377 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8378 			    sizeof(persis_io.pr), M_WAITOK);
8379 		} else /* sa_res_key != 0 */ {
8380 
8381 			/*
8382 			 * If we aren't registered currently then increment
8383 			 * the key count and set the registered flag.
8384 			 */
8385 			ctl_alloc_prkey(lun, residx);
8386 			if (ctl_get_prkey(lun, residx) == 0)
8387 				lun->pr_key_count++;
8388 			ctl_set_prkey(lun, residx, sa_res_key);
8389 			lun->pr_generation++;
8390 			mtx_unlock(&lun->lun_lock);
8391 
8392 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8393 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8394 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8395 			persis_io.pr.pr_info.residx = residx;
8396 			memcpy(persis_io.pr.pr_info.sa_res_key,
8397 			       param->serv_act_res_key,
8398 			       sizeof(param->serv_act_res_key));
8399 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8400 			    sizeof(persis_io.pr), M_WAITOK);
8401 		}
8402 
8403 		break;
8404 	}
8405 	case SPRO_RESERVE:
8406 #if 0
8407                 printf("Reserve executed type %d\n", type);
8408 #endif
8409 		mtx_lock(&lun->lun_lock);
8410 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8411 			/*
8412 			 * if this isn't the reservation holder and it's
8413 			 * not a "all registrants" type or if the type is
8414 			 * different then we have a conflict
8415 			 */
8416 			if ((lun->pr_res_idx != residx
8417 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8418 			 || lun->pr_res_type != type) {
8419 				mtx_unlock(&lun->lun_lock);
8420 				free(ctsio->kern_data_ptr, M_CTL);
8421 				ctl_set_reservation_conflict(ctsio);
8422 				ctl_done((union ctl_io *)ctsio);
8423 				return (CTL_RETVAL_COMPLETE);
8424 			}
8425 			mtx_unlock(&lun->lun_lock);
8426 		} else /* create a reservation */ {
8427 			/*
8428 			 * If it's not an "all registrants" type record
8429 			 * reservation holder
8430 			 */
8431 			if (type != SPR_TYPE_WR_EX_AR
8432 			 && type != SPR_TYPE_EX_AC_AR)
8433 				lun->pr_res_idx = residx; /* Res holder */
8434 			else
8435 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8436 
8437 			lun->flags |= CTL_LUN_PR_RESERVED;
8438 			lun->pr_res_type = type;
8439 
8440 			mtx_unlock(&lun->lun_lock);
8441 
8442 			/* send msg to other side */
8443 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8444 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8445 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8446 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8447 			persis_io.pr.pr_info.res_type = type;
8448 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8449 			    sizeof(persis_io.pr), M_WAITOK);
8450 		}
8451 		break;
8452 
8453 	case SPRO_RELEASE:
8454 		mtx_lock(&lun->lun_lock);
8455 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8456 			/* No reservation exists return good status */
8457 			mtx_unlock(&lun->lun_lock);
8458 			goto done;
8459 		}
8460 		/*
8461 		 * Is this nexus a reservation holder?
8462 		 */
8463 		if (lun->pr_res_idx != residx
8464 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8465 			/*
8466 			 * not a res holder return good status but
8467 			 * do nothing
8468 			 */
8469 			mtx_unlock(&lun->lun_lock);
8470 			goto done;
8471 		}
8472 
8473 		if (lun->pr_res_type != type) {
8474 			mtx_unlock(&lun->lun_lock);
8475 			free(ctsio->kern_data_ptr, M_CTL);
8476 			ctl_set_illegal_pr_release(ctsio);
8477 			ctl_done((union ctl_io *)ctsio);
8478 			return (CTL_RETVAL_COMPLETE);
8479 		}
8480 
8481 		/* okay to release */
8482 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8483 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8484 		lun->pr_res_type = 0;
8485 
8486 		/*
8487 		 * If this isn't an exclusive access reservation and NUAR
8488 		 * is not set, generate UA for all other registrants.
8489 		 */
8490 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8491 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8492 			for (i = softc->init_min; i < softc->init_max; i++) {
8493 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8494 					continue;
8495 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8496 			}
8497 		}
8498 		mtx_unlock(&lun->lun_lock);
8499 
8500 		/* Send msg to other side */
8501 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8502 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8503 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8504 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8505 		     sizeof(persis_io.pr), M_WAITOK);
8506 		break;
8507 
8508 	case SPRO_CLEAR:
8509 		/* send msg to other side */
8510 
8511 		mtx_lock(&lun->lun_lock);
8512 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8513 		lun->pr_res_type = 0;
8514 		lun->pr_key_count = 0;
8515 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8516 
8517 		ctl_clr_prkey(lun, residx);
8518 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8519 			if (ctl_get_prkey(lun, i) != 0) {
8520 				ctl_clr_prkey(lun, i);
8521 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8522 			}
8523 		lun->pr_generation++;
8524 		mtx_unlock(&lun->lun_lock);
8525 
8526 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8527 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8528 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8529 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8530 		     sizeof(persis_io.pr), M_WAITOK);
8531 		break;
8532 
8533 	case SPRO_PREEMPT:
8534 	case SPRO_PRE_ABO: {
8535 		int nretval;
8536 
8537 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8538 					  residx, ctsio, cdb, param);
8539 		if (nretval != 0)
8540 			return (CTL_RETVAL_COMPLETE);
8541 		break;
8542 	}
8543 	default:
8544 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8545 	}
8546 
8547 done:
8548 	free(ctsio->kern_data_ptr, M_CTL);
8549 	ctl_set_success(ctsio);
8550 	ctl_done((union ctl_io *)ctsio);
8551 
8552 	return (retval);
8553 }
8554 
8555 /*
8556  * This routine is for handling a message from the other SC pertaining to
8557  * persistent reserve out. All the error checking will have been done
8558  * so only perorming the action need be done here to keep the two
8559  * in sync.
8560  */
8561 static void
8562 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8563 {
8564 	struct ctl_softc *softc = CTL_SOFTC(io);
8565 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8566 	struct ctl_lun *lun;
8567 	int i;
8568 	uint32_t residx, targ_lun;
8569 
8570 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8571 	mtx_lock(&softc->ctl_lock);
8572 	if (targ_lun >= CTL_MAX_LUNS ||
8573 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8574 		mtx_unlock(&softc->ctl_lock);
8575 		return;
8576 	}
8577 	mtx_lock(&lun->lun_lock);
8578 	mtx_unlock(&softc->ctl_lock);
8579 	if (lun->flags & CTL_LUN_DISABLED) {
8580 		mtx_unlock(&lun->lun_lock);
8581 		return;
8582 	}
8583 	residx = ctl_get_initindex(&msg->hdr.nexus);
8584 	switch(msg->pr.pr_info.action) {
8585 	case CTL_PR_REG_KEY:
8586 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8587 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8588 			lun->pr_key_count++;
8589 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8590 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8591 		lun->pr_generation++;
8592 		break;
8593 
8594 	case CTL_PR_UNREG_KEY:
8595 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8596 		lun->pr_key_count--;
8597 
8598 		/* XXX Need to see if the reservation has been released */
8599 		/* if so do we need to generate UA? */
8600 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8601 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8602 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8603 
8604 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8605 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8606 			    lun->pr_key_count) {
8607 				/*
8608 				 * If the reservation is a registrants
8609 				 * only type we need to generate a UA
8610 				 * for other registered inits.  The
8611 				 * sense code should be RESERVATIONS
8612 				 * RELEASED
8613 				 */
8614 
8615 				for (i = softc->init_min; i < softc->init_max; i++) {
8616 					if (ctl_get_prkey(lun, i) == 0)
8617 						continue;
8618 
8619 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8620 				}
8621 			}
8622 			lun->pr_res_type = 0;
8623 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8624 			if (lun->pr_key_count==0) {
8625 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8626 				lun->pr_res_type = 0;
8627 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8628 			}
8629 		}
8630 		lun->pr_generation++;
8631 		break;
8632 
8633 	case CTL_PR_RESERVE:
8634 		lun->flags |= CTL_LUN_PR_RESERVED;
8635 		lun->pr_res_type = msg->pr.pr_info.res_type;
8636 		lun->pr_res_idx = msg->pr.pr_info.residx;
8637 
8638 		break;
8639 
8640 	case CTL_PR_RELEASE:
8641 		/*
8642 		 * If this isn't an exclusive access reservation and NUAR
8643 		 * is not set, generate UA for all other registrants.
8644 		 */
8645 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8646 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8647 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8648 			for (i = softc->init_min; i < softc->init_max; i++)
8649 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8650 					continue;
8651 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8652 		}
8653 
8654 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8655 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8656 		lun->pr_res_type = 0;
8657 		break;
8658 
8659 	case CTL_PR_PREEMPT:
8660 		ctl_pro_preempt_other(lun, msg);
8661 		break;
8662 	case CTL_PR_CLEAR:
8663 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8664 		lun->pr_res_type = 0;
8665 		lun->pr_key_count = 0;
8666 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8667 
8668 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8669 			if (ctl_get_prkey(lun, i) == 0)
8670 				continue;
8671 			ctl_clr_prkey(lun, i);
8672 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8673 		}
8674 		lun->pr_generation++;
8675 		break;
8676 	}
8677 
8678 	mtx_unlock(&lun->lun_lock);
8679 }
8680 
8681 int
8682 ctl_read_write(struct ctl_scsiio *ctsio)
8683 {
8684 	struct ctl_lun *lun = CTL_LUN(ctsio);
8685 	struct ctl_lba_len_flags *lbalen;
8686 	uint64_t lba;
8687 	uint32_t num_blocks;
8688 	int flags, retval;
8689 	int isread;
8690 
8691 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8692 
8693 	flags = 0;
8694 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8695 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8696 	switch (ctsio->cdb[0]) {
8697 	case READ_6:
8698 	case WRITE_6: {
8699 		struct scsi_rw_6 *cdb;
8700 
8701 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8702 
8703 		lba = scsi_3btoul(cdb->addr);
8704 		/* only 5 bits are valid in the most significant address byte */
8705 		lba &= 0x1fffff;
8706 		num_blocks = cdb->length;
8707 		/*
8708 		 * This is correct according to SBC-2.
8709 		 */
8710 		if (num_blocks == 0)
8711 			num_blocks = 256;
8712 		break;
8713 	}
8714 	case READ_10:
8715 	case WRITE_10: {
8716 		struct scsi_rw_10 *cdb;
8717 
8718 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8719 		if (cdb->byte2 & SRW10_FUA)
8720 			flags |= CTL_LLF_FUA;
8721 		if (cdb->byte2 & SRW10_DPO)
8722 			flags |= CTL_LLF_DPO;
8723 		lba = scsi_4btoul(cdb->addr);
8724 		num_blocks = scsi_2btoul(cdb->length);
8725 		break;
8726 	}
8727 	case WRITE_VERIFY_10: {
8728 		struct scsi_write_verify_10 *cdb;
8729 
8730 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8731 		flags |= CTL_LLF_FUA;
8732 		if (cdb->byte2 & SWV_DPO)
8733 			flags |= CTL_LLF_DPO;
8734 		lba = scsi_4btoul(cdb->addr);
8735 		num_blocks = scsi_2btoul(cdb->length);
8736 		break;
8737 	}
8738 	case READ_12:
8739 	case WRITE_12: {
8740 		struct scsi_rw_12 *cdb;
8741 
8742 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8743 		if (cdb->byte2 & SRW12_FUA)
8744 			flags |= CTL_LLF_FUA;
8745 		if (cdb->byte2 & SRW12_DPO)
8746 			flags |= CTL_LLF_DPO;
8747 		lba = scsi_4btoul(cdb->addr);
8748 		num_blocks = scsi_4btoul(cdb->length);
8749 		break;
8750 	}
8751 	case WRITE_VERIFY_12: {
8752 		struct scsi_write_verify_12 *cdb;
8753 
8754 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8755 		flags |= CTL_LLF_FUA;
8756 		if (cdb->byte2 & SWV_DPO)
8757 			flags |= CTL_LLF_DPO;
8758 		lba = scsi_4btoul(cdb->addr);
8759 		num_blocks = scsi_4btoul(cdb->length);
8760 		break;
8761 	}
8762 	case READ_16:
8763 	case WRITE_16: {
8764 		struct scsi_rw_16 *cdb;
8765 
8766 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8767 		if (cdb->byte2 & SRW12_FUA)
8768 			flags |= CTL_LLF_FUA;
8769 		if (cdb->byte2 & SRW12_DPO)
8770 			flags |= CTL_LLF_DPO;
8771 		lba = scsi_8btou64(cdb->addr);
8772 		num_blocks = scsi_4btoul(cdb->length);
8773 		break;
8774 	}
8775 	case WRITE_ATOMIC_16: {
8776 		struct scsi_write_atomic_16 *cdb;
8777 
8778 		if (lun->be_lun->atomicblock == 0) {
8779 			ctl_set_invalid_opcode(ctsio);
8780 			ctl_done((union ctl_io *)ctsio);
8781 			return (CTL_RETVAL_COMPLETE);
8782 		}
8783 
8784 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8785 		if (cdb->byte2 & SRW12_FUA)
8786 			flags |= CTL_LLF_FUA;
8787 		if (cdb->byte2 & SRW12_DPO)
8788 			flags |= CTL_LLF_DPO;
8789 		lba = scsi_8btou64(cdb->addr);
8790 		num_blocks = scsi_2btoul(cdb->length);
8791 		if (num_blocks > lun->be_lun->atomicblock) {
8792 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8793 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8794 			    /*bit*/ 0);
8795 			ctl_done((union ctl_io *)ctsio);
8796 			return (CTL_RETVAL_COMPLETE);
8797 		}
8798 		break;
8799 	}
8800 	case WRITE_VERIFY_16: {
8801 		struct scsi_write_verify_16 *cdb;
8802 
8803 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8804 		flags |= CTL_LLF_FUA;
8805 		if (cdb->byte2 & SWV_DPO)
8806 			flags |= CTL_LLF_DPO;
8807 		lba = scsi_8btou64(cdb->addr);
8808 		num_blocks = scsi_4btoul(cdb->length);
8809 		break;
8810 	}
8811 	default:
8812 		/*
8813 		 * We got a command we don't support.  This shouldn't
8814 		 * happen, commands should be filtered out above us.
8815 		 */
8816 		ctl_set_invalid_opcode(ctsio);
8817 		ctl_done((union ctl_io *)ctsio);
8818 
8819 		return (CTL_RETVAL_COMPLETE);
8820 		break; /* NOTREACHED */
8821 	}
8822 
8823 	/*
8824 	 * The first check is to make sure we're in bounds, the second
8825 	 * check is to catch wrap-around problems.  If the lba + num blocks
8826 	 * is less than the lba, then we've wrapped around and the block
8827 	 * range is invalid anyway.
8828 	 */
8829 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8830 	 || ((lba + num_blocks) < lba)) {
8831 		ctl_set_lba_out_of_range(ctsio,
8832 		    MAX(lba, lun->be_lun->maxlba + 1));
8833 		ctl_done((union ctl_io *)ctsio);
8834 		return (CTL_RETVAL_COMPLETE);
8835 	}
8836 
8837 	/*
8838 	 * According to SBC-3, a transfer length of 0 is not an error.
8839 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8840 	 * translates to 256 blocks for those commands.
8841 	 */
8842 	if (num_blocks == 0) {
8843 		ctl_set_success(ctsio);
8844 		ctl_done((union ctl_io *)ctsio);
8845 		return (CTL_RETVAL_COMPLETE);
8846 	}
8847 
8848 	/* Set FUA and/or DPO if caches are disabled. */
8849 	if (isread) {
8850 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8851 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8852 	} else {
8853 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8854 			flags |= CTL_LLF_FUA;
8855 	}
8856 
8857 	lbalen = (struct ctl_lba_len_flags *)
8858 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8859 	lbalen->lba = lba;
8860 	lbalen->len = num_blocks;
8861 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8862 
8863 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8864 	ctsio->kern_rel_offset = 0;
8865 
8866 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8867 
8868 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8869 	return (retval);
8870 }
8871 
8872 static int
8873 ctl_cnw_cont(union ctl_io *io)
8874 {
8875 	struct ctl_lun *lun = CTL_LUN(io);
8876 	struct ctl_scsiio *ctsio;
8877 	struct ctl_lba_len_flags *lbalen;
8878 	int retval;
8879 
8880 	ctsio = &io->scsiio;
8881 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8882 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8883 	lbalen = (struct ctl_lba_len_flags *)
8884 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8885 	lbalen->flags &= ~CTL_LLF_COMPARE;
8886 	lbalen->flags |= CTL_LLF_WRITE;
8887 
8888 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8889 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8890 	return (retval);
8891 }
8892 
8893 int
8894 ctl_cnw(struct ctl_scsiio *ctsio)
8895 {
8896 	struct ctl_lun *lun = CTL_LUN(ctsio);
8897 	struct ctl_lba_len_flags *lbalen;
8898 	uint64_t lba;
8899 	uint32_t num_blocks;
8900 	int flags, retval;
8901 
8902 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8903 
8904 	flags = 0;
8905 	switch (ctsio->cdb[0]) {
8906 	case COMPARE_AND_WRITE: {
8907 		struct scsi_compare_and_write *cdb;
8908 
8909 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8910 		if (cdb->byte2 & SRW10_FUA)
8911 			flags |= CTL_LLF_FUA;
8912 		if (cdb->byte2 & SRW10_DPO)
8913 			flags |= CTL_LLF_DPO;
8914 		lba = scsi_8btou64(cdb->addr);
8915 		num_blocks = cdb->length;
8916 		break;
8917 	}
8918 	default:
8919 		/*
8920 		 * We got a command we don't support.  This shouldn't
8921 		 * happen, commands should be filtered out above us.
8922 		 */
8923 		ctl_set_invalid_opcode(ctsio);
8924 		ctl_done((union ctl_io *)ctsio);
8925 
8926 		return (CTL_RETVAL_COMPLETE);
8927 		break; /* NOTREACHED */
8928 	}
8929 
8930 	/*
8931 	 * The first check is to make sure we're in bounds, the second
8932 	 * check is to catch wrap-around problems.  If the lba + num blocks
8933 	 * is less than the lba, then we've wrapped around and the block
8934 	 * range is invalid anyway.
8935 	 */
8936 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8937 	 || ((lba + num_blocks) < lba)) {
8938 		ctl_set_lba_out_of_range(ctsio,
8939 		    MAX(lba, lun->be_lun->maxlba + 1));
8940 		ctl_done((union ctl_io *)ctsio);
8941 		return (CTL_RETVAL_COMPLETE);
8942 	}
8943 
8944 	/*
8945 	 * According to SBC-3, a transfer length of 0 is not an error.
8946 	 */
8947 	if (num_blocks == 0) {
8948 		ctl_set_success(ctsio);
8949 		ctl_done((union ctl_io *)ctsio);
8950 		return (CTL_RETVAL_COMPLETE);
8951 	}
8952 
8953 	/* Set FUA if write cache is disabled. */
8954 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8955 		flags |= CTL_LLF_FUA;
8956 
8957 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8958 	ctsio->kern_rel_offset = 0;
8959 
8960 	/*
8961 	 * Set the IO_CONT flag, so that if this I/O gets passed to
8962 	 * ctl_data_submit_done(), it'll get passed back to
8963 	 * ctl_ctl_cnw_cont() for further processing.
8964 	 */
8965 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8966 	ctsio->io_cont = ctl_cnw_cont;
8967 
8968 	lbalen = (struct ctl_lba_len_flags *)
8969 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8970 	lbalen->lba = lba;
8971 	lbalen->len = num_blocks;
8972 	lbalen->flags = CTL_LLF_COMPARE | flags;
8973 
8974 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8975 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8976 	return (retval);
8977 }
8978 
8979 int
8980 ctl_verify(struct ctl_scsiio *ctsio)
8981 {
8982 	struct ctl_lun *lun = CTL_LUN(ctsio);
8983 	struct ctl_lba_len_flags *lbalen;
8984 	uint64_t lba;
8985 	uint32_t num_blocks;
8986 	int bytchk, flags;
8987 	int retval;
8988 
8989 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8990 
8991 	bytchk = 0;
8992 	flags = CTL_LLF_FUA;
8993 	switch (ctsio->cdb[0]) {
8994 	case VERIFY_10: {
8995 		struct scsi_verify_10 *cdb;
8996 
8997 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8998 		if (cdb->byte2 & SVFY_BYTCHK)
8999 			bytchk = 1;
9000 		if (cdb->byte2 & SVFY_DPO)
9001 			flags |= CTL_LLF_DPO;
9002 		lba = scsi_4btoul(cdb->addr);
9003 		num_blocks = scsi_2btoul(cdb->length);
9004 		break;
9005 	}
9006 	case VERIFY_12: {
9007 		struct scsi_verify_12 *cdb;
9008 
9009 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9010 		if (cdb->byte2 & SVFY_BYTCHK)
9011 			bytchk = 1;
9012 		if (cdb->byte2 & SVFY_DPO)
9013 			flags |= CTL_LLF_DPO;
9014 		lba = scsi_4btoul(cdb->addr);
9015 		num_blocks = scsi_4btoul(cdb->length);
9016 		break;
9017 	}
9018 	case VERIFY_16: {
9019 		struct scsi_rw_16 *cdb;
9020 
9021 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9022 		if (cdb->byte2 & SVFY_BYTCHK)
9023 			bytchk = 1;
9024 		if (cdb->byte2 & SVFY_DPO)
9025 			flags |= CTL_LLF_DPO;
9026 		lba = scsi_8btou64(cdb->addr);
9027 		num_blocks = scsi_4btoul(cdb->length);
9028 		break;
9029 	}
9030 	default:
9031 		/*
9032 		 * We got a command we don't support.  This shouldn't
9033 		 * happen, commands should be filtered out above us.
9034 		 */
9035 		ctl_set_invalid_opcode(ctsio);
9036 		ctl_done((union ctl_io *)ctsio);
9037 		return (CTL_RETVAL_COMPLETE);
9038 	}
9039 
9040 	/*
9041 	 * The first check is to make sure we're in bounds, the second
9042 	 * check is to catch wrap-around problems.  If the lba + num blocks
9043 	 * is less than the lba, then we've wrapped around and the block
9044 	 * range is invalid anyway.
9045 	 */
9046 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9047 	 || ((lba + num_blocks) < lba)) {
9048 		ctl_set_lba_out_of_range(ctsio,
9049 		    MAX(lba, lun->be_lun->maxlba + 1));
9050 		ctl_done((union ctl_io *)ctsio);
9051 		return (CTL_RETVAL_COMPLETE);
9052 	}
9053 
9054 	/*
9055 	 * According to SBC-3, a transfer length of 0 is not an error.
9056 	 */
9057 	if (num_blocks == 0) {
9058 		ctl_set_success(ctsio);
9059 		ctl_done((union ctl_io *)ctsio);
9060 		return (CTL_RETVAL_COMPLETE);
9061 	}
9062 
9063 	lbalen = (struct ctl_lba_len_flags *)
9064 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9065 	lbalen->lba = lba;
9066 	lbalen->len = num_blocks;
9067 	if (bytchk) {
9068 		lbalen->flags = CTL_LLF_COMPARE | flags;
9069 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9070 	} else {
9071 		lbalen->flags = CTL_LLF_VERIFY | flags;
9072 		ctsio->kern_total_len = 0;
9073 	}
9074 	ctsio->kern_rel_offset = 0;
9075 
9076 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9077 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9078 	return (retval);
9079 }
9080 
9081 int
9082 ctl_report_luns(struct ctl_scsiio *ctsio)
9083 {
9084 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9085 	struct ctl_port *port = CTL_PORT(ctsio);
9086 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9087 	struct scsi_report_luns *cdb;
9088 	struct scsi_report_luns_data *lun_data;
9089 	int num_filled, num_luns, num_port_luns, retval;
9090 	uint32_t alloc_len, lun_datalen;
9091 	uint32_t initidx, targ_lun_id, lun_id;
9092 
9093 	retval = CTL_RETVAL_COMPLETE;
9094 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9095 
9096 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9097 
9098 	num_luns = 0;
9099 	num_port_luns = port->lun_map ? port->lun_map_size : CTL_MAX_LUNS;
9100 	mtx_lock(&softc->ctl_lock);
9101 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9102 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9103 			num_luns++;
9104 	}
9105 	mtx_unlock(&softc->ctl_lock);
9106 
9107 	switch (cdb->select_report) {
9108 	case RPL_REPORT_DEFAULT:
9109 	case RPL_REPORT_ALL:
9110 	case RPL_REPORT_NONSUBSID:
9111 		break;
9112 	case RPL_REPORT_WELLKNOWN:
9113 	case RPL_REPORT_ADMIN:
9114 	case RPL_REPORT_CONGLOM:
9115 		num_luns = 0;
9116 		break;
9117 	default:
9118 		ctl_set_invalid_field(ctsio,
9119 				      /*sks_valid*/ 1,
9120 				      /*command*/ 1,
9121 				      /*field*/ 2,
9122 				      /*bit_valid*/ 0,
9123 				      /*bit*/ 0);
9124 		ctl_done((union ctl_io *)ctsio);
9125 		return (retval);
9126 		break; /* NOTREACHED */
9127 	}
9128 
9129 	alloc_len = scsi_4btoul(cdb->length);
9130 	/*
9131 	 * The initiator has to allocate at least 16 bytes for this request,
9132 	 * so he can at least get the header and the first LUN.  Otherwise
9133 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9134 	 */
9135 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9136 	    sizeof(struct scsi_report_luns_lundata))) {
9137 		ctl_set_invalid_field(ctsio,
9138 				      /*sks_valid*/ 1,
9139 				      /*command*/ 1,
9140 				      /*field*/ 6,
9141 				      /*bit_valid*/ 0,
9142 				      /*bit*/ 0);
9143 		ctl_done((union ctl_io *)ctsio);
9144 		return (retval);
9145 	}
9146 
9147 	lun_datalen = sizeof(*lun_data) +
9148 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9149 
9150 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9151 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9152 	ctsio->kern_sg_entries = 0;
9153 
9154 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9155 
9156 	mtx_lock(&softc->ctl_lock);
9157 	for (targ_lun_id = 0, num_filled = 0;
9158 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9159 	    targ_lun_id++) {
9160 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9161 		if (lun_id == UINT32_MAX)
9162 			continue;
9163 		lun = softc->ctl_luns[lun_id];
9164 		if (lun == NULL)
9165 			continue;
9166 
9167 		be64enc(lun_data->luns[num_filled++].lundata,
9168 		    ctl_encode_lun(targ_lun_id));
9169 
9170 		/*
9171 		 * According to SPC-3, rev 14 section 6.21:
9172 		 *
9173 		 * "The execution of a REPORT LUNS command to any valid and
9174 		 * installed logical unit shall clear the REPORTED LUNS DATA
9175 		 * HAS CHANGED unit attention condition for all logical
9176 		 * units of that target with respect to the requesting
9177 		 * initiator. A valid and installed logical unit is one
9178 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9179 		 * INQUIRY data (see 6.4.2)."
9180 		 *
9181 		 * If request_lun is NULL, the LUN this report luns command
9182 		 * was issued to is either disabled or doesn't exist. In that
9183 		 * case, we shouldn't clear any pending lun change unit
9184 		 * attention.
9185 		 */
9186 		if (request_lun != NULL) {
9187 			mtx_lock(&lun->lun_lock);
9188 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9189 			mtx_unlock(&lun->lun_lock);
9190 		}
9191 	}
9192 	mtx_unlock(&softc->ctl_lock);
9193 
9194 	/*
9195 	 * It's quite possible that we've returned fewer LUNs than we allocated
9196 	 * space for.  Trim it.
9197 	 */
9198 	lun_datalen = sizeof(*lun_data) +
9199 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9200 
9201 	if (lun_datalen < alloc_len) {
9202 		ctsio->residual = alloc_len - lun_datalen;
9203 		ctsio->kern_data_len = lun_datalen;
9204 		ctsio->kern_total_len = lun_datalen;
9205 	} else {
9206 		ctsio->residual = 0;
9207 		ctsio->kern_data_len = alloc_len;
9208 		ctsio->kern_total_len = alloc_len;
9209 	}
9210 	ctsio->kern_data_resid = 0;
9211 	ctsio->kern_rel_offset = 0;
9212 	ctsio->kern_sg_entries = 0;
9213 
9214 	/*
9215 	 * We set this to the actual data length, regardless of how much
9216 	 * space we actually have to return results.  If the user looks at
9217 	 * this value, he'll know whether or not he allocated enough space
9218 	 * and reissue the command if necessary.  We don't support well
9219 	 * known logical units, so if the user asks for that, return none.
9220 	 */
9221 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9222 
9223 	/*
9224 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9225 	 * this request.
9226 	 */
9227 	ctl_set_success(ctsio);
9228 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9229 	ctsio->be_move_done = ctl_config_move_done;
9230 	ctl_datamove((union ctl_io *)ctsio);
9231 	return (retval);
9232 }
9233 
9234 int
9235 ctl_request_sense(struct ctl_scsiio *ctsio)
9236 {
9237 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9238 	struct ctl_lun *lun = CTL_LUN(ctsio);
9239 	struct scsi_request_sense *cdb;
9240 	struct scsi_sense_data *sense_ptr;
9241 	uint32_t initidx;
9242 	int have_error;
9243 	u_int sense_len = SSD_FULL_SIZE;
9244 	scsi_sense_data_type sense_format;
9245 	ctl_ua_type ua_type;
9246 	uint8_t asc = 0, ascq = 0;
9247 
9248 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9249 
9250 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9251 
9252 	/*
9253 	 * Determine which sense format the user wants.
9254 	 */
9255 	if (cdb->byte2 & SRS_DESC)
9256 		sense_format = SSD_TYPE_DESC;
9257 	else
9258 		sense_format = SSD_TYPE_FIXED;
9259 
9260 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9261 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9262 	ctsio->kern_sg_entries = 0;
9263 
9264 	/*
9265 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9266 	 * larger than the largest allowed value for the length field in the
9267 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9268 	 */
9269 	ctsio->residual = 0;
9270 	ctsio->kern_data_len = cdb->length;
9271 	ctsio->kern_total_len = cdb->length;
9272 
9273 	ctsio->kern_data_resid = 0;
9274 	ctsio->kern_rel_offset = 0;
9275 	ctsio->kern_sg_entries = 0;
9276 
9277 	/*
9278 	 * If we don't have a LUN, we don't have any pending sense.
9279 	 */
9280 	if (lun == NULL ||
9281 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9282 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9283 		/* "Logical unit not supported" */
9284 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9285 		    /*current_error*/ 1,
9286 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9287 		    /*asc*/ 0x25,
9288 		    /*ascq*/ 0x00,
9289 		    SSD_ELEM_NONE);
9290 		goto send;
9291 	}
9292 
9293 	have_error = 0;
9294 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9295 	/*
9296 	 * Check for pending sense, and then for pending unit attentions.
9297 	 * Pending sense gets returned first, then pending unit attentions.
9298 	 */
9299 	mtx_lock(&lun->lun_lock);
9300 #ifdef CTL_WITH_CA
9301 	if (ctl_is_set(lun->have_ca, initidx)) {
9302 		scsi_sense_data_type stored_format;
9303 
9304 		/*
9305 		 * Check to see which sense format was used for the stored
9306 		 * sense data.
9307 		 */
9308 		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9309 
9310 		/*
9311 		 * If the user requested a different sense format than the
9312 		 * one we stored, then we need to convert it to the other
9313 		 * format.  If we're going from descriptor to fixed format
9314 		 * sense data, we may lose things in translation, depending
9315 		 * on what options were used.
9316 		 *
9317 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9318 		 * for some reason we'll just copy it out as-is.
9319 		 */
9320 		if ((stored_format == SSD_TYPE_FIXED)
9321 		 && (sense_format == SSD_TYPE_DESC))
9322 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9323 			    &lun->pending_sense[initidx],
9324 			    (struct scsi_sense_data_desc *)sense_ptr);
9325 		else if ((stored_format == SSD_TYPE_DESC)
9326 		      && (sense_format == SSD_TYPE_FIXED))
9327 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9328 			    &lun->pending_sense[initidx],
9329 			    (struct scsi_sense_data_fixed *)sense_ptr);
9330 		else
9331 			memcpy(sense_ptr, &lun->pending_sense[initidx],
9332 			       MIN(sizeof(*sense_ptr),
9333 			       sizeof(lun->pending_sense[initidx])));
9334 
9335 		ctl_clear_mask(lun->have_ca, initidx);
9336 		have_error = 1;
9337 	} else
9338 #endif
9339 	if (have_error == 0) {
9340 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9341 		    sense_format);
9342 		if (ua_type != CTL_UA_NONE)
9343 			have_error = 1;
9344 	}
9345 	if (have_error == 0) {
9346 		/*
9347 		 * Report informational exception if have one and allowed.
9348 		 */
9349 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9350 			asc = lun->ie_asc;
9351 			ascq = lun->ie_ascq;
9352 		}
9353 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9354 		    /*current_error*/ 1,
9355 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9356 		    /*asc*/ asc,
9357 		    /*ascq*/ ascq,
9358 		    SSD_ELEM_NONE);
9359 	}
9360 	mtx_unlock(&lun->lun_lock);
9361 
9362 send:
9363 	/*
9364 	 * We report the SCSI status as OK, since the status of the command
9365 	 * itself is OK.  We're reporting sense as parameter data.
9366 	 */
9367 	ctl_set_success(ctsio);
9368 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9369 	ctsio->be_move_done = ctl_config_move_done;
9370 	ctl_datamove((union ctl_io *)ctsio);
9371 	return (CTL_RETVAL_COMPLETE);
9372 }
9373 
9374 int
9375 ctl_tur(struct ctl_scsiio *ctsio)
9376 {
9377 
9378 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9379 
9380 	ctl_set_success(ctsio);
9381 	ctl_done((union ctl_io *)ctsio);
9382 
9383 	return (CTL_RETVAL_COMPLETE);
9384 }
9385 
9386 /*
9387  * SCSI VPD page 0x00, the Supported VPD Pages page.
9388  */
9389 static int
9390 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9391 {
9392 	struct ctl_lun *lun = CTL_LUN(ctsio);
9393 	struct scsi_vpd_supported_pages *pages;
9394 	int sup_page_size;
9395 	int p;
9396 
9397 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9398 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9399 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9400 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9401 	ctsio->kern_sg_entries = 0;
9402 
9403 	if (sup_page_size < alloc_len) {
9404 		ctsio->residual = alloc_len - sup_page_size;
9405 		ctsio->kern_data_len = sup_page_size;
9406 		ctsio->kern_total_len = sup_page_size;
9407 	} else {
9408 		ctsio->residual = 0;
9409 		ctsio->kern_data_len = alloc_len;
9410 		ctsio->kern_total_len = alloc_len;
9411 	}
9412 	ctsio->kern_data_resid = 0;
9413 	ctsio->kern_rel_offset = 0;
9414 	ctsio->kern_sg_entries = 0;
9415 
9416 	/*
9417 	 * The control device is always connected.  The disk device, on the
9418 	 * other hand, may not be online all the time.  Need to change this
9419 	 * to figure out whether the disk device is actually online or not.
9420 	 */
9421 	if (lun != NULL)
9422 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9423 				lun->be_lun->lun_type;
9424 	else
9425 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9426 
9427 	p = 0;
9428 	/* Supported VPD pages */
9429 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9430 	/* Serial Number */
9431 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9432 	/* Device Identification */
9433 	pages->page_list[p++] = SVPD_DEVICE_ID;
9434 	/* Extended INQUIRY Data */
9435 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9436 	/* Mode Page Policy */
9437 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9438 	/* SCSI Ports */
9439 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9440 	/* Third-party Copy */
9441 	pages->page_list[p++] = SVPD_SCSI_TPC;
9442 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9443 		/* Block limits */
9444 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9445 		/* Block Device Characteristics */
9446 		pages->page_list[p++] = SVPD_BDC;
9447 		/* Logical Block Provisioning */
9448 		pages->page_list[p++] = SVPD_LBP;
9449 	}
9450 	pages->length = p;
9451 
9452 	ctl_set_success(ctsio);
9453 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9454 	ctsio->be_move_done = ctl_config_move_done;
9455 	ctl_datamove((union ctl_io *)ctsio);
9456 	return (CTL_RETVAL_COMPLETE);
9457 }
9458 
9459 /*
9460  * SCSI VPD page 0x80, the Unit Serial Number page.
9461  */
9462 static int
9463 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9464 {
9465 	struct ctl_lun *lun = CTL_LUN(ctsio);
9466 	struct scsi_vpd_unit_serial_number *sn_ptr;
9467 	int data_len;
9468 
9469 	data_len = 4 + CTL_SN_LEN;
9470 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9471 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9472 	if (data_len < alloc_len) {
9473 		ctsio->residual = alloc_len - data_len;
9474 		ctsio->kern_data_len = data_len;
9475 		ctsio->kern_total_len = data_len;
9476 	} else {
9477 		ctsio->residual = 0;
9478 		ctsio->kern_data_len = alloc_len;
9479 		ctsio->kern_total_len = alloc_len;
9480 	}
9481 	ctsio->kern_data_resid = 0;
9482 	ctsio->kern_rel_offset = 0;
9483 	ctsio->kern_sg_entries = 0;
9484 
9485 	/*
9486 	 * The control device is always connected.  The disk device, on the
9487 	 * other hand, may not be online all the time.  Need to change this
9488 	 * to figure out whether the disk device is actually online or not.
9489 	 */
9490 	if (lun != NULL)
9491 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9492 				  lun->be_lun->lun_type;
9493 	else
9494 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9495 
9496 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9497 	sn_ptr->length = CTL_SN_LEN;
9498 	/*
9499 	 * If we don't have a LUN, we just leave the serial number as
9500 	 * all spaces.
9501 	 */
9502 	if (lun != NULL) {
9503 		strncpy((char *)sn_ptr->serial_num,
9504 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9505 	} else
9506 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9507 
9508 	ctl_set_success(ctsio);
9509 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9510 	ctsio->be_move_done = ctl_config_move_done;
9511 	ctl_datamove((union ctl_io *)ctsio);
9512 	return (CTL_RETVAL_COMPLETE);
9513 }
9514 
9515 
9516 /*
9517  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9518  */
9519 static int
9520 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9521 {
9522 	struct ctl_lun *lun = CTL_LUN(ctsio);
9523 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9524 	int data_len;
9525 
9526 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9527 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9528 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9529 	ctsio->kern_sg_entries = 0;
9530 
9531 	if (data_len < alloc_len) {
9532 		ctsio->residual = alloc_len - data_len;
9533 		ctsio->kern_data_len = data_len;
9534 		ctsio->kern_total_len = data_len;
9535 	} else {
9536 		ctsio->residual = 0;
9537 		ctsio->kern_data_len = alloc_len;
9538 		ctsio->kern_total_len = alloc_len;
9539 	}
9540 	ctsio->kern_data_resid = 0;
9541 	ctsio->kern_rel_offset = 0;
9542 	ctsio->kern_sg_entries = 0;
9543 
9544 	/*
9545 	 * The control device is always connected.  The disk device, on the
9546 	 * other hand, may not be online all the time.
9547 	 */
9548 	if (lun != NULL)
9549 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9550 				     lun->be_lun->lun_type;
9551 	else
9552 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9553 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9554 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9555 	/*
9556 	 * We support head of queue, ordered and simple tags.
9557 	 */
9558 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9559 	/*
9560 	 * Volatile cache supported.
9561 	 */
9562 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9563 
9564 	/*
9565 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9566 	 * attention for a particular IT nexus on all LUNs once we report
9567 	 * it to that nexus once.  This bit is required as of SPC-4.
9568 	 */
9569 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9570 
9571 	/*
9572 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9573 	 */
9574 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9575 
9576 	/*
9577 	 * XXX KDM in order to correctly answer this, we would need
9578 	 * information from the SIM to determine how much sense data it
9579 	 * can send.  So this would really be a path inquiry field, most
9580 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9581 	 * but the hardware may or may not be able to support that much.
9582 	 * 0 just means that the maximum sense data length is not reported.
9583 	 */
9584 	eid_ptr->max_sense_length = 0;
9585 
9586 	ctl_set_success(ctsio);
9587 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9588 	ctsio->be_move_done = ctl_config_move_done;
9589 	ctl_datamove((union ctl_io *)ctsio);
9590 	return (CTL_RETVAL_COMPLETE);
9591 }
9592 
9593 static int
9594 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9595 {
9596 	struct ctl_lun *lun = CTL_LUN(ctsio);
9597 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9598 	int data_len;
9599 
9600 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9601 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9602 
9603 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9604 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9605 	ctsio->kern_sg_entries = 0;
9606 
9607 	if (data_len < alloc_len) {
9608 		ctsio->residual = alloc_len - data_len;
9609 		ctsio->kern_data_len = data_len;
9610 		ctsio->kern_total_len = data_len;
9611 	} else {
9612 		ctsio->residual = 0;
9613 		ctsio->kern_data_len = alloc_len;
9614 		ctsio->kern_total_len = alloc_len;
9615 	}
9616 	ctsio->kern_data_resid = 0;
9617 	ctsio->kern_rel_offset = 0;
9618 	ctsio->kern_sg_entries = 0;
9619 
9620 	/*
9621 	 * The control device is always connected.  The disk device, on the
9622 	 * other hand, may not be online all the time.
9623 	 */
9624 	if (lun != NULL)
9625 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9626 				     lun->be_lun->lun_type;
9627 	else
9628 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9629 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9630 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9631 	mpp_ptr->descr[0].page_code = 0x3f;
9632 	mpp_ptr->descr[0].subpage_code = 0xff;
9633 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9634 
9635 	ctl_set_success(ctsio);
9636 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9637 	ctsio->be_move_done = ctl_config_move_done;
9638 	ctl_datamove((union ctl_io *)ctsio);
9639 	return (CTL_RETVAL_COMPLETE);
9640 }
9641 
9642 /*
9643  * SCSI VPD page 0x83, the Device Identification page.
9644  */
9645 static int
9646 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9647 {
9648 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9649 	struct ctl_port *port = CTL_PORT(ctsio);
9650 	struct ctl_lun *lun = CTL_LUN(ctsio);
9651 	struct scsi_vpd_device_id *devid_ptr;
9652 	struct scsi_vpd_id_descriptor *desc;
9653 	int data_len, g;
9654 	uint8_t proto;
9655 
9656 	data_len = sizeof(struct scsi_vpd_device_id) +
9657 	    sizeof(struct scsi_vpd_id_descriptor) +
9658 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9659 	    sizeof(struct scsi_vpd_id_descriptor) +
9660 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9661 	if (lun && lun->lun_devid)
9662 		data_len += lun->lun_devid->len;
9663 	if (port && port->port_devid)
9664 		data_len += port->port_devid->len;
9665 	if (port && port->target_devid)
9666 		data_len += port->target_devid->len;
9667 
9668 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9669 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9670 	ctsio->kern_sg_entries = 0;
9671 
9672 	if (data_len < alloc_len) {
9673 		ctsio->residual = alloc_len - data_len;
9674 		ctsio->kern_data_len = data_len;
9675 		ctsio->kern_total_len = data_len;
9676 	} else {
9677 		ctsio->residual = 0;
9678 		ctsio->kern_data_len = alloc_len;
9679 		ctsio->kern_total_len = alloc_len;
9680 	}
9681 	ctsio->kern_data_resid = 0;
9682 	ctsio->kern_rel_offset = 0;
9683 	ctsio->kern_sg_entries = 0;
9684 
9685 	/*
9686 	 * The control device is always connected.  The disk device, on the
9687 	 * other hand, may not be online all the time.
9688 	 */
9689 	if (lun != NULL)
9690 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9691 				     lun->be_lun->lun_type;
9692 	else
9693 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9694 	devid_ptr->page_code = SVPD_DEVICE_ID;
9695 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9696 
9697 	if (port && port->port_type == CTL_PORT_FC)
9698 		proto = SCSI_PROTO_FC << 4;
9699 	else if (port && port->port_type == CTL_PORT_ISCSI)
9700 		proto = SCSI_PROTO_ISCSI << 4;
9701 	else
9702 		proto = SCSI_PROTO_SPI << 4;
9703 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9704 
9705 	/*
9706 	 * We're using a LUN association here.  i.e., this device ID is a
9707 	 * per-LUN identifier.
9708 	 */
9709 	if (lun && lun->lun_devid) {
9710 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9711 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9712 		    lun->lun_devid->len);
9713 	}
9714 
9715 	/*
9716 	 * This is for the WWPN which is a port association.
9717 	 */
9718 	if (port && port->port_devid) {
9719 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9720 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9721 		    port->port_devid->len);
9722 	}
9723 
9724 	/*
9725 	 * This is for the Relative Target Port(type 4h) identifier
9726 	 */
9727 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9728 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9729 	    SVPD_ID_TYPE_RELTARG;
9730 	desc->length = 4;
9731 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9732 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9733 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9734 
9735 	/*
9736 	 * This is for the Target Port Group(type 5h) identifier
9737 	 */
9738 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9739 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9740 	    SVPD_ID_TYPE_TPORTGRP;
9741 	desc->length = 4;
9742 	if (softc->is_single ||
9743 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9744 		g = 1;
9745 	else
9746 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9747 	scsi_ulto2b(g, &desc->identifier[2]);
9748 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9749 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9750 
9751 	/*
9752 	 * This is for the Target identifier
9753 	 */
9754 	if (port && port->target_devid) {
9755 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9756 	}
9757 
9758 	ctl_set_success(ctsio);
9759 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9760 	ctsio->be_move_done = ctl_config_move_done;
9761 	ctl_datamove((union ctl_io *)ctsio);
9762 	return (CTL_RETVAL_COMPLETE);
9763 }
9764 
9765 static int
9766 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9767 {
9768 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9769 	struct ctl_lun *lun = CTL_LUN(ctsio);
9770 	struct scsi_vpd_scsi_ports *sp;
9771 	struct scsi_vpd_port_designation *pd;
9772 	struct scsi_vpd_port_designation_cont *pdc;
9773 	struct ctl_port *port;
9774 	int data_len, num_target_ports, iid_len, id_len;
9775 
9776 	num_target_ports = 0;
9777 	iid_len = 0;
9778 	id_len = 0;
9779 	mtx_lock(&softc->ctl_lock);
9780 	STAILQ_FOREACH(port, &softc->port_list, links) {
9781 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9782 			continue;
9783 		if (lun != NULL &&
9784 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9785 			continue;
9786 		num_target_ports++;
9787 		if (port->init_devid)
9788 			iid_len += port->init_devid->len;
9789 		if (port->port_devid)
9790 			id_len += port->port_devid->len;
9791 	}
9792 	mtx_unlock(&softc->ctl_lock);
9793 
9794 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9795 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9796 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9797 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9798 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9799 	ctsio->kern_sg_entries = 0;
9800 
9801 	if (data_len < alloc_len) {
9802 		ctsio->residual = alloc_len - data_len;
9803 		ctsio->kern_data_len = data_len;
9804 		ctsio->kern_total_len = data_len;
9805 	} else {
9806 		ctsio->residual = 0;
9807 		ctsio->kern_data_len = alloc_len;
9808 		ctsio->kern_total_len = alloc_len;
9809 	}
9810 	ctsio->kern_data_resid = 0;
9811 	ctsio->kern_rel_offset = 0;
9812 	ctsio->kern_sg_entries = 0;
9813 
9814 	/*
9815 	 * The control device is always connected.  The disk device, on the
9816 	 * other hand, may not be online all the time.  Need to change this
9817 	 * to figure out whether the disk device is actually online or not.
9818 	 */
9819 	if (lun != NULL)
9820 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9821 				  lun->be_lun->lun_type;
9822 	else
9823 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9824 
9825 	sp->page_code = SVPD_SCSI_PORTS;
9826 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9827 	    sp->page_length);
9828 	pd = &sp->design[0];
9829 
9830 	mtx_lock(&softc->ctl_lock);
9831 	STAILQ_FOREACH(port, &softc->port_list, links) {
9832 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9833 			continue;
9834 		if (lun != NULL &&
9835 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9836 			continue;
9837 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9838 		if (port->init_devid) {
9839 			iid_len = port->init_devid->len;
9840 			memcpy(pd->initiator_transportid,
9841 			    port->init_devid->data, port->init_devid->len);
9842 		} else
9843 			iid_len = 0;
9844 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9845 		pdc = (struct scsi_vpd_port_designation_cont *)
9846 		    (&pd->initiator_transportid[iid_len]);
9847 		if (port->port_devid) {
9848 			id_len = port->port_devid->len;
9849 			memcpy(pdc->target_port_descriptors,
9850 			    port->port_devid->data, port->port_devid->len);
9851 		} else
9852 			id_len = 0;
9853 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9854 		pd = (struct scsi_vpd_port_designation *)
9855 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9856 	}
9857 	mtx_unlock(&softc->ctl_lock);
9858 
9859 	ctl_set_success(ctsio);
9860 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9861 	ctsio->be_move_done = ctl_config_move_done;
9862 	ctl_datamove((union ctl_io *)ctsio);
9863 	return (CTL_RETVAL_COMPLETE);
9864 }
9865 
9866 static int
9867 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9868 {
9869 	struct ctl_lun *lun = CTL_LUN(ctsio);
9870 	struct scsi_vpd_block_limits *bl_ptr;
9871 	uint64_t ival;
9872 
9873 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9874 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9875 	ctsio->kern_sg_entries = 0;
9876 
9877 	if (sizeof(*bl_ptr) < alloc_len) {
9878 		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9879 		ctsio->kern_data_len = sizeof(*bl_ptr);
9880 		ctsio->kern_total_len = sizeof(*bl_ptr);
9881 	} else {
9882 		ctsio->residual = 0;
9883 		ctsio->kern_data_len = alloc_len;
9884 		ctsio->kern_total_len = alloc_len;
9885 	}
9886 	ctsio->kern_data_resid = 0;
9887 	ctsio->kern_rel_offset = 0;
9888 	ctsio->kern_sg_entries = 0;
9889 
9890 	/*
9891 	 * The control device is always connected.  The disk device, on the
9892 	 * other hand, may not be online all the time.  Need to change this
9893 	 * to figure out whether the disk device is actually online or not.
9894 	 */
9895 	if (lun != NULL)
9896 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9897 				  lun->be_lun->lun_type;
9898 	else
9899 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9900 
9901 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9902 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9903 	bl_ptr->max_cmp_write_len = 0xff;
9904 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9905 	if (lun != NULL) {
9906 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9907 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9908 			ival = 0xffffffff;
9909 			ctl_get_opt_number(&lun->be_lun->options,
9910 			    "unmap_max_lba", &ival);
9911 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9912 			ival = 0xffffffff;
9913 			ctl_get_opt_number(&lun->be_lun->options,
9914 			    "unmap_max_descr", &ival);
9915 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9916 			if (lun->be_lun->ublockexp != 0) {
9917 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9918 				    bl_ptr->opt_unmap_grain);
9919 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9920 				    bl_ptr->unmap_grain_align);
9921 			}
9922 		}
9923 		scsi_ulto4b(lun->be_lun->atomicblock,
9924 		    bl_ptr->max_atomic_transfer_length);
9925 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9926 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9927 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9928 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9929 		ival = UINT64_MAX;
9930 		ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9931 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9932 	}
9933 
9934 	ctl_set_success(ctsio);
9935 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9936 	ctsio->be_move_done = ctl_config_move_done;
9937 	ctl_datamove((union ctl_io *)ctsio);
9938 	return (CTL_RETVAL_COMPLETE);
9939 }
9940 
9941 static int
9942 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9943 {
9944 	struct ctl_lun *lun = CTL_LUN(ctsio);
9945 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9946 	const char *value;
9947 	u_int i;
9948 
9949 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9950 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9951 	ctsio->kern_sg_entries = 0;
9952 
9953 	if (sizeof(*bdc_ptr) < alloc_len) {
9954 		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9955 		ctsio->kern_data_len = sizeof(*bdc_ptr);
9956 		ctsio->kern_total_len = sizeof(*bdc_ptr);
9957 	} else {
9958 		ctsio->residual = 0;
9959 		ctsio->kern_data_len = alloc_len;
9960 		ctsio->kern_total_len = alloc_len;
9961 	}
9962 	ctsio->kern_data_resid = 0;
9963 	ctsio->kern_rel_offset = 0;
9964 	ctsio->kern_sg_entries = 0;
9965 
9966 	/*
9967 	 * The control device is always connected.  The disk device, on the
9968 	 * other hand, may not be online all the time.  Need to change this
9969 	 * to figure out whether the disk device is actually online or not.
9970 	 */
9971 	if (lun != NULL)
9972 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9973 				  lun->be_lun->lun_type;
9974 	else
9975 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9976 	bdc_ptr->page_code = SVPD_BDC;
9977 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9978 	if (lun != NULL &&
9979 	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9980 		i = strtol(value, NULL, 0);
9981 	else
9982 		i = CTL_DEFAULT_ROTATION_RATE;
9983 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9984 	if (lun != NULL &&
9985 	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9986 		i = strtol(value, NULL, 0);
9987 	else
9988 		i = 0;
9989 	bdc_ptr->wab_wac_ff = (i & 0x0f);
9990 	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9991 
9992 	ctl_set_success(ctsio);
9993 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9994 	ctsio->be_move_done = ctl_config_move_done;
9995 	ctl_datamove((union ctl_io *)ctsio);
9996 	return (CTL_RETVAL_COMPLETE);
9997 }
9998 
9999 static int
10000 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10001 {
10002 	struct ctl_lun *lun = CTL_LUN(ctsio);
10003 	struct scsi_vpd_logical_block_prov *lbp_ptr;
10004 	const char *value;
10005 
10006 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10007 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10008 	ctsio->kern_sg_entries = 0;
10009 
10010 	if (sizeof(*lbp_ptr) < alloc_len) {
10011 		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10012 		ctsio->kern_data_len = sizeof(*lbp_ptr);
10013 		ctsio->kern_total_len = sizeof(*lbp_ptr);
10014 	} else {
10015 		ctsio->residual = 0;
10016 		ctsio->kern_data_len = alloc_len;
10017 		ctsio->kern_total_len = alloc_len;
10018 	}
10019 	ctsio->kern_data_resid = 0;
10020 	ctsio->kern_rel_offset = 0;
10021 	ctsio->kern_sg_entries = 0;
10022 
10023 	/*
10024 	 * The control device is always connected.  The disk device, on the
10025 	 * other hand, may not be online all the time.  Need to change this
10026 	 * to figure out whether the disk device is actually online or not.
10027 	 */
10028 	if (lun != NULL)
10029 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10030 				  lun->be_lun->lun_type;
10031 	else
10032 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10033 
10034 	lbp_ptr->page_code = SVPD_LBP;
10035 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10036 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
10037 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10038 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10039 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10040 		value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
10041 		if (value != NULL) {
10042 			if (strcmp(value, "resource") == 0)
10043 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10044 			else if (strcmp(value, "thin") == 0)
10045 				lbp_ptr->prov_type = SVPD_LBP_THIN;
10046 		} else
10047 			lbp_ptr->prov_type = SVPD_LBP_THIN;
10048 	}
10049 
10050 	ctl_set_success(ctsio);
10051 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10052 	ctsio->be_move_done = ctl_config_move_done;
10053 	ctl_datamove((union ctl_io *)ctsio);
10054 	return (CTL_RETVAL_COMPLETE);
10055 }
10056 
10057 /*
10058  * INQUIRY with the EVPD bit set.
10059  */
10060 static int
10061 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10062 {
10063 	struct ctl_lun *lun = CTL_LUN(ctsio);
10064 	struct scsi_inquiry *cdb;
10065 	int alloc_len, retval;
10066 
10067 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10068 	alloc_len = scsi_2btoul(cdb->length);
10069 
10070 	switch (cdb->page_code) {
10071 	case SVPD_SUPPORTED_PAGES:
10072 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10073 		break;
10074 	case SVPD_UNIT_SERIAL_NUMBER:
10075 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10076 		break;
10077 	case SVPD_DEVICE_ID:
10078 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10079 		break;
10080 	case SVPD_EXTENDED_INQUIRY_DATA:
10081 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10082 		break;
10083 	case SVPD_MODE_PAGE_POLICY:
10084 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10085 		break;
10086 	case SVPD_SCSI_PORTS:
10087 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10088 		break;
10089 	case SVPD_SCSI_TPC:
10090 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10091 		break;
10092 	case SVPD_BLOCK_LIMITS:
10093 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10094 			goto err;
10095 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10096 		break;
10097 	case SVPD_BDC:
10098 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10099 			goto err;
10100 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10101 		break;
10102 	case SVPD_LBP:
10103 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10104 			goto err;
10105 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10106 		break;
10107 	default:
10108 err:
10109 		ctl_set_invalid_field(ctsio,
10110 				      /*sks_valid*/ 1,
10111 				      /*command*/ 1,
10112 				      /*field*/ 2,
10113 				      /*bit_valid*/ 0,
10114 				      /*bit*/ 0);
10115 		ctl_done((union ctl_io *)ctsio);
10116 		retval = CTL_RETVAL_COMPLETE;
10117 		break;
10118 	}
10119 
10120 	return (retval);
10121 }
10122 
10123 /*
10124  * Standard INQUIRY data.
10125  */
10126 static int
10127 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10128 {
10129 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
10130 	struct ctl_port *port = CTL_PORT(ctsio);
10131 	struct ctl_lun *lun = CTL_LUN(ctsio);
10132 	struct scsi_inquiry_data *inq_ptr;
10133 	struct scsi_inquiry *cdb;
10134 	char *val;
10135 	uint32_t alloc_len, data_len;
10136 	ctl_port_type port_type;
10137 
10138 	port_type = port->port_type;
10139 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10140 		port_type = CTL_PORT_SCSI;
10141 
10142 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10143 	alloc_len = scsi_2btoul(cdb->length);
10144 
10145 	/*
10146 	 * We malloc the full inquiry data size here and fill it
10147 	 * in.  If the user only asks for less, we'll give him
10148 	 * that much.
10149 	 */
10150 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10151 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10152 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10153 	ctsio->kern_sg_entries = 0;
10154 	ctsio->kern_data_resid = 0;
10155 	ctsio->kern_rel_offset = 0;
10156 
10157 	if (data_len < alloc_len) {
10158 		ctsio->residual = alloc_len - data_len;
10159 		ctsio->kern_data_len = data_len;
10160 		ctsio->kern_total_len = data_len;
10161 	} else {
10162 		ctsio->residual = 0;
10163 		ctsio->kern_data_len = alloc_len;
10164 		ctsio->kern_total_len = alloc_len;
10165 	}
10166 
10167 	if (lun != NULL) {
10168 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10169 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10170 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10171 			    lun->be_lun->lun_type;
10172 		} else {
10173 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10174 			    lun->be_lun->lun_type;
10175 		}
10176 		if (lun->flags & CTL_LUN_REMOVABLE)
10177 			inq_ptr->dev_qual2 |= SID_RMB;
10178 	} else
10179 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10180 
10181 	/* RMB in byte 2 is 0 */
10182 	inq_ptr->version = SCSI_REV_SPC5;
10183 
10184 	/*
10185 	 * According to SAM-3, even if a device only supports a single
10186 	 * level of LUN addressing, it should still set the HISUP bit:
10187 	 *
10188 	 * 4.9.1 Logical unit numbers overview
10189 	 *
10190 	 * All logical unit number formats described in this standard are
10191 	 * hierarchical in structure even when only a single level in that
10192 	 * hierarchy is used. The HISUP bit shall be set to one in the
10193 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10194 	 * format described in this standard is used.  Non-hierarchical
10195 	 * formats are outside the scope of this standard.
10196 	 *
10197 	 * Therefore we set the HiSup bit here.
10198 	 *
10199 	 * The response format is 2, per SPC-3.
10200 	 */
10201 	inq_ptr->response_format = SID_HiSup | 2;
10202 
10203 	inq_ptr->additional_length = data_len -
10204 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10205 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10206 			 inq_ptr->additional_length));
10207 
10208 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10209 	if (port_type == CTL_PORT_SCSI)
10210 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10211 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10212 	inq_ptr->flags = SID_CmdQue;
10213 	if (port_type == CTL_PORT_SCSI)
10214 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10215 
10216 	/*
10217 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10218 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10219 	 * name and 4 bytes for the revision.
10220 	 */
10221 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10222 	    "vendor")) == NULL) {
10223 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10224 	} else {
10225 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10226 		strncpy(inq_ptr->vendor, val,
10227 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10228 	}
10229 	if (lun == NULL) {
10230 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10231 		    sizeof(inq_ptr->product));
10232 	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10233 		switch (lun->be_lun->lun_type) {
10234 		case T_DIRECT:
10235 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10236 			    sizeof(inq_ptr->product));
10237 			break;
10238 		case T_PROCESSOR:
10239 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10240 			    sizeof(inq_ptr->product));
10241 			break;
10242 		case T_CDROM:
10243 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10244 			    sizeof(inq_ptr->product));
10245 			break;
10246 		default:
10247 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10248 			    sizeof(inq_ptr->product));
10249 			break;
10250 		}
10251 	} else {
10252 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10253 		strncpy(inq_ptr->product, val,
10254 		    min(sizeof(inq_ptr->product), strlen(val)));
10255 	}
10256 
10257 	/*
10258 	 * XXX make this a macro somewhere so it automatically gets
10259 	 * incremented when we make changes.
10260 	 */
10261 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10262 	    "revision")) == NULL) {
10263 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10264 	} else {
10265 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10266 		strncpy(inq_ptr->revision, val,
10267 		    min(sizeof(inq_ptr->revision), strlen(val)));
10268 	}
10269 
10270 	/*
10271 	 * For parallel SCSI, we support double transition and single
10272 	 * transition clocking.  We also support QAS (Quick Arbitration
10273 	 * and Selection) and Information Unit transfers on both the
10274 	 * control and array devices.
10275 	 */
10276 	if (port_type == CTL_PORT_SCSI)
10277 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10278 				    SID_SPI_IUS;
10279 
10280 	/* SAM-6 (no version claimed) */
10281 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10282 	/* SPC-5 (no version claimed) */
10283 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10284 	if (port_type == CTL_PORT_FC) {
10285 		/* FCP-2 ANSI INCITS.350:2003 */
10286 		scsi_ulto2b(0x0917, inq_ptr->version3);
10287 	} else if (port_type == CTL_PORT_SCSI) {
10288 		/* SPI-4 ANSI INCITS.362:200x */
10289 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10290 	} else if (port_type == CTL_PORT_ISCSI) {
10291 		/* iSCSI (no version claimed) */
10292 		scsi_ulto2b(0x0960, inq_ptr->version3);
10293 	} else if (port_type == CTL_PORT_SAS) {
10294 		/* SAS (no version claimed) */
10295 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10296 	}
10297 
10298 	if (lun == NULL) {
10299 		/* SBC-4 (no version claimed) */
10300 		scsi_ulto2b(0x0600, inq_ptr->version4);
10301 	} else {
10302 		switch (lun->be_lun->lun_type) {
10303 		case T_DIRECT:
10304 			/* SBC-4 (no version claimed) */
10305 			scsi_ulto2b(0x0600, inq_ptr->version4);
10306 			break;
10307 		case T_PROCESSOR:
10308 			break;
10309 		case T_CDROM:
10310 			/* MMC-6 (no version claimed) */
10311 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10312 			break;
10313 		default:
10314 			break;
10315 		}
10316 	}
10317 
10318 	ctl_set_success(ctsio);
10319 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10320 	ctsio->be_move_done = ctl_config_move_done;
10321 	ctl_datamove((union ctl_io *)ctsio);
10322 	return (CTL_RETVAL_COMPLETE);
10323 }
10324 
10325 int
10326 ctl_inquiry(struct ctl_scsiio *ctsio)
10327 {
10328 	struct scsi_inquiry *cdb;
10329 	int retval;
10330 
10331 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10332 
10333 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10334 	if (cdb->byte2 & SI_EVPD)
10335 		retval = ctl_inquiry_evpd(ctsio);
10336 	else if (cdb->page_code == 0)
10337 		retval = ctl_inquiry_std(ctsio);
10338 	else {
10339 		ctl_set_invalid_field(ctsio,
10340 				      /*sks_valid*/ 1,
10341 				      /*command*/ 1,
10342 				      /*field*/ 2,
10343 				      /*bit_valid*/ 0,
10344 				      /*bit*/ 0);
10345 		ctl_done((union ctl_io *)ctsio);
10346 		return (CTL_RETVAL_COMPLETE);
10347 	}
10348 
10349 	return (retval);
10350 }
10351 
10352 int
10353 ctl_get_config(struct ctl_scsiio *ctsio)
10354 {
10355 	struct ctl_lun *lun = CTL_LUN(ctsio);
10356 	struct scsi_get_config_header *hdr;
10357 	struct scsi_get_config_feature *feature;
10358 	struct scsi_get_config *cdb;
10359 	uint32_t alloc_len, data_len;
10360 	int rt, starting;
10361 
10362 	cdb = (struct scsi_get_config *)ctsio->cdb;
10363 	rt = (cdb->rt & SGC_RT_MASK);
10364 	starting = scsi_2btoul(cdb->starting_feature);
10365 	alloc_len = scsi_2btoul(cdb->length);
10366 
10367 	data_len = sizeof(struct scsi_get_config_header) +
10368 	    sizeof(struct scsi_get_config_feature) + 8 +
10369 	    sizeof(struct scsi_get_config_feature) + 8 +
10370 	    sizeof(struct scsi_get_config_feature) + 4 +
10371 	    sizeof(struct scsi_get_config_feature) + 4 +
10372 	    sizeof(struct scsi_get_config_feature) + 8 +
10373 	    sizeof(struct scsi_get_config_feature) +
10374 	    sizeof(struct scsi_get_config_feature) + 4 +
10375 	    sizeof(struct scsi_get_config_feature) + 4 +
10376 	    sizeof(struct scsi_get_config_feature) + 4 +
10377 	    sizeof(struct scsi_get_config_feature) + 4 +
10378 	    sizeof(struct scsi_get_config_feature) + 4 +
10379 	    sizeof(struct scsi_get_config_feature) + 4;
10380 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10381 	ctsio->kern_sg_entries = 0;
10382 	ctsio->kern_data_resid = 0;
10383 	ctsio->kern_rel_offset = 0;
10384 
10385 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10386 	if (lun->flags & CTL_LUN_NO_MEDIA)
10387 		scsi_ulto2b(0x0000, hdr->current_profile);
10388 	else
10389 		scsi_ulto2b(0x0010, hdr->current_profile);
10390 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10391 
10392 	if (starting > 0x003b)
10393 		goto done;
10394 	if (starting > 0x003a)
10395 		goto f3b;
10396 	if (starting > 0x002b)
10397 		goto f3a;
10398 	if (starting > 0x002a)
10399 		goto f2b;
10400 	if (starting > 0x001f)
10401 		goto f2a;
10402 	if (starting > 0x001e)
10403 		goto f1f;
10404 	if (starting > 0x001d)
10405 		goto f1e;
10406 	if (starting > 0x0010)
10407 		goto f1d;
10408 	if (starting > 0x0003)
10409 		goto f10;
10410 	if (starting > 0x0002)
10411 		goto f3;
10412 	if (starting > 0x0001)
10413 		goto f2;
10414 	if (starting > 0x0000)
10415 		goto f1;
10416 
10417 	/* Profile List */
10418 	scsi_ulto2b(0x0000, feature->feature_code);
10419 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10420 	feature->add_length = 8;
10421 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10422 	feature->feature_data[2] = 0x00;
10423 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10424 	feature->feature_data[6] = 0x01;
10425 	feature = (struct scsi_get_config_feature *)
10426 	    &feature->feature_data[feature->add_length];
10427 
10428 f1:	/* Core */
10429 	scsi_ulto2b(0x0001, feature->feature_code);
10430 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10431 	feature->add_length = 8;
10432 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10433 	feature->feature_data[4] = 0x03;
10434 	feature = (struct scsi_get_config_feature *)
10435 	    &feature->feature_data[feature->add_length];
10436 
10437 f2:	/* Morphing */
10438 	scsi_ulto2b(0x0002, feature->feature_code);
10439 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10440 	feature->add_length = 4;
10441 	feature->feature_data[0] = 0x02;
10442 	feature = (struct scsi_get_config_feature *)
10443 	    &feature->feature_data[feature->add_length];
10444 
10445 f3:	/* Removable Medium */
10446 	scsi_ulto2b(0x0003, feature->feature_code);
10447 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10448 	feature->add_length = 4;
10449 	feature->feature_data[0] = 0x39;
10450 	feature = (struct scsi_get_config_feature *)
10451 	    &feature->feature_data[feature->add_length];
10452 
10453 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10454 		goto done;
10455 
10456 f10:	/* Random Read */
10457 	scsi_ulto2b(0x0010, feature->feature_code);
10458 	feature->flags = 0x00;
10459 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10460 		feature->flags |= SGC_F_CURRENT;
10461 	feature->add_length = 8;
10462 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10463 	scsi_ulto2b(1, &feature->feature_data[4]);
10464 	feature->feature_data[6] = 0x00;
10465 	feature = (struct scsi_get_config_feature *)
10466 	    &feature->feature_data[feature->add_length];
10467 
10468 f1d:	/* Multi-Read */
10469 	scsi_ulto2b(0x001D, feature->feature_code);
10470 	feature->flags = 0x00;
10471 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10472 		feature->flags |= SGC_F_CURRENT;
10473 	feature->add_length = 0;
10474 	feature = (struct scsi_get_config_feature *)
10475 	    &feature->feature_data[feature->add_length];
10476 
10477 f1e:	/* CD Read */
10478 	scsi_ulto2b(0x001E, feature->feature_code);
10479 	feature->flags = 0x00;
10480 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10481 		feature->flags |= SGC_F_CURRENT;
10482 	feature->add_length = 4;
10483 	feature->feature_data[0] = 0x00;
10484 	feature = (struct scsi_get_config_feature *)
10485 	    &feature->feature_data[feature->add_length];
10486 
10487 f1f:	/* DVD Read */
10488 	scsi_ulto2b(0x001F, feature->feature_code);
10489 	feature->flags = 0x08;
10490 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10491 		feature->flags |= SGC_F_CURRENT;
10492 	feature->add_length = 4;
10493 	feature->feature_data[0] = 0x01;
10494 	feature->feature_data[2] = 0x03;
10495 	feature = (struct scsi_get_config_feature *)
10496 	    &feature->feature_data[feature->add_length];
10497 
10498 f2a:	/* DVD+RW */
10499 	scsi_ulto2b(0x002A, feature->feature_code);
10500 	feature->flags = 0x04;
10501 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10502 		feature->flags |= SGC_F_CURRENT;
10503 	feature->add_length = 4;
10504 	feature->feature_data[0] = 0x00;
10505 	feature->feature_data[1] = 0x00;
10506 	feature = (struct scsi_get_config_feature *)
10507 	    &feature->feature_data[feature->add_length];
10508 
10509 f2b:	/* DVD+R */
10510 	scsi_ulto2b(0x002B, feature->feature_code);
10511 	feature->flags = 0x00;
10512 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10513 		feature->flags |= SGC_F_CURRENT;
10514 	feature->add_length = 4;
10515 	feature->feature_data[0] = 0x00;
10516 	feature = (struct scsi_get_config_feature *)
10517 	    &feature->feature_data[feature->add_length];
10518 
10519 f3a:	/* DVD+RW Dual Layer */
10520 	scsi_ulto2b(0x003A, feature->feature_code);
10521 	feature->flags = 0x00;
10522 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10523 		feature->flags |= SGC_F_CURRENT;
10524 	feature->add_length = 4;
10525 	feature->feature_data[0] = 0x00;
10526 	feature->feature_data[1] = 0x00;
10527 	feature = (struct scsi_get_config_feature *)
10528 	    &feature->feature_data[feature->add_length];
10529 
10530 f3b:	/* DVD+R Dual Layer */
10531 	scsi_ulto2b(0x003B, feature->feature_code);
10532 	feature->flags = 0x00;
10533 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10534 		feature->flags |= SGC_F_CURRENT;
10535 	feature->add_length = 4;
10536 	feature->feature_data[0] = 0x00;
10537 	feature = (struct scsi_get_config_feature *)
10538 	    &feature->feature_data[feature->add_length];
10539 
10540 done:
10541 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10542 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10543 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10544 		if (scsi_2btoul(feature->feature_code) == starting)
10545 			feature = (struct scsi_get_config_feature *)
10546 			    &feature->feature_data[feature->add_length];
10547 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10548 	}
10549 	scsi_ulto4b(data_len - 4, hdr->data_length);
10550 	if (data_len < alloc_len) {
10551 		ctsio->residual = alloc_len - data_len;
10552 		ctsio->kern_data_len = data_len;
10553 		ctsio->kern_total_len = data_len;
10554 	} else {
10555 		ctsio->residual = 0;
10556 		ctsio->kern_data_len = alloc_len;
10557 		ctsio->kern_total_len = alloc_len;
10558 	}
10559 
10560 	ctl_set_success(ctsio);
10561 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10562 	ctsio->be_move_done = ctl_config_move_done;
10563 	ctl_datamove((union ctl_io *)ctsio);
10564 	return (CTL_RETVAL_COMPLETE);
10565 }
10566 
10567 int
10568 ctl_get_event_status(struct ctl_scsiio *ctsio)
10569 {
10570 	struct scsi_get_event_status_header *hdr;
10571 	struct scsi_get_event_status *cdb;
10572 	uint32_t alloc_len, data_len;
10573 	int notif_class;
10574 
10575 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10576 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10577 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10578 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10579 		ctl_done((union ctl_io *)ctsio);
10580 		return (CTL_RETVAL_COMPLETE);
10581 	}
10582 	notif_class = cdb->notif_class;
10583 	alloc_len = scsi_2btoul(cdb->length);
10584 
10585 	data_len = sizeof(struct scsi_get_event_status_header);
10586 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10587 	ctsio->kern_sg_entries = 0;
10588 	ctsio->kern_data_resid = 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_get_event_status_header *)ctsio->kern_data_ptr;
10602 	scsi_ulto2b(0, hdr->descr_length);
10603 	hdr->nea_class = SGESN_NEA;
10604 	hdr->supported_class = 0;
10605 
10606 	ctl_set_success(ctsio);
10607 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10608 	ctsio->be_move_done = ctl_config_move_done;
10609 	ctl_datamove((union ctl_io *)ctsio);
10610 	return (CTL_RETVAL_COMPLETE);
10611 }
10612 
10613 int
10614 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10615 {
10616 	struct scsi_mechanism_status_header *hdr;
10617 	struct scsi_mechanism_status *cdb;
10618 	uint32_t alloc_len, data_len;
10619 
10620 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10621 	alloc_len = scsi_2btoul(cdb->length);
10622 
10623 	data_len = sizeof(struct scsi_mechanism_status_header);
10624 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10625 	ctsio->kern_sg_entries = 0;
10626 	ctsio->kern_data_resid = 0;
10627 	ctsio->kern_rel_offset = 0;
10628 
10629 	if (data_len < alloc_len) {
10630 		ctsio->residual = alloc_len - data_len;
10631 		ctsio->kern_data_len = data_len;
10632 		ctsio->kern_total_len = data_len;
10633 	} else {
10634 		ctsio->residual = 0;
10635 		ctsio->kern_data_len = alloc_len;
10636 		ctsio->kern_total_len = alloc_len;
10637 	}
10638 
10639 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10640 	hdr->state1 = 0x00;
10641 	hdr->state2 = 0xe0;
10642 	scsi_ulto3b(0, hdr->lba);
10643 	hdr->slots_num = 0;
10644 	scsi_ulto2b(0, hdr->slots_length);
10645 
10646 	ctl_set_success(ctsio);
10647 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10648 	ctsio->be_move_done = ctl_config_move_done;
10649 	ctl_datamove((union ctl_io *)ctsio);
10650 	return (CTL_RETVAL_COMPLETE);
10651 }
10652 
10653 static void
10654 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10655 {
10656 
10657 	lba += 150;
10658 	buf[0] = 0;
10659 	buf[1] = bin2bcd((lba / 75) / 60);
10660 	buf[2] = bin2bcd((lba / 75) % 60);
10661 	buf[3] = bin2bcd(lba % 75);
10662 }
10663 
10664 int
10665 ctl_read_toc(struct ctl_scsiio *ctsio)
10666 {
10667 	struct ctl_lun *lun = CTL_LUN(ctsio);
10668 	struct scsi_read_toc_hdr *hdr;
10669 	struct scsi_read_toc_type01_descr *descr;
10670 	struct scsi_read_toc *cdb;
10671 	uint32_t alloc_len, data_len;
10672 	int format, msf;
10673 
10674 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10675 	msf = (cdb->byte2 & CD_MSF) != 0;
10676 	format = cdb->format;
10677 	alloc_len = scsi_2btoul(cdb->data_len);
10678 
10679 	data_len = sizeof(struct scsi_read_toc_hdr);
10680 	if (format == 0)
10681 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10682 	else
10683 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10684 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10685 	ctsio->kern_sg_entries = 0;
10686 	ctsio->kern_data_resid = 0;
10687 	ctsio->kern_rel_offset = 0;
10688 
10689 	if (data_len < alloc_len) {
10690 		ctsio->residual = alloc_len - data_len;
10691 		ctsio->kern_data_len = data_len;
10692 		ctsio->kern_total_len = data_len;
10693 	} else {
10694 		ctsio->residual = 0;
10695 		ctsio->kern_data_len = alloc_len;
10696 		ctsio->kern_total_len = alloc_len;
10697 	}
10698 
10699 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10700 	if (format == 0) {
10701 		scsi_ulto2b(0x12, hdr->data_length);
10702 		hdr->first = 1;
10703 		hdr->last = 1;
10704 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10705 		descr->addr_ctl = 0x14;
10706 		descr->track_number = 1;
10707 		if (msf)
10708 			ctl_ultomsf(0, descr->track_start);
10709 		else
10710 			scsi_ulto4b(0, descr->track_start);
10711 		descr++;
10712 		descr->addr_ctl = 0x14;
10713 		descr->track_number = 0xaa;
10714 		if (msf)
10715 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10716 		else
10717 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10718 	} else {
10719 		scsi_ulto2b(0x0a, hdr->data_length);
10720 		hdr->first = 1;
10721 		hdr->last = 1;
10722 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10723 		descr->addr_ctl = 0x14;
10724 		descr->track_number = 1;
10725 		if (msf)
10726 			ctl_ultomsf(0, descr->track_start);
10727 		else
10728 			scsi_ulto4b(0, descr->track_start);
10729 	}
10730 
10731 	ctl_set_success(ctsio);
10732 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10733 	ctsio->be_move_done = ctl_config_move_done;
10734 	ctl_datamove((union ctl_io *)ctsio);
10735 	return (CTL_RETVAL_COMPLETE);
10736 }
10737 
10738 /*
10739  * For known CDB types, parse the LBA and length.
10740  */
10741 static int
10742 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10743 {
10744 	if (io->io_hdr.io_type != CTL_IO_SCSI)
10745 		return (1);
10746 
10747 	switch (io->scsiio.cdb[0]) {
10748 	case COMPARE_AND_WRITE: {
10749 		struct scsi_compare_and_write *cdb;
10750 
10751 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10752 
10753 		*lba = scsi_8btou64(cdb->addr);
10754 		*len = cdb->length;
10755 		break;
10756 	}
10757 	case READ_6:
10758 	case WRITE_6: {
10759 		struct scsi_rw_6 *cdb;
10760 
10761 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10762 
10763 		*lba = scsi_3btoul(cdb->addr);
10764 		/* only 5 bits are valid in the most significant address byte */
10765 		*lba &= 0x1fffff;
10766 		*len = cdb->length;
10767 		break;
10768 	}
10769 	case READ_10:
10770 	case WRITE_10: {
10771 		struct scsi_rw_10 *cdb;
10772 
10773 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10774 
10775 		*lba = scsi_4btoul(cdb->addr);
10776 		*len = scsi_2btoul(cdb->length);
10777 		break;
10778 	}
10779 	case WRITE_VERIFY_10: {
10780 		struct scsi_write_verify_10 *cdb;
10781 
10782 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10783 
10784 		*lba = scsi_4btoul(cdb->addr);
10785 		*len = scsi_2btoul(cdb->length);
10786 		break;
10787 	}
10788 	case READ_12:
10789 	case WRITE_12: {
10790 		struct scsi_rw_12 *cdb;
10791 
10792 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10793 
10794 		*lba = scsi_4btoul(cdb->addr);
10795 		*len = scsi_4btoul(cdb->length);
10796 		break;
10797 	}
10798 	case WRITE_VERIFY_12: {
10799 		struct scsi_write_verify_12 *cdb;
10800 
10801 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10802 
10803 		*lba = scsi_4btoul(cdb->addr);
10804 		*len = scsi_4btoul(cdb->length);
10805 		break;
10806 	}
10807 	case READ_16:
10808 	case WRITE_16: {
10809 		struct scsi_rw_16 *cdb;
10810 
10811 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10812 
10813 		*lba = scsi_8btou64(cdb->addr);
10814 		*len = scsi_4btoul(cdb->length);
10815 		break;
10816 	}
10817 	case WRITE_ATOMIC_16: {
10818 		struct scsi_write_atomic_16 *cdb;
10819 
10820 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10821 
10822 		*lba = scsi_8btou64(cdb->addr);
10823 		*len = scsi_2btoul(cdb->length);
10824 		break;
10825 	}
10826 	case WRITE_VERIFY_16: {
10827 		struct scsi_write_verify_16 *cdb;
10828 
10829 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10830 
10831 		*lba = scsi_8btou64(cdb->addr);
10832 		*len = scsi_4btoul(cdb->length);
10833 		break;
10834 	}
10835 	case WRITE_SAME_10: {
10836 		struct scsi_write_same_10 *cdb;
10837 
10838 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10839 
10840 		*lba = scsi_4btoul(cdb->addr);
10841 		*len = scsi_2btoul(cdb->length);
10842 		break;
10843 	}
10844 	case WRITE_SAME_16: {
10845 		struct scsi_write_same_16 *cdb;
10846 
10847 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10848 
10849 		*lba = scsi_8btou64(cdb->addr);
10850 		*len = scsi_4btoul(cdb->length);
10851 		break;
10852 	}
10853 	case VERIFY_10: {
10854 		struct scsi_verify_10 *cdb;
10855 
10856 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10857 
10858 		*lba = scsi_4btoul(cdb->addr);
10859 		*len = scsi_2btoul(cdb->length);
10860 		break;
10861 	}
10862 	case VERIFY_12: {
10863 		struct scsi_verify_12 *cdb;
10864 
10865 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10866 
10867 		*lba = scsi_4btoul(cdb->addr);
10868 		*len = scsi_4btoul(cdb->length);
10869 		break;
10870 	}
10871 	case VERIFY_16: {
10872 		struct scsi_verify_16 *cdb;
10873 
10874 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10875 
10876 		*lba = scsi_8btou64(cdb->addr);
10877 		*len = scsi_4btoul(cdb->length);
10878 		break;
10879 	}
10880 	case UNMAP: {
10881 		*lba = 0;
10882 		*len = UINT64_MAX;
10883 		break;
10884 	}
10885 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10886 		struct scsi_get_lba_status *cdb;
10887 
10888 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10889 		*lba = scsi_8btou64(cdb->addr);
10890 		*len = UINT32_MAX;
10891 		break;
10892 	}
10893 	default:
10894 		return (1);
10895 		break; /* NOTREACHED */
10896 	}
10897 
10898 	return (0);
10899 }
10900 
10901 static ctl_action
10902 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10903     bool seq)
10904 {
10905 	uint64_t endlba1, endlba2;
10906 
10907 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10908 	endlba2 = lba2 + len2 - 1;
10909 
10910 	if ((endlba1 < lba2) || (endlba2 < lba1))
10911 		return (CTL_ACTION_PASS);
10912 	else
10913 		return (CTL_ACTION_BLOCK);
10914 }
10915 
10916 static int
10917 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10918 {
10919 	struct ctl_ptr_len_flags *ptrlen;
10920 	struct scsi_unmap_desc *buf, *end, *range;
10921 	uint64_t lba;
10922 	uint32_t len;
10923 
10924 	/* If not UNMAP -- go other way. */
10925 	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10926 	    io->scsiio.cdb[0] != UNMAP)
10927 		return (CTL_ACTION_ERROR);
10928 
10929 	/* If UNMAP without data -- block and wait for data. */
10930 	ptrlen = (struct ctl_ptr_len_flags *)
10931 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10932 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10933 	    ptrlen->ptr == NULL)
10934 		return (CTL_ACTION_BLOCK);
10935 
10936 	/* UNMAP with data -- check for collision. */
10937 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10938 	end = buf + ptrlen->len / sizeof(*buf);
10939 	for (range = buf; range < end; range++) {
10940 		lba = scsi_8btou64(range->lba);
10941 		len = scsi_4btoul(range->length);
10942 		if ((lba < lba2 + len2) && (lba + len > lba2))
10943 			return (CTL_ACTION_BLOCK);
10944 	}
10945 	return (CTL_ACTION_PASS);
10946 }
10947 
10948 static ctl_action
10949 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10950 {
10951 	uint64_t lba1, lba2;
10952 	uint64_t len1, len2;
10953 	int retval;
10954 
10955 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10956 		return (CTL_ACTION_ERROR);
10957 
10958 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10959 	if (retval != CTL_ACTION_ERROR)
10960 		return (retval);
10961 
10962 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10963 		return (CTL_ACTION_ERROR);
10964 
10965 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10966 		seq = FALSE;
10967 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10968 }
10969 
10970 static ctl_action
10971 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10972 {
10973 	uint64_t lba1, lba2;
10974 	uint64_t len1, len2;
10975 
10976 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10977 		return (CTL_ACTION_PASS);
10978 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10979 		return (CTL_ACTION_ERROR);
10980 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10981 		return (CTL_ACTION_ERROR);
10982 
10983 	if (lba1 + len1 == lba2)
10984 		return (CTL_ACTION_BLOCK);
10985 	return (CTL_ACTION_PASS);
10986 }
10987 
10988 static ctl_action
10989 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10990     union ctl_io *ooa_io)
10991 {
10992 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10993 	const ctl_serialize_action *serialize_row;
10994 
10995 	/*
10996 	 * The initiator attempted multiple untagged commands at the same
10997 	 * time.  Can't do that.
10998 	 */
10999 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11000 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11001 	 && ((pending_io->io_hdr.nexus.targ_port ==
11002 	      ooa_io->io_hdr.nexus.targ_port)
11003 	  && (pending_io->io_hdr.nexus.initid ==
11004 	      ooa_io->io_hdr.nexus.initid))
11005 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11006 	      CTL_FLAG_STATUS_SENT)) == 0))
11007 		return (CTL_ACTION_OVERLAP);
11008 
11009 	/*
11010 	 * The initiator attempted to send multiple tagged commands with
11011 	 * the same ID.  (It's fine if different initiators have the same
11012 	 * tag ID.)
11013 	 *
11014 	 * Even if all of those conditions are true, we don't kill the I/O
11015 	 * if the command ahead of us has been aborted.  We won't end up
11016 	 * sending it to the FETD, and it's perfectly legal to resend a
11017 	 * command with the same tag number as long as the previous
11018 	 * instance of this tag number has been aborted somehow.
11019 	 */
11020 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11021 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11022 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11023 	 && ((pending_io->io_hdr.nexus.targ_port ==
11024 	      ooa_io->io_hdr.nexus.targ_port)
11025 	  && (pending_io->io_hdr.nexus.initid ==
11026 	      ooa_io->io_hdr.nexus.initid))
11027 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
11028 	      CTL_FLAG_STATUS_SENT)) == 0))
11029 		return (CTL_ACTION_OVERLAP_TAG);
11030 
11031 	/*
11032 	 * If we get a head of queue tag, SAM-3 says that we should
11033 	 * immediately execute it.
11034 	 *
11035 	 * What happens if this command would normally block for some other
11036 	 * reason?  e.g. a request sense with a head of queue tag
11037 	 * immediately after a write.  Normally that would block, but this
11038 	 * will result in its getting executed immediately...
11039 	 *
11040 	 * We currently return "pass" instead of "skip", so we'll end up
11041 	 * going through the rest of the queue to check for overlapped tags.
11042 	 *
11043 	 * XXX KDM check for other types of blockage first??
11044 	 */
11045 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11046 		return (CTL_ACTION_PASS);
11047 
11048 	/*
11049 	 * Ordered tags have to block until all items ahead of them
11050 	 * have completed.  If we get called with an ordered tag, we always
11051 	 * block, if something else is ahead of us in the queue.
11052 	 */
11053 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11054 		return (CTL_ACTION_BLOCK);
11055 
11056 	/*
11057 	 * Simple tags get blocked until all head of queue and ordered tags
11058 	 * ahead of them have completed.  I'm lumping untagged commands in
11059 	 * with simple tags here.  XXX KDM is that the right thing to do?
11060 	 */
11061 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11062 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11063 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11064 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11065 		return (CTL_ACTION_BLOCK);
11066 
11067 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11068 	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
11069 	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
11070 	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
11071 	     pending_io->scsiio.cdb[1], pending_io));
11072 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11073 	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
11074 		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
11075 	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
11076 	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
11077 	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
11078 	     ooa_io->scsiio.cdb[1], ooa_io));
11079 
11080 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11081 
11082 	switch (serialize_row[pending_entry->seridx]) {
11083 	case CTL_SER_BLOCK:
11084 		return (CTL_ACTION_BLOCK);
11085 	case CTL_SER_EXTENT:
11086 		return (ctl_extent_check(ooa_io, pending_io,
11087 		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11088 	case CTL_SER_EXTENTOPT:
11089 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11090 		    SCP_QUEUE_ALG_UNRESTRICTED)
11091 			return (ctl_extent_check(ooa_io, pending_io,
11092 			    (lun->be_lun &&
11093 			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11094 		return (CTL_ACTION_PASS);
11095 	case CTL_SER_EXTENTSEQ:
11096 		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11097 			return (ctl_extent_check_seq(ooa_io, pending_io));
11098 		return (CTL_ACTION_PASS);
11099 	case CTL_SER_PASS:
11100 		return (CTL_ACTION_PASS);
11101 	case CTL_SER_BLOCKOPT:
11102 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
11103 		    SCP_QUEUE_ALG_UNRESTRICTED)
11104 			return (CTL_ACTION_BLOCK);
11105 		return (CTL_ACTION_PASS);
11106 	case CTL_SER_SKIP:
11107 		return (CTL_ACTION_SKIP);
11108 	default:
11109 		panic("%s: Invalid serialization value %d for %d => %d",
11110 		    __func__, serialize_row[pending_entry->seridx],
11111 		    pending_entry->seridx, ooa_entry->seridx);
11112 	}
11113 
11114 	return (CTL_ACTION_ERROR);
11115 }
11116 
11117 /*
11118  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11119  * Assumptions:
11120  * - pending_io is generally either incoming, or on the blocked queue
11121  * - starting I/O is the I/O we want to start the check with.
11122  */
11123 static ctl_action
11124 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11125 	      union ctl_io *starting_io)
11126 {
11127 	union ctl_io *ooa_io;
11128 	ctl_action action;
11129 
11130 	mtx_assert(&lun->lun_lock, MA_OWNED);
11131 
11132 	/*
11133 	 * Run back along the OOA queue, starting with the current
11134 	 * blocked I/O and going through every I/O before it on the
11135 	 * queue.  If starting_io is NULL, we'll just end up returning
11136 	 * CTL_ACTION_PASS.
11137 	 */
11138 	for (ooa_io = starting_io; ooa_io != NULL;
11139 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11140 	     ooa_links)){
11141 
11142 		/*
11143 		 * This routine just checks to see whether
11144 		 * cur_blocked is blocked by ooa_io, which is ahead
11145 		 * of it in the queue.  It doesn't queue/dequeue
11146 		 * cur_blocked.
11147 		 */
11148 		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11149 		switch (action) {
11150 		case CTL_ACTION_BLOCK:
11151 		case CTL_ACTION_OVERLAP:
11152 		case CTL_ACTION_OVERLAP_TAG:
11153 		case CTL_ACTION_SKIP:
11154 		case CTL_ACTION_ERROR:
11155 			return (action);
11156 			break; /* NOTREACHED */
11157 		case CTL_ACTION_PASS:
11158 			break;
11159 		default:
11160 			panic("%s: Invalid action %d\n", __func__, action);
11161 		}
11162 	}
11163 
11164 	return (CTL_ACTION_PASS);
11165 }
11166 
11167 /*
11168  * Assumptions:
11169  * - An I/O has just completed, and has been removed from the per-LUN OOA
11170  *   queue, so some items on the blocked queue may now be unblocked.
11171  */
11172 static int
11173 ctl_check_blocked(struct ctl_lun *lun)
11174 {
11175 	struct ctl_softc *softc = lun->ctl_softc;
11176 	union ctl_io *cur_blocked, *next_blocked;
11177 
11178 	mtx_assert(&lun->lun_lock, MA_OWNED);
11179 
11180 	/*
11181 	 * Run forward from the head of the blocked queue, checking each
11182 	 * entry against the I/Os prior to it on the OOA queue to see if
11183 	 * there is still any blockage.
11184 	 *
11185 	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11186 	 * with our removing a variable on it while it is traversing the
11187 	 * list.
11188 	 */
11189 	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11190 	     cur_blocked != NULL; cur_blocked = next_blocked) {
11191 		union ctl_io *prev_ooa;
11192 		ctl_action action;
11193 
11194 		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11195 							  blocked_links);
11196 
11197 		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11198 						      ctl_ooaq, ooa_links);
11199 
11200 		/*
11201 		 * If cur_blocked happens to be the first item in the OOA
11202 		 * queue now, prev_ooa will be NULL, and the action
11203 		 * returned will just be CTL_ACTION_PASS.
11204 		 */
11205 		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11206 
11207 		switch (action) {
11208 		case CTL_ACTION_BLOCK:
11209 			/* Nothing to do here, still blocked */
11210 			break;
11211 		case CTL_ACTION_OVERLAP:
11212 		case CTL_ACTION_OVERLAP_TAG:
11213 			/*
11214 			 * This shouldn't happen!  In theory we've already
11215 			 * checked this command for overlap...
11216 			 */
11217 			break;
11218 		case CTL_ACTION_PASS:
11219 		case CTL_ACTION_SKIP: {
11220 			const struct ctl_cmd_entry *entry;
11221 
11222 			/*
11223 			 * The skip case shouldn't happen, this transaction
11224 			 * should have never made it onto the blocked queue.
11225 			 */
11226 			/*
11227 			 * This I/O is no longer blocked, we can remove it
11228 			 * from the blocked queue.  Since this is a TAILQ
11229 			 * (doubly linked list), we can do O(1) removals
11230 			 * from any place on the list.
11231 			 */
11232 			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11233 				     blocked_links);
11234 			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11235 
11236 			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11237 			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11238 				/*
11239 				 * Need to send IO back to original side to
11240 				 * run
11241 				 */
11242 				union ctl_ha_msg msg_info;
11243 
11244 				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11245 				msg_info.hdr.original_sc =
11246 					cur_blocked->io_hdr.original_sc;
11247 				msg_info.hdr.serializing_sc = cur_blocked;
11248 				msg_info.hdr.msg_type = CTL_MSG_R2R;
11249 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11250 				    sizeof(msg_info.hdr), M_NOWAIT);
11251 				break;
11252 			}
11253 			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11254 
11255 			/*
11256 			 * Check this I/O for LUN state changes that may
11257 			 * have happened while this command was blocked.
11258 			 * The LUN state may have been changed by a command
11259 			 * ahead of us in the queue, so we need to re-check
11260 			 * for any states that can be caused by SCSI
11261 			 * commands.
11262 			 */
11263 			if (ctl_scsiio_lun_check(lun, entry,
11264 						 &cur_blocked->scsiio) == 0) {
11265 				cur_blocked->io_hdr.flags |=
11266 				                      CTL_FLAG_IS_WAS_ON_RTR;
11267 				ctl_enqueue_rtr(cur_blocked);
11268 			} else
11269 				ctl_done(cur_blocked);
11270 			break;
11271 		}
11272 		default:
11273 			/*
11274 			 * This probably shouldn't happen -- we shouldn't
11275 			 * get CTL_ACTION_ERROR, or anything else.
11276 			 */
11277 			break;
11278 		}
11279 	}
11280 
11281 	return (CTL_RETVAL_COMPLETE);
11282 }
11283 
11284 /*
11285  * This routine (with one exception) checks LUN flags that can be set by
11286  * commands ahead of us in the OOA queue.  These flags have to be checked
11287  * when a command initially comes in, and when we pull a command off the
11288  * blocked queue and are preparing to execute it.  The reason we have to
11289  * check these flags for commands on the blocked queue is that the LUN
11290  * state may have been changed by a command ahead of us while we're on the
11291  * blocked queue.
11292  *
11293  * Ordering is somewhat important with these checks, so please pay
11294  * careful attention to the placement of any new checks.
11295  */
11296 static int
11297 ctl_scsiio_lun_check(struct ctl_lun *lun,
11298     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11299 {
11300 	struct ctl_softc *softc = lun->ctl_softc;
11301 	int retval;
11302 	uint32_t residx;
11303 
11304 	retval = 0;
11305 
11306 	mtx_assert(&lun->lun_lock, MA_OWNED);
11307 
11308 	/*
11309 	 * If this shelf is a secondary shelf controller, we may have to
11310 	 * reject some commands disallowed by HA mode and link state.
11311 	 */
11312 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11313 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11314 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11315 			ctl_set_lun_unavail(ctsio);
11316 			retval = 1;
11317 			goto bailout;
11318 		}
11319 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11320 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11321 			ctl_set_lun_transit(ctsio);
11322 			retval = 1;
11323 			goto bailout;
11324 		}
11325 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11326 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11327 			ctl_set_lun_standby(ctsio);
11328 			retval = 1;
11329 			goto bailout;
11330 		}
11331 
11332 		/* The rest of checks are only done on executing side */
11333 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11334 			goto bailout;
11335 	}
11336 
11337 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11338 		if (lun->be_lun &&
11339 		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11340 			ctl_set_hw_write_protected(ctsio);
11341 			retval = 1;
11342 			goto bailout;
11343 		}
11344 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11345 			ctl_set_sense(ctsio, /*current_error*/ 1,
11346 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11347 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11348 			retval = 1;
11349 			goto bailout;
11350 		}
11351 	}
11352 
11353 	/*
11354 	 * Check for a reservation conflict.  If this command isn't allowed
11355 	 * even on reserved LUNs, and if this initiator isn't the one who
11356 	 * reserved us, reject the command with a reservation conflict.
11357 	 */
11358 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11359 	if ((lun->flags & CTL_LUN_RESERVED)
11360 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11361 		if (lun->res_idx != residx) {
11362 			ctl_set_reservation_conflict(ctsio);
11363 			retval = 1;
11364 			goto bailout;
11365 		}
11366 	}
11367 
11368 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11369 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11370 		/* No reservation or command is allowed. */;
11371 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11372 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11373 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11374 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11375 		/* The command is allowed for Write Exclusive resv. */;
11376 	} else {
11377 		/*
11378 		 * if we aren't registered or it's a res holder type
11379 		 * reservation and this isn't the res holder then set a
11380 		 * conflict.
11381 		 */
11382 		if (ctl_get_prkey(lun, residx) == 0 ||
11383 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11384 			ctl_set_reservation_conflict(ctsio);
11385 			retval = 1;
11386 			goto bailout;
11387 		}
11388 	}
11389 
11390 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11391 		if (lun->flags & CTL_LUN_EJECTED)
11392 			ctl_set_lun_ejected(ctsio);
11393 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11394 			if (lun->flags & CTL_LUN_REMOVABLE)
11395 				ctl_set_lun_no_media(ctsio);
11396 			else
11397 				ctl_set_lun_int_reqd(ctsio);
11398 		} else if (lun->flags & CTL_LUN_STOPPED)
11399 			ctl_set_lun_stopped(ctsio);
11400 		else
11401 			goto bailout;
11402 		retval = 1;
11403 		goto bailout;
11404 	}
11405 
11406 bailout:
11407 	return (retval);
11408 }
11409 
11410 static void
11411 ctl_failover_io(union ctl_io *io, int have_lock)
11412 {
11413 	ctl_set_busy(&io->scsiio);
11414 	ctl_done(io);
11415 }
11416 
11417 static void
11418 ctl_failover_lun(union ctl_io *rio)
11419 {
11420 	struct ctl_softc *softc = CTL_SOFTC(rio);
11421 	struct ctl_lun *lun;
11422 	struct ctl_io_hdr *io, *next_io;
11423 	uint32_t targ_lun;
11424 
11425 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11426 	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11427 
11428 	/* Find and lock the LUN. */
11429 	mtx_lock(&softc->ctl_lock);
11430 	if (targ_lun > CTL_MAX_LUNS ||
11431 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11432 		mtx_unlock(&softc->ctl_lock);
11433 		return;
11434 	}
11435 	mtx_lock(&lun->lun_lock);
11436 	mtx_unlock(&softc->ctl_lock);
11437 	if (lun->flags & CTL_LUN_DISABLED) {
11438 		mtx_unlock(&lun->lun_lock);
11439 		return;
11440 	}
11441 
11442 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11443 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11444 			/* We are master */
11445 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11446 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11447 					io->flags |= CTL_FLAG_ABORT;
11448 					io->flags |= CTL_FLAG_FAILOVER;
11449 				} else { /* This can be only due to DATAMOVE */
11450 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11451 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11452 					io->flags |= CTL_FLAG_IO_ACTIVE;
11453 					io->port_status = 31340;
11454 					ctl_enqueue_isc((union ctl_io *)io);
11455 				}
11456 			}
11457 			/* We are slave */
11458 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11459 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11460 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11461 					io->flags |= CTL_FLAG_FAILOVER;
11462 				} else {
11463 					ctl_set_busy(&((union ctl_io *)io)->
11464 					    scsiio);
11465 					ctl_done((union ctl_io *)io);
11466 				}
11467 			}
11468 		}
11469 	} else { /* SERIALIZE modes */
11470 		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11471 		    next_io) {
11472 			/* We are master */
11473 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11474 				TAILQ_REMOVE(&lun->blocked_queue, io,
11475 				    blocked_links);
11476 				io->flags &= ~CTL_FLAG_BLOCKED;
11477 				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11478 				ctl_free_io((union ctl_io *)io);
11479 			}
11480 		}
11481 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11482 			/* We are master */
11483 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11484 				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11485 				ctl_free_io((union ctl_io *)io);
11486 			}
11487 			/* We are slave */
11488 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11489 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11490 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11491 					ctl_set_busy(&((union ctl_io *)io)->
11492 					    scsiio);
11493 					ctl_done((union ctl_io *)io);
11494 				}
11495 			}
11496 		}
11497 		ctl_check_blocked(lun);
11498 	}
11499 	mtx_unlock(&lun->lun_lock);
11500 }
11501 
11502 static int
11503 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11504 {
11505 	struct ctl_lun *lun;
11506 	const struct ctl_cmd_entry *entry;
11507 	uint32_t initidx, targ_lun;
11508 	int retval = 0;
11509 
11510 	lun = NULL;
11511 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11512 	if (targ_lun < CTL_MAX_LUNS)
11513 		lun = softc->ctl_luns[targ_lun];
11514 	if (lun) {
11515 		/*
11516 		 * If the LUN is invalid, pretend that it doesn't exist.
11517 		 * It will go away as soon as all pending I/O has been
11518 		 * completed.
11519 		 */
11520 		mtx_lock(&lun->lun_lock);
11521 		if (lun->flags & CTL_LUN_DISABLED) {
11522 			mtx_unlock(&lun->lun_lock);
11523 			lun = NULL;
11524 		}
11525 	}
11526 	CTL_LUN(ctsio) = lun;
11527 	if (lun) {
11528 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11529 
11530 		/*
11531 		 * Every I/O goes into the OOA queue for a particular LUN,
11532 		 * and stays there until completion.
11533 		 */
11534 #ifdef CTL_TIME_IO
11535 		if (TAILQ_EMPTY(&lun->ooa_queue))
11536 			lun->idle_time += getsbinuptime() - lun->last_busy;
11537 #endif
11538 		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11539 	}
11540 
11541 	/* Get command entry and return error if it is unsuppotyed. */
11542 	entry = ctl_validate_command(ctsio);
11543 	if (entry == NULL) {
11544 		if (lun)
11545 			mtx_unlock(&lun->lun_lock);
11546 		return (retval);
11547 	}
11548 
11549 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11550 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11551 
11552 	/*
11553 	 * Check to see whether we can send this command to LUNs that don't
11554 	 * exist.  This should pretty much only be the case for inquiry
11555 	 * and request sense.  Further checks, below, really require having
11556 	 * a LUN, so we can't really check the command anymore.  Just put
11557 	 * it on the rtr queue.
11558 	 */
11559 	if (lun == NULL) {
11560 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11561 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11562 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11563 			return (retval);
11564 		}
11565 
11566 		ctl_set_unsupported_lun(ctsio);
11567 		ctl_done((union ctl_io *)ctsio);
11568 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11569 		return (retval);
11570 	} else {
11571 		/*
11572 		 * Make sure we support this particular command on this LUN.
11573 		 * e.g., we don't support writes to the control LUN.
11574 		 */
11575 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11576 			mtx_unlock(&lun->lun_lock);
11577 			ctl_set_invalid_opcode(ctsio);
11578 			ctl_done((union ctl_io *)ctsio);
11579 			return (retval);
11580 		}
11581 	}
11582 
11583 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11584 
11585 #ifdef CTL_WITH_CA
11586 	/*
11587 	 * If we've got a request sense, it'll clear the contingent
11588 	 * allegiance condition.  Otherwise, if we have a CA condition for
11589 	 * this initiator, clear it, because it sent down a command other
11590 	 * than request sense.
11591 	 */
11592 	if ((ctsio->cdb[0] != REQUEST_SENSE)
11593 	 && (ctl_is_set(lun->have_ca, initidx)))
11594 		ctl_clear_mask(lun->have_ca, initidx);
11595 #endif
11596 
11597 	/*
11598 	 * If the command has this flag set, it handles its own unit
11599 	 * attention reporting, we shouldn't do anything.  Otherwise we
11600 	 * check for any pending unit attentions, and send them back to the
11601 	 * initiator.  We only do this when a command initially comes in,
11602 	 * not when we pull it off the blocked queue.
11603 	 *
11604 	 * According to SAM-3, section 5.3.2, the order that things get
11605 	 * presented back to the host is basically unit attentions caused
11606 	 * by some sort of reset event, busy status, reservation conflicts
11607 	 * or task set full, and finally any other status.
11608 	 *
11609 	 * One issue here is that some of the unit attentions we report
11610 	 * don't fall into the "reset" category (e.g. "reported luns data
11611 	 * has changed").  So reporting it here, before the reservation
11612 	 * check, may be technically wrong.  I guess the only thing to do
11613 	 * would be to check for and report the reset events here, and then
11614 	 * check for the other unit attention types after we check for a
11615 	 * reservation conflict.
11616 	 *
11617 	 * XXX KDM need to fix this
11618 	 */
11619 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11620 		ctl_ua_type ua_type;
11621 		u_int sense_len = 0;
11622 
11623 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11624 		    &sense_len, SSD_TYPE_NONE);
11625 		if (ua_type != CTL_UA_NONE) {
11626 			mtx_unlock(&lun->lun_lock);
11627 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11628 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11629 			ctsio->sense_len = sense_len;
11630 			ctl_done((union ctl_io *)ctsio);
11631 			return (retval);
11632 		}
11633 	}
11634 
11635 
11636 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11637 		mtx_unlock(&lun->lun_lock);
11638 		ctl_done((union ctl_io *)ctsio);
11639 		return (retval);
11640 	}
11641 
11642 	/*
11643 	 * XXX CHD this is where we want to send IO to other side if
11644 	 * this LUN is secondary on this SC. We will need to make a copy
11645 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11646 	 * the copy we send as FROM_OTHER.
11647 	 * We also need to stuff the address of the original IO so we can
11648 	 * find it easily. Something similar will need be done on the other
11649 	 * side so when we are done we can find the copy.
11650 	 */
11651 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11652 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11653 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11654 		union ctl_ha_msg msg_info;
11655 		int isc_retval;
11656 
11657 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11658 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11659 		mtx_unlock(&lun->lun_lock);
11660 
11661 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11662 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11663 		msg_info.hdr.serializing_sc = NULL;
11664 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11665 		msg_info.scsi.tag_num = ctsio->tag_num;
11666 		msg_info.scsi.tag_type = ctsio->tag_type;
11667 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11668 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11669 
11670 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11671 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11672 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11673 			ctl_set_busy(ctsio);
11674 			ctl_done((union ctl_io *)ctsio);
11675 			return (retval);
11676 		}
11677 		return (retval);
11678 	}
11679 
11680 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11681 			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11682 			      ctl_ooaq, ooa_links))) {
11683 	case CTL_ACTION_BLOCK:
11684 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11685 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11686 				  blocked_links);
11687 		mtx_unlock(&lun->lun_lock);
11688 		return (retval);
11689 	case CTL_ACTION_PASS:
11690 	case CTL_ACTION_SKIP:
11691 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11692 		mtx_unlock(&lun->lun_lock);
11693 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11694 		break;
11695 	case CTL_ACTION_OVERLAP:
11696 		mtx_unlock(&lun->lun_lock);
11697 		ctl_set_overlapped_cmd(ctsio);
11698 		ctl_done((union ctl_io *)ctsio);
11699 		break;
11700 	case CTL_ACTION_OVERLAP_TAG:
11701 		mtx_unlock(&lun->lun_lock);
11702 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11703 		ctl_done((union ctl_io *)ctsio);
11704 		break;
11705 	case CTL_ACTION_ERROR:
11706 	default:
11707 		mtx_unlock(&lun->lun_lock);
11708 		ctl_set_internal_failure(ctsio,
11709 					 /*sks_valid*/ 0,
11710 					 /*retry_count*/ 0);
11711 		ctl_done((union ctl_io *)ctsio);
11712 		break;
11713 	}
11714 	return (retval);
11715 }
11716 
11717 const struct ctl_cmd_entry *
11718 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11719 {
11720 	const struct ctl_cmd_entry *entry;
11721 	int service_action;
11722 
11723 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11724 	if (sa)
11725 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11726 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11727 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11728 		entry = &((const struct ctl_cmd_entry *)
11729 		    entry->execute)[service_action];
11730 	}
11731 	return (entry);
11732 }
11733 
11734 const struct ctl_cmd_entry *
11735 ctl_validate_command(struct ctl_scsiio *ctsio)
11736 {
11737 	const struct ctl_cmd_entry *entry;
11738 	int i, sa;
11739 	uint8_t diff;
11740 
11741 	entry = ctl_get_cmd_entry(ctsio, &sa);
11742 	if (entry->execute == NULL) {
11743 		if (sa)
11744 			ctl_set_invalid_field(ctsio,
11745 					      /*sks_valid*/ 1,
11746 					      /*command*/ 1,
11747 					      /*field*/ 1,
11748 					      /*bit_valid*/ 1,
11749 					      /*bit*/ 4);
11750 		else
11751 			ctl_set_invalid_opcode(ctsio);
11752 		ctl_done((union ctl_io *)ctsio);
11753 		return (NULL);
11754 	}
11755 	KASSERT(entry->length > 0,
11756 	    ("Not defined length for command 0x%02x/0x%02x",
11757 	     ctsio->cdb[0], ctsio->cdb[1]));
11758 	for (i = 1; i < entry->length; i++) {
11759 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11760 		if (diff == 0)
11761 			continue;
11762 		ctl_set_invalid_field(ctsio,
11763 				      /*sks_valid*/ 1,
11764 				      /*command*/ 1,
11765 				      /*field*/ i,
11766 				      /*bit_valid*/ 1,
11767 				      /*bit*/ fls(diff) - 1);
11768 		ctl_done((union ctl_io *)ctsio);
11769 		return (NULL);
11770 	}
11771 	return (entry);
11772 }
11773 
11774 static int
11775 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11776 {
11777 
11778 	switch (lun_type) {
11779 	case T_DIRECT:
11780 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11781 			return (0);
11782 		break;
11783 	case T_PROCESSOR:
11784 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11785 			return (0);
11786 		break;
11787 	case T_CDROM:
11788 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11789 			return (0);
11790 		break;
11791 	default:
11792 		return (0);
11793 	}
11794 	return (1);
11795 }
11796 
11797 static int
11798 ctl_scsiio(struct ctl_scsiio *ctsio)
11799 {
11800 	int retval;
11801 	const struct ctl_cmd_entry *entry;
11802 
11803 	retval = CTL_RETVAL_COMPLETE;
11804 
11805 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11806 
11807 	entry = ctl_get_cmd_entry(ctsio, NULL);
11808 
11809 	/*
11810 	 * If this I/O has been aborted, just send it straight to
11811 	 * ctl_done() without executing it.
11812 	 */
11813 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11814 		ctl_done((union ctl_io *)ctsio);
11815 		goto bailout;
11816 	}
11817 
11818 	/*
11819 	 * All the checks should have been handled by ctl_scsiio_precheck().
11820 	 * We should be clear now to just execute the I/O.
11821 	 */
11822 	retval = entry->execute(ctsio);
11823 
11824 bailout:
11825 	return (retval);
11826 }
11827 
11828 /*
11829  * Since we only implement one target right now, a bus reset simply resets
11830  * our single target.
11831  */
11832 static int
11833 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11834 {
11835 	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11836 }
11837 
11838 static int
11839 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11840 		 ctl_ua_type ua_type)
11841 {
11842 	struct ctl_port *port = CTL_PORT(io);
11843 	struct ctl_lun *lun;
11844 	int retval;
11845 
11846 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11847 		union ctl_ha_msg msg_info;
11848 
11849 		msg_info.hdr.nexus = io->io_hdr.nexus;
11850 		if (ua_type==CTL_UA_TARG_RESET)
11851 			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11852 		else
11853 			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11854 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11855 		msg_info.hdr.original_sc = NULL;
11856 		msg_info.hdr.serializing_sc = NULL;
11857 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11858 		    sizeof(msg_info.task), M_WAITOK);
11859 	}
11860 	retval = 0;
11861 
11862 	mtx_lock(&softc->ctl_lock);
11863 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11864 		if (port != NULL &&
11865 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11866 			continue;
11867 		retval += ctl_do_lun_reset(lun, io, ua_type);
11868 	}
11869 	mtx_unlock(&softc->ctl_lock);
11870 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11871 	return (retval);
11872 }
11873 
11874 /*
11875  * The LUN should always be set.  The I/O is optional, and is used to
11876  * distinguish between I/Os sent by this initiator, and by other
11877  * initiators.  We set unit attention for initiators other than this one.
11878  * SAM-3 is vague on this point.  It does say that a unit attention should
11879  * be established for other initiators when a LUN is reset (see section
11880  * 5.7.3), but it doesn't specifically say that the unit attention should
11881  * be established for this particular initiator when a LUN is reset.  Here
11882  * is the relevant text, from SAM-3 rev 8:
11883  *
11884  * 5.7.2 When a SCSI initiator port aborts its own tasks
11885  *
11886  * When a SCSI initiator port causes its own task(s) to be aborted, no
11887  * notification that the task(s) have been aborted shall be returned to
11888  * the SCSI initiator port other than the completion response for the
11889  * command or task management function action that caused the task(s) to
11890  * be aborted and notification(s) associated with related effects of the
11891  * action (e.g., a reset unit attention condition).
11892  *
11893  * XXX KDM for now, we're setting unit attention for all initiators.
11894  */
11895 static int
11896 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11897 {
11898 	union ctl_io *xio;
11899 #if 0
11900 	uint32_t initidx;
11901 #endif
11902 	int i;
11903 
11904 	mtx_lock(&lun->lun_lock);
11905 	/*
11906 	 * Run through the OOA queue and abort each I/O.
11907 	 */
11908 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11909 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11910 		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11911 	}
11912 
11913 	/*
11914 	 * This version sets unit attention for every
11915 	 */
11916 #if 0
11917 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11918 	ctl_est_ua_all(lun, initidx, ua_type);
11919 #else
11920 	ctl_est_ua_all(lun, -1, ua_type);
11921 #endif
11922 
11923 	/*
11924 	 * A reset (any kind, really) clears reservations established with
11925 	 * RESERVE/RELEASE.  It does not clear reservations established
11926 	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11927 	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11928 	 * reservations made with the RESERVE/RELEASE commands, because
11929 	 * those commands are obsolete in SPC-3.
11930 	 */
11931 	lun->flags &= ~CTL_LUN_RESERVED;
11932 
11933 #ifdef CTL_WITH_CA
11934 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11935 		ctl_clear_mask(lun->have_ca, i);
11936 #endif
11937 	lun->prevent_count = 0;
11938 	if (lun->prevent) {
11939 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11940 			ctl_clear_mask(lun->prevent, i);
11941 	}
11942 	mtx_unlock(&lun->lun_lock);
11943 
11944 	return (0);
11945 }
11946 
11947 static int
11948 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11949 {
11950 	struct ctl_lun *lun;
11951 	uint32_t targ_lun;
11952 	int retval;
11953 
11954 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11955 	mtx_lock(&softc->ctl_lock);
11956 	if (targ_lun >= CTL_MAX_LUNS ||
11957 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11958 		mtx_unlock(&softc->ctl_lock);
11959 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11960 		return (1);
11961 	}
11962 	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11963 	mtx_unlock(&softc->ctl_lock);
11964 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11965 
11966 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11967 		union ctl_ha_msg msg_info;
11968 
11969 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11970 		msg_info.hdr.nexus = io->io_hdr.nexus;
11971 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11972 		msg_info.hdr.original_sc = NULL;
11973 		msg_info.hdr.serializing_sc = NULL;
11974 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11975 		    sizeof(msg_info.task), M_WAITOK);
11976 	}
11977 	return (retval);
11978 }
11979 
11980 static void
11981 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11982     int other_sc)
11983 {
11984 	union ctl_io *xio;
11985 
11986 	mtx_assert(&lun->lun_lock, MA_OWNED);
11987 
11988 	/*
11989 	 * Run through the OOA queue and attempt to find the given I/O.
11990 	 * The target port, initiator ID, tag type and tag number have to
11991 	 * match the values that we got from the initiator.  If we have an
11992 	 * untagged command to abort, simply abort the first untagged command
11993 	 * we come to.  We only allow one untagged command at a time of course.
11994 	 */
11995 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11996 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11997 
11998 		if ((targ_port == UINT32_MAX ||
11999 		     targ_port == xio->io_hdr.nexus.targ_port) &&
12000 		    (init_id == UINT32_MAX ||
12001 		     init_id == xio->io_hdr.nexus.initid)) {
12002 			if (targ_port != xio->io_hdr.nexus.targ_port ||
12003 			    init_id != xio->io_hdr.nexus.initid)
12004 				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12005 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12006 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12007 				union ctl_ha_msg msg_info;
12008 
12009 				msg_info.hdr.nexus = xio->io_hdr.nexus;
12010 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12011 				msg_info.task.tag_num = xio->scsiio.tag_num;
12012 				msg_info.task.tag_type = xio->scsiio.tag_type;
12013 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12014 				msg_info.hdr.original_sc = NULL;
12015 				msg_info.hdr.serializing_sc = NULL;
12016 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12017 				    sizeof(msg_info.task), M_NOWAIT);
12018 			}
12019 		}
12020 	}
12021 }
12022 
12023 static int
12024 ctl_abort_task_set(union ctl_io *io)
12025 {
12026 	struct ctl_softc *softc = CTL_SOFTC(io);
12027 	struct ctl_lun *lun;
12028 	uint32_t targ_lun;
12029 
12030 	/*
12031 	 * Look up the LUN.
12032 	 */
12033 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12034 	mtx_lock(&softc->ctl_lock);
12035 	if (targ_lun >= CTL_MAX_LUNS ||
12036 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12037 		mtx_unlock(&softc->ctl_lock);
12038 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12039 		return (1);
12040 	}
12041 
12042 	mtx_lock(&lun->lun_lock);
12043 	mtx_unlock(&softc->ctl_lock);
12044 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12045 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12046 		    io->io_hdr.nexus.initid,
12047 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12048 	} else { /* CTL_TASK_CLEAR_TASK_SET */
12049 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12050 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12051 	}
12052 	mtx_unlock(&lun->lun_lock);
12053 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12054 	return (0);
12055 }
12056 
12057 static int
12058 ctl_i_t_nexus_reset(union ctl_io *io)
12059 {
12060 	struct ctl_softc *softc = CTL_SOFTC(io);
12061 	struct ctl_lun *lun;
12062 	uint32_t initidx;
12063 
12064 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12065 		union ctl_ha_msg msg_info;
12066 
12067 		msg_info.hdr.nexus = io->io_hdr.nexus;
12068 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12069 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12070 		msg_info.hdr.original_sc = NULL;
12071 		msg_info.hdr.serializing_sc = NULL;
12072 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12073 		    sizeof(msg_info.task), M_WAITOK);
12074 	}
12075 
12076 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12077 	mtx_lock(&softc->ctl_lock);
12078 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12079 		mtx_lock(&lun->lun_lock);
12080 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12081 		    io->io_hdr.nexus.initid, 1);
12082 #ifdef CTL_WITH_CA
12083 		ctl_clear_mask(lun->have_ca, initidx);
12084 #endif
12085 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12086 			lun->flags &= ~CTL_LUN_RESERVED;
12087 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
12088 			ctl_clear_mask(lun->prevent, initidx);
12089 			lun->prevent_count--;
12090 		}
12091 		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12092 		mtx_unlock(&lun->lun_lock);
12093 	}
12094 	mtx_unlock(&softc->ctl_lock);
12095 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12096 	return (0);
12097 }
12098 
12099 static int
12100 ctl_abort_task(union ctl_io *io)
12101 {
12102 	struct ctl_softc *softc = CTL_SOFTC(io);
12103 	union ctl_io *xio;
12104 	struct ctl_lun *lun;
12105 #if 0
12106 	struct sbuf sb;
12107 	char printbuf[128];
12108 #endif
12109 	int found;
12110 	uint32_t targ_lun;
12111 
12112 	found = 0;
12113 
12114 	/*
12115 	 * Look up the LUN.
12116 	 */
12117 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12118 	mtx_lock(&softc->ctl_lock);
12119 	if (targ_lun >= CTL_MAX_LUNS ||
12120 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12121 		mtx_unlock(&softc->ctl_lock);
12122 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12123 		return (1);
12124 	}
12125 
12126 #if 0
12127 	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12128 	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12129 #endif
12130 
12131 	mtx_lock(&lun->lun_lock);
12132 	mtx_unlock(&softc->ctl_lock);
12133 	/*
12134 	 * Run through the OOA queue and attempt to find the given I/O.
12135 	 * The target port, initiator ID, tag type and tag number have to
12136 	 * match the values that we got from the initiator.  If we have an
12137 	 * untagged command to abort, simply abort the first untagged command
12138 	 * we come to.  We only allow one untagged command at a time of course.
12139 	 */
12140 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12141 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12142 #if 0
12143 		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12144 
12145 		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12146 			    lun->lun, xio->scsiio.tag_num,
12147 			    xio->scsiio.tag_type,
12148 			    (xio->io_hdr.blocked_links.tqe_prev
12149 			    == NULL) ? "" : " BLOCKED",
12150 			    (xio->io_hdr.flags &
12151 			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12152 			    (xio->io_hdr.flags &
12153 			    CTL_FLAG_ABORT) ? " ABORT" : "",
12154 			    (xio->io_hdr.flags &
12155 			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12156 		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12157 		sbuf_finish(&sb);
12158 		printf("%s\n", sbuf_data(&sb));
12159 #endif
12160 
12161 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12162 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12163 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12164 			continue;
12165 
12166 		/*
12167 		 * If the abort says that the task is untagged, the
12168 		 * task in the queue must be untagged.  Otherwise,
12169 		 * we just check to see whether the tag numbers
12170 		 * match.  This is because the QLogic firmware
12171 		 * doesn't pass back the tag type in an abort
12172 		 * request.
12173 		 */
12174 #if 0
12175 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12176 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12177 		 || (xio->scsiio.tag_num == io->taskio.tag_num))
12178 #endif
12179 		/*
12180 		 * XXX KDM we've got problems with FC, because it
12181 		 * doesn't send down a tag type with aborts.  So we
12182 		 * can only really go by the tag number...
12183 		 * This may cause problems with parallel SCSI.
12184 		 * Need to figure that out!!
12185 		 */
12186 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12187 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12188 			found = 1;
12189 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12190 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12191 				union ctl_ha_msg msg_info;
12192 
12193 				msg_info.hdr.nexus = io->io_hdr.nexus;
12194 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12195 				msg_info.task.tag_num = io->taskio.tag_num;
12196 				msg_info.task.tag_type = io->taskio.tag_type;
12197 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12198 				msg_info.hdr.original_sc = NULL;
12199 				msg_info.hdr.serializing_sc = NULL;
12200 #if 0
12201 				printf("Sent Abort to other side\n");
12202 #endif
12203 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12204 				    sizeof(msg_info.task), M_NOWAIT);
12205 			}
12206 #if 0
12207 			printf("ctl_abort_task: found I/O to abort\n");
12208 #endif
12209 		}
12210 	}
12211 	mtx_unlock(&lun->lun_lock);
12212 
12213 	if (found == 0) {
12214 		/*
12215 		 * This isn't really an error.  It's entirely possible for
12216 		 * the abort and command completion to cross on the wire.
12217 		 * This is more of an informative/diagnostic error.
12218 		 */
12219 #if 0
12220 		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12221 		       "%u:%u:%u tag %d type %d\n",
12222 		       io->io_hdr.nexus.initid,
12223 		       io->io_hdr.nexus.targ_port,
12224 		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12225 		       io->taskio.tag_type);
12226 #endif
12227 	}
12228 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12229 	return (0);
12230 }
12231 
12232 static int
12233 ctl_query_task(union ctl_io *io, int task_set)
12234 {
12235 	struct ctl_softc *softc = CTL_SOFTC(io);
12236 	union ctl_io *xio;
12237 	struct ctl_lun *lun;
12238 	int found = 0;
12239 	uint32_t targ_lun;
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 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12252 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12253 
12254 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12255 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12256 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12257 			continue;
12258 
12259 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12260 			found = 1;
12261 			break;
12262 		}
12263 	}
12264 	mtx_unlock(&lun->lun_lock);
12265 	if (found)
12266 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12267 	else
12268 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12269 	return (0);
12270 }
12271 
12272 static int
12273 ctl_query_async_event(union ctl_io *io)
12274 {
12275 	struct ctl_softc *softc = CTL_SOFTC(io);
12276 	struct ctl_lun *lun;
12277 	ctl_ua_type ua;
12278 	uint32_t targ_lun, initidx;
12279 
12280 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12281 	mtx_lock(&softc->ctl_lock);
12282 	if (targ_lun >= CTL_MAX_LUNS ||
12283 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12284 		mtx_unlock(&softc->ctl_lock);
12285 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12286 		return (1);
12287 	}
12288 	mtx_lock(&lun->lun_lock);
12289 	mtx_unlock(&softc->ctl_lock);
12290 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12291 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12292 	mtx_unlock(&lun->lun_lock);
12293 	if (ua != CTL_UA_NONE)
12294 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12295 	else
12296 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12297 	return (0);
12298 }
12299 
12300 static void
12301 ctl_run_task(union ctl_io *io)
12302 {
12303 	struct ctl_softc *softc = CTL_SOFTC(io);
12304 	int retval = 1;
12305 
12306 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12307 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12308 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12309 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12310 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12311 	switch (io->taskio.task_action) {
12312 	case CTL_TASK_ABORT_TASK:
12313 		retval = ctl_abort_task(io);
12314 		break;
12315 	case CTL_TASK_ABORT_TASK_SET:
12316 	case CTL_TASK_CLEAR_TASK_SET:
12317 		retval = ctl_abort_task_set(io);
12318 		break;
12319 	case CTL_TASK_CLEAR_ACA:
12320 		break;
12321 	case CTL_TASK_I_T_NEXUS_RESET:
12322 		retval = ctl_i_t_nexus_reset(io);
12323 		break;
12324 	case CTL_TASK_LUN_RESET:
12325 		retval = ctl_lun_reset(softc, io);
12326 		break;
12327 	case CTL_TASK_TARGET_RESET:
12328 		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12329 		break;
12330 	case CTL_TASK_BUS_RESET:
12331 		retval = ctl_bus_reset(softc, io);
12332 		break;
12333 	case CTL_TASK_PORT_LOGIN:
12334 		break;
12335 	case CTL_TASK_PORT_LOGOUT:
12336 		break;
12337 	case CTL_TASK_QUERY_TASK:
12338 		retval = ctl_query_task(io, 0);
12339 		break;
12340 	case CTL_TASK_QUERY_TASK_SET:
12341 		retval = ctl_query_task(io, 1);
12342 		break;
12343 	case CTL_TASK_QUERY_ASYNC_EVENT:
12344 		retval = ctl_query_async_event(io);
12345 		break;
12346 	default:
12347 		printf("%s: got unknown task management event %d\n",
12348 		       __func__, io->taskio.task_action);
12349 		break;
12350 	}
12351 	if (retval == 0)
12352 		io->io_hdr.status = CTL_SUCCESS;
12353 	else
12354 		io->io_hdr.status = CTL_ERROR;
12355 	ctl_done(io);
12356 }
12357 
12358 /*
12359  * For HA operation.  Handle commands that come in from the other
12360  * controller.
12361  */
12362 static void
12363 ctl_handle_isc(union ctl_io *io)
12364 {
12365 	struct ctl_softc *softc = CTL_SOFTC(io);
12366 	struct ctl_lun *lun;
12367 	const struct ctl_cmd_entry *entry;
12368 	uint32_t targ_lun;
12369 
12370 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12371 	switch (io->io_hdr.msg_type) {
12372 	case CTL_MSG_SERIALIZE:
12373 		ctl_serialize_other_sc_cmd(&io->scsiio);
12374 		break;
12375 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12376 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12377 		if (targ_lun >= CTL_MAX_LUNS ||
12378 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12379 			ctl_done(io);
12380 			break;
12381 		}
12382 		mtx_lock(&lun->lun_lock);
12383 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12384 			mtx_unlock(&lun->lun_lock);
12385 			ctl_done(io);
12386 			break;
12387 		}
12388 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12389 		mtx_unlock(&lun->lun_lock);
12390 		ctl_enqueue_rtr(io);
12391 		break;
12392 	case CTL_MSG_FINISH_IO:
12393 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12394 			ctl_done(io);
12395 			break;
12396 		}
12397 		if (targ_lun >= CTL_MAX_LUNS ||
12398 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12399 			ctl_free_io(io);
12400 			break;
12401 		}
12402 		mtx_lock(&lun->lun_lock);
12403 		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12404 		ctl_check_blocked(lun);
12405 		mtx_unlock(&lun->lun_lock);
12406 		ctl_free_io(io);
12407 		break;
12408 	case CTL_MSG_PERS_ACTION:
12409 		ctl_hndl_per_res_out_on_other_sc(io);
12410 		ctl_free_io(io);
12411 		break;
12412 	case CTL_MSG_BAD_JUJU:
12413 		ctl_done(io);
12414 		break;
12415 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12416 		ctl_datamove_remote(io);
12417 		break;
12418 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12419 		io->scsiio.be_move_done(io);
12420 		break;
12421 	case CTL_MSG_FAILOVER:
12422 		ctl_failover_lun(io);
12423 		ctl_free_io(io);
12424 		break;
12425 	default:
12426 		printf("%s: Invalid message type %d\n",
12427 		       __func__, io->io_hdr.msg_type);
12428 		ctl_free_io(io);
12429 		break;
12430 	}
12431 
12432 }
12433 
12434 
12435 /*
12436  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12437  * there is no match.
12438  */
12439 static ctl_lun_error_pattern
12440 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12441 {
12442 	const struct ctl_cmd_entry *entry;
12443 	ctl_lun_error_pattern filtered_pattern, pattern;
12444 
12445 	pattern = desc->error_pattern;
12446 
12447 	/*
12448 	 * XXX KDM we need more data passed into this function to match a
12449 	 * custom pattern, and we actually need to implement custom pattern
12450 	 * matching.
12451 	 */
12452 	if (pattern & CTL_LUN_PAT_CMD)
12453 		return (CTL_LUN_PAT_CMD);
12454 
12455 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12456 		return (CTL_LUN_PAT_ANY);
12457 
12458 	entry = ctl_get_cmd_entry(ctsio, NULL);
12459 
12460 	filtered_pattern = entry->pattern & pattern;
12461 
12462 	/*
12463 	 * If the user requested specific flags in the pattern (e.g.
12464 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12465 	 * flags.
12466 	 *
12467 	 * If the user did not specify any flags, it doesn't matter whether
12468 	 * or not the command supports the flags.
12469 	 */
12470 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12471 	     (pattern & ~CTL_LUN_PAT_MASK))
12472 		return (CTL_LUN_PAT_NONE);
12473 
12474 	/*
12475 	 * If the user asked for a range check, see if the requested LBA
12476 	 * range overlaps with this command's LBA range.
12477 	 */
12478 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12479 		uint64_t lba1;
12480 		uint64_t len1;
12481 		ctl_action action;
12482 		int retval;
12483 
12484 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12485 		if (retval != 0)
12486 			return (CTL_LUN_PAT_NONE);
12487 
12488 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12489 					      desc->lba_range.len, FALSE);
12490 		/*
12491 		 * A "pass" means that the LBA ranges don't overlap, so
12492 		 * this doesn't match the user's range criteria.
12493 		 */
12494 		if (action == CTL_ACTION_PASS)
12495 			return (CTL_LUN_PAT_NONE);
12496 	}
12497 
12498 	return (filtered_pattern);
12499 }
12500 
12501 static void
12502 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12503 {
12504 	struct ctl_error_desc *desc, *desc2;
12505 
12506 	mtx_assert(&lun->lun_lock, MA_OWNED);
12507 
12508 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12509 		ctl_lun_error_pattern pattern;
12510 		/*
12511 		 * Check to see whether this particular command matches
12512 		 * the pattern in the descriptor.
12513 		 */
12514 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12515 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12516 			continue;
12517 
12518 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12519 		case CTL_LUN_INJ_ABORTED:
12520 			ctl_set_aborted(&io->scsiio);
12521 			break;
12522 		case CTL_LUN_INJ_MEDIUM_ERR:
12523 			ctl_set_medium_error(&io->scsiio,
12524 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12525 			     CTL_FLAG_DATA_OUT);
12526 			break;
12527 		case CTL_LUN_INJ_UA:
12528 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12529 			 * OCCURRED */
12530 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12531 			break;
12532 		case CTL_LUN_INJ_CUSTOM:
12533 			/*
12534 			 * We're assuming the user knows what he is doing.
12535 			 * Just copy the sense information without doing
12536 			 * checks.
12537 			 */
12538 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12539 			      MIN(sizeof(desc->custom_sense),
12540 				  sizeof(io->scsiio.sense_data)));
12541 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12542 			io->scsiio.sense_len = SSD_FULL_SIZE;
12543 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12544 			break;
12545 		case CTL_LUN_INJ_NONE:
12546 		default:
12547 			/*
12548 			 * If this is an error injection type we don't know
12549 			 * about, clear the continuous flag (if it is set)
12550 			 * so it will get deleted below.
12551 			 */
12552 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12553 			break;
12554 		}
12555 		/*
12556 		 * By default, each error injection action is a one-shot
12557 		 */
12558 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12559 			continue;
12560 
12561 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12562 
12563 		free(desc, M_CTL);
12564 	}
12565 }
12566 
12567 #ifdef CTL_IO_DELAY
12568 static void
12569 ctl_datamove_timer_wakeup(void *arg)
12570 {
12571 	union ctl_io *io;
12572 
12573 	io = (union ctl_io *)arg;
12574 
12575 	ctl_datamove(io);
12576 }
12577 #endif /* CTL_IO_DELAY */
12578 
12579 void
12580 ctl_datamove(union ctl_io *io)
12581 {
12582 	void (*fe_datamove)(union ctl_io *io);
12583 
12584 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12585 
12586 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12587 
12588 #ifdef CTL_TIME_IO
12589 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12590 		char str[256];
12591 		char path_str[64];
12592 		struct sbuf sb;
12593 
12594 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12595 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12596 
12597 		sbuf_cat(&sb, path_str);
12598 		switch (io->io_hdr.io_type) {
12599 		case CTL_IO_SCSI:
12600 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12601 			sbuf_printf(&sb, "\n");
12602 			sbuf_cat(&sb, path_str);
12603 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12604 				    io->scsiio.tag_num, io->scsiio.tag_type);
12605 			break;
12606 		case CTL_IO_TASK:
12607 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12608 				    "Tag Type: %d\n", io->taskio.task_action,
12609 				    io->taskio.tag_num, io->taskio.tag_type);
12610 			break;
12611 		default:
12612 			panic("%s: Invalid CTL I/O type %d\n",
12613 			    __func__, io->io_hdr.io_type);
12614 		}
12615 		sbuf_cat(&sb, path_str);
12616 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12617 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12618 		sbuf_finish(&sb);
12619 		printf("%s", sbuf_data(&sb));
12620 	}
12621 #endif /* CTL_TIME_IO */
12622 
12623 #ifdef CTL_IO_DELAY
12624 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12625 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12626 	} else {
12627 		if ((lun != NULL)
12628 		 && (lun->delay_info.datamove_delay > 0)) {
12629 
12630 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12631 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12632 			callout_reset(&io->io_hdr.delay_callout,
12633 				      lun->delay_info.datamove_delay * hz,
12634 				      ctl_datamove_timer_wakeup, io);
12635 			if (lun->delay_info.datamove_type ==
12636 			    CTL_DELAY_TYPE_ONESHOT)
12637 				lun->delay_info.datamove_delay = 0;
12638 			return;
12639 		}
12640 	}
12641 #endif
12642 
12643 	/*
12644 	 * This command has been aborted.  Set the port status, so we fail
12645 	 * the data move.
12646 	 */
12647 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12648 		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12649 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12650 		       io->io_hdr.nexus.targ_port,
12651 		       io->io_hdr.nexus.targ_lun);
12652 		io->io_hdr.port_status = 31337;
12653 		/*
12654 		 * Note that the backend, in this case, will get the
12655 		 * callback in its context.  In other cases it may get
12656 		 * called in the frontend's interrupt thread context.
12657 		 */
12658 		io->scsiio.be_move_done(io);
12659 		return;
12660 	}
12661 
12662 	/* Don't confuse frontend with zero length data move. */
12663 	if (io->scsiio.kern_data_len == 0) {
12664 		io->scsiio.be_move_done(io);
12665 		return;
12666 	}
12667 
12668 	fe_datamove = CTL_PORT(io)->fe_datamove;
12669 	fe_datamove(io);
12670 }
12671 
12672 static void
12673 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12674 {
12675 	union ctl_ha_msg msg;
12676 #ifdef CTL_TIME_IO
12677 	struct bintime cur_bt;
12678 #endif
12679 
12680 	memset(&msg, 0, sizeof(msg));
12681 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12682 	msg.hdr.original_sc = io;
12683 	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12684 	msg.hdr.nexus = io->io_hdr.nexus;
12685 	msg.hdr.status = io->io_hdr.status;
12686 	msg.scsi.tag_num = io->scsiio.tag_num;
12687 	msg.scsi.tag_type = io->scsiio.tag_type;
12688 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12689 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12690 	       io->scsiio.sense_len);
12691 	msg.scsi.sense_len = io->scsiio.sense_len;
12692 	msg.scsi.sense_residual = io->scsiio.sense_residual;
12693 	msg.scsi.fetd_status = io->io_hdr.port_status;
12694 	msg.scsi.residual = io->scsiio.residual;
12695 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12696 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12697 		ctl_failover_io(io, /*have_lock*/ have_lock);
12698 		return;
12699 	}
12700 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12701 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12702 	    msg.scsi.sense_len, M_WAITOK);
12703 
12704 #ifdef CTL_TIME_IO
12705 	getbinuptime(&cur_bt);
12706 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12707 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12708 #endif
12709 	io->io_hdr.num_dmas++;
12710 }
12711 
12712 /*
12713  * The DMA to the remote side is done, now we need to tell the other side
12714  * we're done so it can continue with its data movement.
12715  */
12716 static void
12717 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12718 {
12719 	union ctl_io *io;
12720 	uint32_t i;
12721 
12722 	io = rq->context;
12723 
12724 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12725 		printf("%s: ISC DMA write failed with error %d", __func__,
12726 		       rq->ret);
12727 		ctl_set_internal_failure(&io->scsiio,
12728 					 /*sks_valid*/ 1,
12729 					 /*retry_count*/ rq->ret);
12730 	}
12731 
12732 	ctl_dt_req_free(rq);
12733 
12734 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12735 		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12736 	free(io->io_hdr.remote_sglist, M_CTL);
12737 	io->io_hdr.remote_sglist = NULL;
12738 	io->io_hdr.local_sglist = NULL;
12739 
12740 	/*
12741 	 * The data is in local and remote memory, so now we need to send
12742 	 * status (good or back) back to the other side.
12743 	 */
12744 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12745 }
12746 
12747 /*
12748  * We've moved the data from the host/controller into local memory.  Now we
12749  * need to push it over to the remote controller's memory.
12750  */
12751 static int
12752 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12753 {
12754 	int retval;
12755 
12756 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12757 					  ctl_datamove_remote_write_cb);
12758 	return (retval);
12759 }
12760 
12761 static void
12762 ctl_datamove_remote_write(union ctl_io *io)
12763 {
12764 	int retval;
12765 	void (*fe_datamove)(union ctl_io *io);
12766 
12767 	/*
12768 	 * - Get the data from the host/HBA into local memory.
12769 	 * - DMA memory from the local controller to the remote controller.
12770 	 * - Send status back to the remote controller.
12771 	 */
12772 
12773 	retval = ctl_datamove_remote_sgl_setup(io);
12774 	if (retval != 0)
12775 		return;
12776 
12777 	/* Switch the pointer over so the FETD knows what to do */
12778 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12779 
12780 	/*
12781 	 * Use a custom move done callback, since we need to send completion
12782 	 * back to the other controller, not to the backend on this side.
12783 	 */
12784 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12785 
12786 	fe_datamove = CTL_PORT(io)->fe_datamove;
12787 	fe_datamove(io);
12788 }
12789 
12790 static int
12791 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12792 {
12793 #if 0
12794 	char str[256];
12795 	char path_str[64];
12796 	struct sbuf sb;
12797 #endif
12798 	uint32_t i;
12799 
12800 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12801 		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12802 	free(io->io_hdr.remote_sglist, M_CTL);
12803 	io->io_hdr.remote_sglist = NULL;
12804 	io->io_hdr.local_sglist = NULL;
12805 
12806 #if 0
12807 	scsi_path_string(io, path_str, sizeof(path_str));
12808 	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12809 	sbuf_cat(&sb, path_str);
12810 	scsi_command_string(&io->scsiio, NULL, &sb);
12811 	sbuf_printf(&sb, "\n");
12812 	sbuf_cat(&sb, path_str);
12813 	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12814 		    io->scsiio.tag_num, io->scsiio.tag_type);
12815 	sbuf_cat(&sb, path_str);
12816 	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12817 		    io->io_hdr.flags, io->io_hdr.status);
12818 	sbuf_finish(&sb);
12819 	printk("%s", sbuf_data(&sb));
12820 #endif
12821 
12822 
12823 	/*
12824 	 * The read is done, now we need to send status (good or bad) back
12825 	 * to the other side.
12826 	 */
12827 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12828 
12829 	return (0);
12830 }
12831 
12832 static void
12833 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12834 {
12835 	union ctl_io *io;
12836 	void (*fe_datamove)(union ctl_io *io);
12837 
12838 	io = rq->context;
12839 
12840 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12841 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12842 		       rq->ret);
12843 		ctl_set_internal_failure(&io->scsiio,
12844 					 /*sks_valid*/ 1,
12845 					 /*retry_count*/ rq->ret);
12846 	}
12847 
12848 	ctl_dt_req_free(rq);
12849 
12850 	/* Switch the pointer over so the FETD knows what to do */
12851 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12852 
12853 	/*
12854 	 * Use a custom move done callback, since we need to send completion
12855 	 * back to the other controller, not to the backend on this side.
12856 	 */
12857 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12858 
12859 	/* XXX KDM add checks like the ones in ctl_datamove? */
12860 
12861 	fe_datamove = CTL_PORT(io)->fe_datamove;
12862 	fe_datamove(io);
12863 }
12864 
12865 static int
12866 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12867 {
12868 	struct ctl_sg_entry *local_sglist;
12869 	uint32_t len_to_go;
12870 	int retval;
12871 	int i;
12872 
12873 	retval = 0;
12874 	local_sglist = io->io_hdr.local_sglist;
12875 	len_to_go = io->scsiio.kern_data_len;
12876 
12877 	/*
12878 	 * The difficult thing here is that the size of the various
12879 	 * S/G segments may be different than the size from the
12880 	 * remote controller.  That'll make it harder when DMAing
12881 	 * the data back to the other side.
12882 	 */
12883 	for (i = 0; len_to_go > 0; i++) {
12884 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12885 		local_sglist[i].addr =
12886 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12887 
12888 		len_to_go -= local_sglist[i].len;
12889 	}
12890 	/*
12891 	 * Reset the number of S/G entries accordingly.  The original
12892 	 * number of S/G entries is available in rem_sg_entries.
12893 	 */
12894 	io->scsiio.kern_sg_entries = i;
12895 
12896 #if 0
12897 	printf("%s: kern_sg_entries = %d\n", __func__,
12898 	       io->scsiio.kern_sg_entries);
12899 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12900 		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12901 		       local_sglist[i].addr, local_sglist[i].len);
12902 #endif
12903 
12904 	return (retval);
12905 }
12906 
12907 static int
12908 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12909 			 ctl_ha_dt_cb callback)
12910 {
12911 	struct ctl_ha_dt_req *rq;
12912 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12913 	uint32_t local_used, remote_used, total_used;
12914 	int i, j, isc_ret;
12915 
12916 	rq = ctl_dt_req_alloc();
12917 
12918 	/*
12919 	 * If we failed to allocate the request, and if the DMA didn't fail
12920 	 * anyway, set busy status.  This is just a resource allocation
12921 	 * failure.
12922 	 */
12923 	if ((rq == NULL)
12924 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12925 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12926 		ctl_set_busy(&io->scsiio);
12927 
12928 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12929 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12930 
12931 		if (rq != NULL)
12932 			ctl_dt_req_free(rq);
12933 
12934 		/*
12935 		 * The data move failed.  We need to return status back
12936 		 * to the other controller.  No point in trying to DMA
12937 		 * data to the remote controller.
12938 		 */
12939 
12940 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12941 
12942 		return (1);
12943 	}
12944 
12945 	local_sglist = io->io_hdr.local_sglist;
12946 	remote_sglist = io->io_hdr.remote_sglist;
12947 	local_used = 0;
12948 	remote_used = 0;
12949 	total_used = 0;
12950 
12951 	/*
12952 	 * Pull/push the data over the wire from/to the other controller.
12953 	 * This takes into account the possibility that the local and
12954 	 * remote sglists may not be identical in terms of the size of
12955 	 * the elements and the number of elements.
12956 	 *
12957 	 * One fundamental assumption here is that the length allocated for
12958 	 * both the local and remote sglists is identical.  Otherwise, we've
12959 	 * essentially got a coding error of some sort.
12960 	 */
12961 	isc_ret = CTL_HA_STATUS_SUCCESS;
12962 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12963 		uint32_t cur_len;
12964 		uint8_t *tmp_ptr;
12965 
12966 		rq->command = command;
12967 		rq->context = io;
12968 
12969 		/*
12970 		 * Both pointers should be aligned.  But it is possible
12971 		 * that the allocation length is not.  They should both
12972 		 * also have enough slack left over at the end, though,
12973 		 * to round up to the next 8 byte boundary.
12974 		 */
12975 		cur_len = MIN(local_sglist[i].len - local_used,
12976 			      remote_sglist[j].len - remote_used);
12977 		rq->size = cur_len;
12978 
12979 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12980 		tmp_ptr += local_used;
12981 
12982 #if 0
12983 		/* Use physical addresses when talking to ISC hardware */
12984 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12985 			/* XXX KDM use busdma */
12986 			rq->local = vtophys(tmp_ptr);
12987 		} else
12988 			rq->local = tmp_ptr;
12989 #else
12990 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12991 		    ("HA does not support BUS_ADDR"));
12992 		rq->local = tmp_ptr;
12993 #endif
12994 
12995 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12996 		tmp_ptr += remote_used;
12997 		rq->remote = tmp_ptr;
12998 
12999 		rq->callback = NULL;
13000 
13001 		local_used += cur_len;
13002 		if (local_used >= local_sglist[i].len) {
13003 			i++;
13004 			local_used = 0;
13005 		}
13006 
13007 		remote_used += cur_len;
13008 		if (remote_used >= remote_sglist[j].len) {
13009 			j++;
13010 			remote_used = 0;
13011 		}
13012 		total_used += cur_len;
13013 
13014 		if (total_used >= io->scsiio.kern_data_len)
13015 			rq->callback = callback;
13016 
13017 #if 0
13018 		printf("%s: %s: local %p remote %p size %d\n", __func__,
13019 		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13020 		       rq->local, rq->remote, rq->size);
13021 #endif
13022 
13023 		isc_ret = ctl_dt_single(rq);
13024 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
13025 			break;
13026 	}
13027 	if (isc_ret != CTL_HA_STATUS_WAIT) {
13028 		rq->ret = isc_ret;
13029 		callback(rq);
13030 	}
13031 
13032 	return (0);
13033 }
13034 
13035 static void
13036 ctl_datamove_remote_read(union ctl_io *io)
13037 {
13038 	int retval;
13039 	uint32_t i;
13040 
13041 	/*
13042 	 * This will send an error to the other controller in the case of a
13043 	 * failure.
13044 	 */
13045 	retval = ctl_datamove_remote_sgl_setup(io);
13046 	if (retval != 0)
13047 		return;
13048 
13049 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13050 					  ctl_datamove_remote_read_cb);
13051 	if (retval != 0) {
13052 		/*
13053 		 * Make sure we free memory if there was an error..  The
13054 		 * ctl_datamove_remote_xfer() function will send the
13055 		 * datamove done message, or call the callback with an
13056 		 * error if there is a problem.
13057 		 */
13058 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13059 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13060 		free(io->io_hdr.remote_sglist, M_CTL);
13061 		io->io_hdr.remote_sglist = NULL;
13062 		io->io_hdr.local_sglist = NULL;
13063 	}
13064 }
13065 
13066 /*
13067  * Process a datamove request from the other controller.  This is used for
13068  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13069  * first.  Once that is complete, the data gets DMAed into the remote
13070  * controller's memory.  For reads, we DMA from the remote controller's
13071  * memory into our memory first, and then move it out to the FETD.
13072  */
13073 static void
13074 ctl_datamove_remote(union ctl_io *io)
13075 {
13076 
13077 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
13078 
13079 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13080 		ctl_failover_io(io, /*have_lock*/ 0);
13081 		return;
13082 	}
13083 
13084 	/*
13085 	 * Note that we look for an aborted I/O here, but don't do some of
13086 	 * the other checks that ctl_datamove() normally does.
13087 	 * We don't need to run the datamove delay code, since that should
13088 	 * have been done if need be on the other controller.
13089 	 */
13090 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13091 		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13092 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13093 		       io->io_hdr.nexus.targ_port,
13094 		       io->io_hdr.nexus.targ_lun);
13095 		io->io_hdr.port_status = 31338;
13096 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13097 		return;
13098 	}
13099 
13100 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13101 		ctl_datamove_remote_write(io);
13102 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13103 		ctl_datamove_remote_read(io);
13104 	else {
13105 		io->io_hdr.port_status = 31339;
13106 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13107 	}
13108 }
13109 
13110 static void
13111 ctl_process_done(union ctl_io *io)
13112 {
13113 	struct ctl_softc *softc = CTL_SOFTC(io);
13114 	struct ctl_port *port = CTL_PORT(io);
13115 	struct ctl_lun *lun = CTL_LUN(io);
13116 	void (*fe_done)(union ctl_io *io);
13117 	union ctl_ha_msg msg;
13118 
13119 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13120 	fe_done = port->fe_done;
13121 
13122 #ifdef CTL_TIME_IO
13123 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13124 		char str[256];
13125 		char path_str[64];
13126 		struct sbuf sb;
13127 
13128 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13129 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13130 
13131 		sbuf_cat(&sb, path_str);
13132 		switch (io->io_hdr.io_type) {
13133 		case CTL_IO_SCSI:
13134 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13135 			sbuf_printf(&sb, "\n");
13136 			sbuf_cat(&sb, path_str);
13137 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13138 				    io->scsiio.tag_num, io->scsiio.tag_type);
13139 			break;
13140 		case CTL_IO_TASK:
13141 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13142 				    "Tag Type: %d\n", io->taskio.task_action,
13143 				    io->taskio.tag_num, io->taskio.tag_type);
13144 			break;
13145 		default:
13146 			panic("%s: Invalid CTL I/O type %d\n",
13147 			    __func__, io->io_hdr.io_type);
13148 		}
13149 		sbuf_cat(&sb, path_str);
13150 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13151 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13152 		sbuf_finish(&sb);
13153 		printf("%s", sbuf_data(&sb));
13154 	}
13155 #endif /* CTL_TIME_IO */
13156 
13157 	switch (io->io_hdr.io_type) {
13158 	case CTL_IO_SCSI:
13159 		break;
13160 	case CTL_IO_TASK:
13161 		if (ctl_debug & CTL_DEBUG_INFO)
13162 			ctl_io_error_print(io, NULL);
13163 		fe_done(io);
13164 		return;
13165 	default:
13166 		panic("%s: Invalid CTL I/O type %d\n",
13167 		    __func__, io->io_hdr.io_type);
13168 	}
13169 
13170 	if (lun == NULL) {
13171 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13172 				 io->io_hdr.nexus.targ_mapped_lun));
13173 		goto bailout;
13174 	}
13175 
13176 	mtx_lock(&lun->lun_lock);
13177 
13178 	/*
13179 	 * Check to see if we have any informational exception and status
13180 	 * of this command can be modified to report it in form of either
13181 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
13182 	 */
13183 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
13184 	    io->io_hdr.status == CTL_SUCCESS &&
13185 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
13186 		uint8_t mrie = lun->MODE_IE.mrie;
13187 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
13188 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
13189 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
13190 		     mrie == SIEP_MRIE_REC_UNCOND ||
13191 		     mrie == SIEP_MRIE_NO_SENSE) &&
13192 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
13193 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
13194 			ctl_set_sense(&io->scsiio,
13195 			      /*current_error*/ 1,
13196 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
13197 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
13198 			      /*asc*/ lun->ie_asc,
13199 			      /*ascq*/ lun->ie_ascq,
13200 			      SSD_ELEM_NONE);
13201 			lun->ie_reported = 1;
13202 		}
13203 	} else if (lun->ie_reported < 0)
13204 		lun->ie_reported = 0;
13205 
13206 	/*
13207 	 * Check to see if we have any errors to inject here.  We only
13208 	 * inject errors for commands that don't already have errors set.
13209 	 */
13210 	if (!STAILQ_EMPTY(&lun->error_list) &&
13211 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13212 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13213 		ctl_inject_error(lun, io);
13214 
13215 	/*
13216 	 * XXX KDM how do we treat commands that aren't completed
13217 	 * successfully?
13218 	 *
13219 	 * XXX KDM should we also track I/O latency?
13220 	 */
13221 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13222 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13223 		int type;
13224 #ifdef CTL_TIME_IO
13225 		struct bintime bt;
13226 
13227 		getbinuptime(&bt);
13228 		bintime_sub(&bt, &io->io_hdr.start_bt);
13229 #endif
13230 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13231 		    CTL_FLAG_DATA_IN)
13232 			type = CTL_STATS_READ;
13233 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13234 		    CTL_FLAG_DATA_OUT)
13235 			type = CTL_STATS_WRITE;
13236 		else
13237 			type = CTL_STATS_NO_IO;
13238 
13239 #ifdef CTL_LEGACY_STATS
13240 		uint32_t targ_port = port->targ_port;
13241 		lun->legacy_stats.ports[targ_port].bytes[type] +=
13242 		    io->scsiio.kern_total_len;
13243 		lun->legacy_stats.ports[targ_port].operations[type] ++;
13244 		lun->legacy_stats.ports[targ_port].num_dmas[type] +=
13245 		    io->io_hdr.num_dmas;
13246 #ifdef CTL_TIME_IO
13247 		bintime_add(&lun->legacy_stats.ports[targ_port].dma_time[type],
13248 		   &io->io_hdr.dma_bt);
13249 		bintime_add(&lun->legacy_stats.ports[targ_port].time[type],
13250 		    &bt);
13251 #endif
13252 #endif /* CTL_LEGACY_STATS */
13253 
13254 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
13255 		lun->stats.operations[type] ++;
13256 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13257 #ifdef CTL_TIME_IO
13258 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13259 		bintime_add(&lun->stats.time[type], &bt);
13260 #endif
13261 
13262 		mtx_lock(&port->port_lock);
13263 		port->stats.bytes[type] += io->scsiio.kern_total_len;
13264 		port->stats.operations[type] ++;
13265 		port->stats.dmas[type] += io->io_hdr.num_dmas;
13266 #ifdef CTL_TIME_IO
13267 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13268 		bintime_add(&port->stats.time[type], &bt);
13269 #endif
13270 		mtx_unlock(&port->port_lock);
13271 	}
13272 
13273 	/*
13274 	 * Remove this from the OOA queue.
13275 	 */
13276 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13277 #ifdef CTL_TIME_IO
13278 	if (TAILQ_EMPTY(&lun->ooa_queue))
13279 		lun->last_busy = getsbinuptime();
13280 #endif
13281 
13282 	/*
13283 	 * Run through the blocked queue on this LUN and see if anything
13284 	 * has become unblocked, now that this transaction is done.
13285 	 */
13286 	ctl_check_blocked(lun);
13287 
13288 	/*
13289 	 * If the LUN has been invalidated, free it if there is nothing
13290 	 * left on its OOA queue.
13291 	 */
13292 	if ((lun->flags & CTL_LUN_INVALID)
13293 	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13294 		mtx_unlock(&lun->lun_lock);
13295 		mtx_lock(&softc->ctl_lock);
13296 		ctl_free_lun(lun);
13297 		mtx_unlock(&softc->ctl_lock);
13298 	} else
13299 		mtx_unlock(&lun->lun_lock);
13300 
13301 bailout:
13302 
13303 	/*
13304 	 * If this command has been aborted, make sure we set the status
13305 	 * properly.  The FETD is responsible for freeing the I/O and doing
13306 	 * whatever it needs to do to clean up its state.
13307 	 */
13308 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13309 		ctl_set_task_aborted(&io->scsiio);
13310 
13311 	/*
13312 	 * If enabled, print command error status.
13313 	 */
13314 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13315 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13316 		ctl_io_error_print(io, NULL);
13317 
13318 	/*
13319 	 * Tell the FETD or the other shelf controller we're done with this
13320 	 * command.  Note that only SCSI commands get to this point.  Task
13321 	 * management commands are completed above.
13322 	 */
13323 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13324 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13325 		memset(&msg, 0, sizeof(msg));
13326 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13327 		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13328 		msg.hdr.nexus = io->io_hdr.nexus;
13329 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13330 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13331 		    M_WAITOK);
13332 	}
13333 
13334 	fe_done(io);
13335 }
13336 
13337 #ifdef CTL_WITH_CA
13338 /*
13339  * Front end should call this if it doesn't do autosense.  When the request
13340  * sense comes back in from the initiator, we'll dequeue this and send it.
13341  */
13342 int
13343 ctl_queue_sense(union ctl_io *io)
13344 {
13345 	struct ctl_softc *softc = CTL_SOFTC(io);
13346 	struct ctl_port *port = CTL_PORT(io);
13347 	struct ctl_lun *lun;
13348 	uint32_t initidx, targ_lun;
13349 
13350 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13351 
13352 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13353 
13354 	/*
13355 	 * LUN lookup will likely move to the ctl_work_thread() once we
13356 	 * have our new queueing infrastructure (that doesn't put things on
13357 	 * a per-LUN queue initially).  That is so that we can handle
13358 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13359 	 * can't deal with that right now.
13360 	 * If we don't have a LUN for this, just toss the sense information.
13361 	 */
13362 	mtx_lock(&softc->ctl_lock);
13363 	if (targ_lun >= CTL_MAX_LUNS ||
13364 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13365 		mtx_unlock(&softc->ctl_lock);
13366 		goto bailout;
13367 	}
13368 	mtx_lock(&lun->lun_lock);
13369 	mtx_unlock(&softc->ctl_lock);
13370 
13371 	/*
13372 	 * Already have CA set for this LUN...toss the sense information.
13373 	 */
13374 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13375 	if (ctl_is_set(lun->have_ca, initidx)) {
13376 		mtx_unlock(&lun->lun_lock);
13377 		goto bailout;
13378 	}
13379 
13380 	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13381 	       MIN(sizeof(lun->pending_sense[initidx]),
13382 	       sizeof(io->scsiio.sense_data)));
13383 	ctl_set_mask(lun->have_ca, initidx);
13384 	mtx_unlock(&lun->lun_lock);
13385 
13386 bailout:
13387 	ctl_free_io(io);
13388 	return (CTL_RETVAL_COMPLETE);
13389 }
13390 #endif
13391 
13392 /*
13393  * Primary command inlet from frontend ports.  All SCSI and task I/O
13394  * requests must go through this function.
13395  */
13396 int
13397 ctl_queue(union ctl_io *io)
13398 {
13399 	struct ctl_port *port = CTL_PORT(io);
13400 
13401 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13402 
13403 #ifdef CTL_TIME_IO
13404 	io->io_hdr.start_time = time_uptime;
13405 	getbinuptime(&io->io_hdr.start_bt);
13406 #endif /* CTL_TIME_IO */
13407 
13408 	/* Map FE-specific LUN ID into global one. */
13409 	io->io_hdr.nexus.targ_mapped_lun =
13410 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13411 
13412 	switch (io->io_hdr.io_type) {
13413 	case CTL_IO_SCSI:
13414 	case CTL_IO_TASK:
13415 		if (ctl_debug & CTL_DEBUG_CDB)
13416 			ctl_io_print(io);
13417 		ctl_enqueue_incoming(io);
13418 		break;
13419 	default:
13420 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13421 		return (EINVAL);
13422 	}
13423 
13424 	return (CTL_RETVAL_COMPLETE);
13425 }
13426 
13427 #ifdef CTL_IO_DELAY
13428 static void
13429 ctl_done_timer_wakeup(void *arg)
13430 {
13431 	union ctl_io *io;
13432 
13433 	io = (union ctl_io *)arg;
13434 	ctl_done(io);
13435 }
13436 #endif /* CTL_IO_DELAY */
13437 
13438 void
13439 ctl_serseq_done(union ctl_io *io)
13440 {
13441 	struct ctl_lun *lun = CTL_LUN(io);;
13442 
13443 	if (lun->be_lun == NULL ||
13444 	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13445 		return;
13446 	mtx_lock(&lun->lun_lock);
13447 	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13448 	ctl_check_blocked(lun);
13449 	mtx_unlock(&lun->lun_lock);
13450 }
13451 
13452 void
13453 ctl_done(union ctl_io *io)
13454 {
13455 
13456 	/*
13457 	 * Enable this to catch duplicate completion issues.
13458 	 */
13459 #if 0
13460 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13461 		printf("%s: type %d msg %d cdb %x iptl: "
13462 		       "%u:%u:%u tag 0x%04x "
13463 		       "flag %#x status %x\n",
13464 			__func__,
13465 			io->io_hdr.io_type,
13466 			io->io_hdr.msg_type,
13467 			io->scsiio.cdb[0],
13468 			io->io_hdr.nexus.initid,
13469 			io->io_hdr.nexus.targ_port,
13470 			io->io_hdr.nexus.targ_lun,
13471 			(io->io_hdr.io_type ==
13472 			CTL_IO_TASK) ?
13473 			io->taskio.tag_num :
13474 			io->scsiio.tag_num,
13475 		        io->io_hdr.flags,
13476 			io->io_hdr.status);
13477 	} else
13478 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13479 #endif
13480 
13481 	/*
13482 	 * This is an internal copy of an I/O, and should not go through
13483 	 * the normal done processing logic.
13484 	 */
13485 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13486 		return;
13487 
13488 #ifdef CTL_IO_DELAY
13489 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13490 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13491 	} else {
13492 		struct ctl_lun *lun = CTL_LUN(io);
13493 
13494 		if ((lun != NULL)
13495 		 && (lun->delay_info.done_delay > 0)) {
13496 
13497 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13498 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13499 			callout_reset(&io->io_hdr.delay_callout,
13500 				      lun->delay_info.done_delay * hz,
13501 				      ctl_done_timer_wakeup, io);
13502 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13503 				lun->delay_info.done_delay = 0;
13504 			return;
13505 		}
13506 	}
13507 #endif /* CTL_IO_DELAY */
13508 
13509 	ctl_enqueue_done(io);
13510 }
13511 
13512 static void
13513 ctl_work_thread(void *arg)
13514 {
13515 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13516 	struct ctl_softc *softc = thr->ctl_softc;
13517 	union ctl_io *io;
13518 	int retval;
13519 
13520 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13521 
13522 	for (;;) {
13523 		/*
13524 		 * We handle the queues in this order:
13525 		 * - ISC
13526 		 * - done queue (to free up resources, unblock other commands)
13527 		 * - RtR queue
13528 		 * - incoming queue
13529 		 *
13530 		 * If those queues are empty, we break out of the loop and
13531 		 * go to sleep.
13532 		 */
13533 		mtx_lock(&thr->queue_lock);
13534 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13535 		if (io != NULL) {
13536 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13537 			mtx_unlock(&thr->queue_lock);
13538 			ctl_handle_isc(io);
13539 			continue;
13540 		}
13541 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13542 		if (io != NULL) {
13543 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13544 			/* clear any blocked commands, call fe_done */
13545 			mtx_unlock(&thr->queue_lock);
13546 			ctl_process_done(io);
13547 			continue;
13548 		}
13549 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13550 		if (io != NULL) {
13551 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13552 			mtx_unlock(&thr->queue_lock);
13553 			if (io->io_hdr.io_type == CTL_IO_TASK)
13554 				ctl_run_task(io);
13555 			else
13556 				ctl_scsiio_precheck(softc, &io->scsiio);
13557 			continue;
13558 		}
13559 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13560 		if (io != NULL) {
13561 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13562 			mtx_unlock(&thr->queue_lock);
13563 			retval = ctl_scsiio(&io->scsiio);
13564 			if (retval != CTL_RETVAL_COMPLETE)
13565 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13566 			continue;
13567 		}
13568 
13569 		/* Sleep until we have something to do. */
13570 		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13571 	}
13572 }
13573 
13574 static void
13575 ctl_lun_thread(void *arg)
13576 {
13577 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13578 	struct ctl_be_lun *be_lun;
13579 
13580 	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13581 
13582 	for (;;) {
13583 		mtx_lock(&softc->ctl_lock);
13584 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13585 		if (be_lun != NULL) {
13586 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13587 			mtx_unlock(&softc->ctl_lock);
13588 			ctl_create_lun(be_lun);
13589 			continue;
13590 		}
13591 
13592 		/* Sleep until we have something to do. */
13593 		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13594 		    PDROP | PRIBIO, "-", 0);
13595 	}
13596 }
13597 
13598 static void
13599 ctl_thresh_thread(void *arg)
13600 {
13601 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13602 	struct ctl_lun *lun;
13603 	struct ctl_logical_block_provisioning_page *page;
13604 	const char *attr;
13605 	union ctl_ha_msg msg;
13606 	uint64_t thres, val;
13607 	int i, e, set;
13608 
13609 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13610 
13611 	for (;;) {
13612 		mtx_lock(&softc->ctl_lock);
13613 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13614 			if ((lun->flags & CTL_LUN_DISABLED) ||
13615 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13616 			    lun->backend->lun_attr == NULL)
13617 				continue;
13618 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13619 			    softc->ha_mode == CTL_HA_MODE_XFER)
13620 				continue;
13621 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13622 				continue;
13623 			e = 0;
13624 			page = &lun->MODE_LBP;
13625 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13626 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13627 					continue;
13628 				thres = scsi_4btoul(page->descr[i].count);
13629 				thres <<= CTL_LBP_EXPONENT;
13630 				switch (page->descr[i].resource) {
13631 				case 0x01:
13632 					attr = "blocksavail";
13633 					break;
13634 				case 0x02:
13635 					attr = "blocksused";
13636 					break;
13637 				case 0xf1:
13638 					attr = "poolblocksavail";
13639 					break;
13640 				case 0xf2:
13641 					attr = "poolblocksused";
13642 					break;
13643 				default:
13644 					continue;
13645 				}
13646 				mtx_unlock(&softc->ctl_lock); // XXX
13647 				val = lun->backend->lun_attr(
13648 				    lun->be_lun->be_lun, attr);
13649 				mtx_lock(&softc->ctl_lock);
13650 				if (val == UINT64_MAX)
13651 					continue;
13652 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13653 				    == SLBPPD_ARMING_INC)
13654 					e = (val >= thres);
13655 				else
13656 					e = (val <= thres);
13657 				if (e)
13658 					break;
13659 			}
13660 			mtx_lock(&lun->lun_lock);
13661 			if (e) {
13662 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13663 				    (uint8_t *)page, lun->ua_tpt_info);
13664 				if (lun->lasttpt == 0 ||
13665 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13666 					lun->lasttpt = time_uptime;
13667 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13668 					set = 1;
13669 				} else
13670 					set = 0;
13671 			} else {
13672 				lun->lasttpt = 0;
13673 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13674 				set = -1;
13675 			}
13676 			mtx_unlock(&lun->lun_lock);
13677 			if (set != 0 &&
13678 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13679 				/* Send msg to other side. */
13680 				bzero(&msg.ua, sizeof(msg.ua));
13681 				msg.hdr.msg_type = CTL_MSG_UA;
13682 				msg.hdr.nexus.initid = -1;
13683 				msg.hdr.nexus.targ_port = -1;
13684 				msg.hdr.nexus.targ_lun = lun->lun;
13685 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13686 				msg.ua.ua_all = 1;
13687 				msg.ua.ua_set = (set > 0);
13688 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13689 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13690 				mtx_unlock(&softc->ctl_lock); // XXX
13691 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13692 				    sizeof(msg.ua), M_WAITOK);
13693 				mtx_lock(&softc->ctl_lock);
13694 			}
13695 		}
13696 		mtx_unlock(&softc->ctl_lock);
13697 		pause("-", CTL_LBP_PERIOD * hz);
13698 	}
13699 }
13700 
13701 static void
13702 ctl_enqueue_incoming(union ctl_io *io)
13703 {
13704 	struct ctl_softc *softc = CTL_SOFTC(io);
13705 	struct ctl_thread *thr;
13706 	u_int idx;
13707 
13708 	idx = (io->io_hdr.nexus.targ_port * 127 +
13709 	       io->io_hdr.nexus.initid) % worker_threads;
13710 	thr = &softc->threads[idx];
13711 	mtx_lock(&thr->queue_lock);
13712 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13713 	mtx_unlock(&thr->queue_lock);
13714 	wakeup(thr);
13715 }
13716 
13717 static void
13718 ctl_enqueue_rtr(union ctl_io *io)
13719 {
13720 	struct ctl_softc *softc = CTL_SOFTC(io);
13721 	struct ctl_thread *thr;
13722 
13723 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13724 	mtx_lock(&thr->queue_lock);
13725 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13726 	mtx_unlock(&thr->queue_lock);
13727 	wakeup(thr);
13728 }
13729 
13730 static void
13731 ctl_enqueue_done(union ctl_io *io)
13732 {
13733 	struct ctl_softc *softc = CTL_SOFTC(io);
13734 	struct ctl_thread *thr;
13735 
13736 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13737 	mtx_lock(&thr->queue_lock);
13738 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13739 	mtx_unlock(&thr->queue_lock);
13740 	wakeup(thr);
13741 }
13742 
13743 static void
13744 ctl_enqueue_isc(union ctl_io *io)
13745 {
13746 	struct ctl_softc *softc = CTL_SOFTC(io);
13747 	struct ctl_thread *thr;
13748 
13749 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13750 	mtx_lock(&thr->queue_lock);
13751 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13752 	mtx_unlock(&thr->queue_lock);
13753 	wakeup(thr);
13754 }
13755 
13756 /*
13757  *  vim: ts=8
13758  */
13759