xref: /freebsd/sys/cam/ctl/ctl.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
5  * Copyright (c) 2012 The FreeBSD Foundation
6  * Copyright (c) 2014-2017 Alexander Motin <mav@FreeBSD.org>
7  * Copyright (c) 2017 Jakub Wojciech Klama <jceel@FreeBSD.org>
8  * Copyright (c) 2018 Marcelo Araujo <araujo@FreeBSD.org>
9  * All rights reserved.
10  *
11  * Portions of this software were developed by Edward Tomasz Napierala
12  * under sponsorship from the FreeBSD Foundation.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions, and the following disclaimer,
19  *    without modification.
20  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
21  *    substantially similar to the "NO WARRANTY" disclaimer below
22  *    ("Disclaimer") and any redistribution must be conditioned upon
23  *    including a substantially similar Disclaimer requirement for further
24  *    binary redistribution.
25  *
26  * NO WARRANTY
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
35  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
36  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGES.
38  *
39  * $Id$
40  */
41 /*
42  * CAM Target Layer, a SCSI device emulation subsystem.
43  *
44  * Author: Ken Merry <ken@FreeBSD.org>
45  */
46 
47 #include <sys/cdefs.h>
48 __FBSDID("$FreeBSD$");
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/ctype.h>
53 #include <sys/kernel.h>
54 #include <sys/types.h>
55 #include <sys/kthread.h>
56 #include <sys/bio.h>
57 #include <sys/fcntl.h>
58 #include <sys/lock.h>
59 #include <sys/module.h>
60 #include <sys/mutex.h>
61 #include <sys/condvar.h>
62 #include <sys/malloc.h>
63 #include <sys/conf.h>
64 #include <sys/ioccom.h>
65 #include <sys/queue.h>
66 #include <sys/sbuf.h>
67 #include <sys/smp.h>
68 #include <sys/endian.h>
69 #include <sys/sysctl.h>
70 #include <sys/nv.h>
71 #include <sys/dnv.h>
72 #include <vm/uma.h>
73 
74 #include <cam/cam.h>
75 #include <cam/scsi/scsi_all.h>
76 #include <cam/scsi/scsi_cd.h>
77 #include <cam/scsi/scsi_da.h>
78 #include <cam/ctl/ctl_io.h>
79 #include <cam/ctl/ctl.h>
80 #include <cam/ctl/ctl_frontend.h>
81 #include <cam/ctl/ctl_util.h>
82 #include <cam/ctl/ctl_backend.h>
83 #include <cam/ctl/ctl_ioctl.h>
84 #include <cam/ctl/ctl_ha.h>
85 #include <cam/ctl/ctl_private.h>
86 #include <cam/ctl/ctl_debug.h>
87 #include <cam/ctl/ctl_scsi_all.h>
88 #include <cam/ctl/ctl_error.h>
89 
90 struct ctl_softc *control_softc = NULL;
91 
92 /*
93  * Template mode pages.
94  */
95 
96 /*
97  * Note that these are default values only.  The actual values will be
98  * filled in when the user does a mode sense.
99  */
100 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
101 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
102 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
103 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
104 	/*read_retry_count*/0,
105 	/*correction_span*/0,
106 	/*head_offset_count*/0,
107 	/*data_strobe_offset_cnt*/0,
108 	/*byte8*/SMS_RWER_LBPERE,
109 	/*write_retry_count*/0,
110 	/*reserved2*/0,
111 	/*recovery_time_limit*/{0, 0},
112 };
113 
114 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
115 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
116 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
117 	/*byte3*/SMS_RWER_PER,
118 	/*read_retry_count*/0,
119 	/*correction_span*/0,
120 	/*head_offset_count*/0,
121 	/*data_strobe_offset_cnt*/0,
122 	/*byte8*/SMS_RWER_LBPERE,
123 	/*write_retry_count*/0,
124 	/*reserved2*/0,
125 	/*recovery_time_limit*/{0, 0},
126 };
127 
128 const static struct scsi_format_page format_page_default = {
129 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
130 	/*page_length*/sizeof(struct scsi_format_page) - 2,
131 	/*tracks_per_zone*/ {0, 0},
132 	/*alt_sectors_per_zone*/ {0, 0},
133 	/*alt_tracks_per_zone*/ {0, 0},
134 	/*alt_tracks_per_lun*/ {0, 0},
135 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
136 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
137 	/*bytes_per_sector*/ {0, 0},
138 	/*interleave*/ {0, 0},
139 	/*track_skew*/ {0, 0},
140 	/*cylinder_skew*/ {0, 0},
141 	/*flags*/ SFP_HSEC,
142 	/*reserved*/ {0, 0, 0}
143 };
144 
145 const static struct scsi_format_page format_page_changeable = {
146 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
147 	/*page_length*/sizeof(struct scsi_format_page) - 2,
148 	/*tracks_per_zone*/ {0, 0},
149 	/*alt_sectors_per_zone*/ {0, 0},
150 	/*alt_tracks_per_zone*/ {0, 0},
151 	/*alt_tracks_per_lun*/ {0, 0},
152 	/*sectors_per_track*/ {0, 0},
153 	/*bytes_per_sector*/ {0, 0},
154 	/*interleave*/ {0, 0},
155 	/*track_skew*/ {0, 0},
156 	/*cylinder_skew*/ {0, 0},
157 	/*flags*/ 0,
158 	/*reserved*/ {0, 0, 0}
159 };
160 
161 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
162 	/*page_code*/SMS_RIGID_DISK_PAGE,
163 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
164 	/*cylinders*/ {0, 0, 0},
165 	/*heads*/ CTL_DEFAULT_HEADS,
166 	/*start_write_precomp*/ {0, 0, 0},
167 	/*start_reduced_current*/ {0, 0, 0},
168 	/*step_rate*/ {0, 0},
169 	/*landing_zone_cylinder*/ {0, 0, 0},
170 	/*rpl*/ SRDP_RPL_DISABLED,
171 	/*rotational_offset*/ 0,
172 	/*reserved1*/ 0,
173 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
174 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
175 	/*reserved2*/ {0, 0}
176 };
177 
178 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
179 	/*page_code*/SMS_RIGID_DISK_PAGE,
180 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
181 	/*cylinders*/ {0, 0, 0},
182 	/*heads*/ 0,
183 	/*start_write_precomp*/ {0, 0, 0},
184 	/*start_reduced_current*/ {0, 0, 0},
185 	/*step_rate*/ {0, 0},
186 	/*landing_zone_cylinder*/ {0, 0, 0},
187 	/*rpl*/ 0,
188 	/*rotational_offset*/ 0,
189 	/*reserved1*/ 0,
190 	/*rotation_rate*/ {0, 0},
191 	/*reserved2*/ {0, 0}
192 };
193 
194 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
195 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
196 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
197 	/*byte3*/0,
198 	/*read_retry_count*/0,
199 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
200 	/*recovery_time_limit*/{0, 0},
201 };
202 
203 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
204 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
205 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
206 	/*byte3*/SMS_VER_PER,
207 	/*read_retry_count*/0,
208 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
209 	/*recovery_time_limit*/{0, 0},
210 };
211 
212 const static struct scsi_caching_page caching_page_default = {
213 	/*page_code*/SMS_CACHING_PAGE,
214 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
215 	/*flags1*/ SCP_DISC | SCP_WCE,
216 	/*ret_priority*/ 0,
217 	/*disable_pf_transfer_len*/ {0xff, 0xff},
218 	/*min_prefetch*/ {0, 0},
219 	/*max_prefetch*/ {0xff, 0xff},
220 	/*max_pf_ceiling*/ {0xff, 0xff},
221 	/*flags2*/ 0,
222 	/*cache_segments*/ 0,
223 	/*cache_seg_size*/ {0, 0},
224 	/*reserved*/ 0,
225 	/*non_cache_seg_size*/ {0, 0, 0}
226 };
227 
228 const static struct scsi_caching_page caching_page_changeable = {
229 	/*page_code*/SMS_CACHING_PAGE,
230 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
231 	/*flags1*/ SCP_WCE | SCP_RCD,
232 	/*ret_priority*/ 0,
233 	/*disable_pf_transfer_len*/ {0, 0},
234 	/*min_prefetch*/ {0, 0},
235 	/*max_prefetch*/ {0, 0},
236 	/*max_pf_ceiling*/ {0, 0},
237 	/*flags2*/ 0,
238 	/*cache_segments*/ 0,
239 	/*cache_seg_size*/ {0, 0},
240 	/*reserved*/ 0,
241 	/*non_cache_seg_size*/ {0, 0, 0}
242 };
243 
244 const static struct scsi_control_page control_page_default = {
245 	/*page_code*/SMS_CONTROL_MODE_PAGE,
246 	/*page_length*/sizeof(struct scsi_control_page) - 2,
247 	/*rlec*/0,
248 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
249 	/*eca_and_aen*/0,
250 	/*flags4*/SCP_TAS,
251 	/*aen_holdoff_period*/{0, 0},
252 	/*busy_timeout_period*/{0, 0},
253 	/*extended_selftest_completion_time*/{0, 0}
254 };
255 
256 const static struct scsi_control_page control_page_changeable = {
257 	/*page_code*/SMS_CONTROL_MODE_PAGE,
258 	/*page_length*/sizeof(struct scsi_control_page) - 2,
259 	/*rlec*/SCP_DSENSE,
260 	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
261 	/*eca_and_aen*/SCP_SWP,
262 	/*flags4*/0,
263 	/*aen_holdoff_period*/{0, 0},
264 	/*busy_timeout_period*/{0, 0},
265 	/*extended_selftest_completion_time*/{0, 0}
266 };
267 
268 #define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
269 
270 const static struct scsi_control_ext_page control_ext_page_default = {
271 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
272 	/*subpage_code*/0x01,
273 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
274 	/*flags*/0,
275 	/*prio*/0,
276 	/*max_sense*/0
277 };
278 
279 const static struct scsi_control_ext_page control_ext_page_changeable = {
280 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
281 	/*subpage_code*/0x01,
282 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
283 	/*flags*/0,
284 	/*prio*/0,
285 	/*max_sense*/0xff
286 };
287 
288 const static struct scsi_info_exceptions_page ie_page_default = {
289 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
290 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
291 	/*info_flags*/SIEP_FLAGS_EWASC,
292 	/*mrie*/SIEP_MRIE_NO,
293 	/*interval_timer*/{0, 0, 0, 0},
294 	/*report_count*/{0, 0, 0, 1}
295 };
296 
297 const static struct scsi_info_exceptions_page ie_page_changeable = {
298 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
299 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
300 	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
301 	    SIEP_FLAGS_LOGERR,
302 	/*mrie*/0x0f,
303 	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
304 	/*report_count*/{0xff, 0xff, 0xff, 0xff}
305 };
306 
307 #define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
308 
309 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
310 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
311 	/*subpage_code*/0x02,
312 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
313 	/*flags*/0,
314 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
315 	/*descr*/{}},
316 	{{/*flags*/0,
317 	  /*resource*/0x01,
318 	  /*reserved*/{0, 0},
319 	  /*count*/{0, 0, 0, 0}},
320 	 {/*flags*/0,
321 	  /*resource*/0x02,
322 	  /*reserved*/{0, 0},
323 	  /*count*/{0, 0, 0, 0}},
324 	 {/*flags*/0,
325 	  /*resource*/0xf1,
326 	  /*reserved*/{0, 0},
327 	  /*count*/{0, 0, 0, 0}},
328 	 {/*flags*/0,
329 	  /*resource*/0xf2,
330 	  /*reserved*/{0, 0},
331 	  /*count*/{0, 0, 0, 0}}
332 	}
333 };
334 
335 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
336 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
337 	/*subpage_code*/0x02,
338 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
339 	/*flags*/SLBPP_SITUA,
340 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
341 	/*descr*/{}},
342 	{{/*flags*/0,
343 	  /*resource*/0,
344 	  /*reserved*/{0, 0},
345 	  /*count*/{0, 0, 0, 0}},
346 	 {/*flags*/0,
347 	  /*resource*/0,
348 	  /*reserved*/{0, 0},
349 	  /*count*/{0, 0, 0, 0}},
350 	 {/*flags*/0,
351 	  /*resource*/0,
352 	  /*reserved*/{0, 0},
353 	  /*count*/{0, 0, 0, 0}},
354 	 {/*flags*/0,
355 	  /*resource*/0,
356 	  /*reserved*/{0, 0},
357 	  /*count*/{0, 0, 0, 0}}
358 	}
359 };
360 
361 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
362 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
363 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
364 	/*caps1*/0x3f,
365 	/*caps2*/0x00,
366 	/*caps3*/0xf0,
367 	/*caps4*/0x00,
368 	/*caps5*/0x29,
369 	/*caps6*/0x00,
370 	/*obsolete*/{0, 0},
371 	/*nvol_levels*/{0, 0},
372 	/*buffer_size*/{8, 0},
373 	/*obsolete2*/{0, 0},
374 	/*reserved*/0,
375 	/*digital*/0,
376 	/*obsolete3*/0,
377 	/*copy_management*/0,
378 	/*reserved2*/0,
379 	/*rotation_control*/0,
380 	/*cur_write_speed*/0,
381 	/*num_speed_descr*/0,
382 };
383 
384 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
385 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
386 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
387 	/*caps1*/0,
388 	/*caps2*/0,
389 	/*caps3*/0,
390 	/*caps4*/0,
391 	/*caps5*/0,
392 	/*caps6*/0,
393 	/*obsolete*/{0, 0},
394 	/*nvol_levels*/{0, 0},
395 	/*buffer_size*/{0, 0},
396 	/*obsolete2*/{0, 0},
397 	/*reserved*/0,
398 	/*digital*/0,
399 	/*obsolete3*/0,
400 	/*copy_management*/0,
401 	/*reserved2*/0,
402 	/*rotation_control*/0,
403 	/*cur_write_speed*/0,
404 	/*num_speed_descr*/0,
405 };
406 
407 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
408 static int worker_threads = -1;
409 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
410     &worker_threads, 1, "Number of worker threads");
411 static int ctl_debug = CTL_DEBUG_NONE;
412 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
413     &ctl_debug, 0, "Enabled debug flags");
414 static int ctl_lun_map_size = 1024;
415 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
416     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
417 #ifdef  CTL_TIME_IO
418 static int ctl_time_io_secs = CTL_TIME_IO_DEFAULT_SECS;
419 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, time_io_secs, CTLFLAG_RWTUN,
420     &ctl_time_io_secs, 0, "Log requests taking more seconds");
421 #endif
422 
423 /*
424  * Maximum number of LUNs we support.  MUST be a power of 2.
425  */
426 #define	CTL_DEFAULT_MAX_LUNS	1024
427 static int ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
428 TUNABLE_INT("kern.cam.ctl.max_luns", &ctl_max_luns);
429 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_luns, CTLFLAG_RDTUN,
430     &ctl_max_luns, CTL_DEFAULT_MAX_LUNS, "Maximum number of LUNs");
431 
432 /*
433  * Maximum number of ports registered at one time.
434  */
435 #define	CTL_DEFAULT_MAX_PORTS		256
436 static int ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
437 TUNABLE_INT("kern.cam.ctl.max_ports", &ctl_max_ports);
438 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, max_ports, CTLFLAG_RDTUN,
439     &ctl_max_ports, CTL_DEFAULT_MAX_LUNS, "Maximum number of ports");
440 
441 /*
442  * Maximum number of initiators we support.
443  */
444 #define	CTL_MAX_INITIATORS	(CTL_MAX_INIT_PER_PORT * ctl_max_ports)
445 
446 /*
447  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
448  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
449  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
450  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
451  */
452 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
453 
454 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
455 				  int param);
456 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
457 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
458 static int ctl_init(void);
459 static int ctl_shutdown(void);
460 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
461 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
462 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
463 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
464 			      struct ctl_ooa *ooa_hdr,
465 			      struct ctl_ooa_entry *kern_entries);
466 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
467 		     struct thread *td);
468 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
469 			 struct ctl_be_lun *be_lun);
470 static int ctl_free_lun(struct ctl_lun *lun);
471 static void ctl_create_lun(struct ctl_be_lun *be_lun);
472 
473 static int ctl_do_mode_select(union ctl_io *io);
474 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
475 			   uint64_t res_key, uint64_t sa_res_key,
476 			   uint8_t type, uint32_t residx,
477 			   struct ctl_scsiio *ctsio,
478 			   struct scsi_per_res_out *cdb,
479 			   struct scsi_per_res_out_parms* param);
480 static void ctl_pro_preempt_other(struct ctl_lun *lun,
481 				  union ctl_ha_msg *msg);
482 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
483 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
484 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
485 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
486 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
487 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
488 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
489 					 int alloc_len);
490 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
491 					 int alloc_len);
492 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
493 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
494 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
495 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
496 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
497 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
498     bool seq);
499 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
500 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
501     union ctl_io *pending_io, union ctl_io *ooa_io);
502 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
503 				union ctl_io *starting_io);
504 static int ctl_check_blocked(struct ctl_lun *lun);
505 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
506 				const struct ctl_cmd_entry *entry,
507 				struct ctl_scsiio *ctsio);
508 static void ctl_failover_lun(union ctl_io *io);
509 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
510 			       struct ctl_scsiio *ctsio);
511 static int ctl_scsiio(struct ctl_scsiio *ctsio);
512 
513 static int ctl_target_reset(union ctl_io *io);
514 static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
515 			 ctl_ua_type ua_type);
516 static int ctl_lun_reset(union ctl_io *io);
517 static int ctl_abort_task(union ctl_io *io);
518 static int ctl_abort_task_set(union ctl_io *io);
519 static int ctl_query_task(union ctl_io *io, int task_set);
520 static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
521 			      ctl_ua_type ua_type);
522 static int ctl_i_t_nexus_reset(union ctl_io *io);
523 static int ctl_query_async_event(union ctl_io *io);
524 static void ctl_run_task(union ctl_io *io);
525 #ifdef CTL_IO_DELAY
526 static void ctl_datamove_timer_wakeup(void *arg);
527 static void ctl_done_timer_wakeup(void *arg);
528 #endif /* CTL_IO_DELAY */
529 
530 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
531 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
532 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
533 static void ctl_datamove_remote_write(union ctl_io *io);
534 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
535 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
536 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
537 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
538 				    ctl_ha_dt_cb callback);
539 static void ctl_datamove_remote_read(union ctl_io *io);
540 static void ctl_datamove_remote(union ctl_io *io);
541 static void ctl_process_done(union ctl_io *io);
542 static void ctl_lun_thread(void *arg);
543 static void ctl_thresh_thread(void *arg);
544 static void ctl_work_thread(void *arg);
545 static void ctl_enqueue_incoming(union ctl_io *io);
546 static void ctl_enqueue_rtr(union ctl_io *io);
547 static void ctl_enqueue_done(union ctl_io *io);
548 static void ctl_enqueue_isc(union ctl_io *io);
549 static const struct ctl_cmd_entry *
550     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
551 static const struct ctl_cmd_entry *
552     ctl_validate_command(struct ctl_scsiio *ctsio);
553 static int ctl_cmd_applicable(uint8_t lun_type,
554     const struct ctl_cmd_entry *entry);
555 static int ctl_ha_init(void);
556 static int ctl_ha_shutdown(void);
557 
558 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
559 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
560 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
561 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
562 
563 /*
564  * Load the serialization table.  This isn't very pretty, but is probably
565  * the easiest way to do it.
566  */
567 #include "ctl_ser_table.c"
568 
569 /*
570  * We only need to define open, close and ioctl routines for this driver.
571  */
572 static struct cdevsw ctl_cdevsw = {
573 	.d_version =	D_VERSION,
574 	.d_flags =	0,
575 	.d_open =	ctl_open,
576 	.d_close =	ctl_close,
577 	.d_ioctl =	ctl_ioctl,
578 	.d_name =	"ctl",
579 };
580 
581 
582 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
583 
584 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
585 
586 static moduledata_t ctl_moduledata = {
587 	"ctl",
588 	ctl_module_event_handler,
589 	NULL
590 };
591 
592 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
593 MODULE_VERSION(ctl, 1);
594 
595 static struct ctl_frontend ha_frontend =
596 {
597 	.name = "ha",
598 	.init = ctl_ha_init,
599 	.shutdown = ctl_ha_shutdown,
600 };
601 
602 static int
603 ctl_ha_init(void)
604 {
605 	struct ctl_softc *softc = control_softc;
606 
607 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
608 	                    &softc->othersc_pool) != 0)
609 		return (ENOMEM);
610 	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
611 		ctl_pool_free(softc->othersc_pool);
612 		return (EIO);
613 	}
614 	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
615 	    != CTL_HA_STATUS_SUCCESS) {
616 		ctl_ha_msg_destroy(softc);
617 		ctl_pool_free(softc->othersc_pool);
618 		return (EIO);
619 	}
620 	return (0);
621 };
622 
623 static int
624 ctl_ha_shutdown(void)
625 {
626 	struct ctl_softc *softc = control_softc;
627 	struct ctl_port *port;
628 
629 	ctl_ha_msg_shutdown(softc);
630 	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
631 		return (EIO);
632 	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
633 		return (EIO);
634 	ctl_pool_free(softc->othersc_pool);
635 	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
636 		ctl_port_deregister(port);
637 		free(port->port_name, M_CTL);
638 		free(port, M_CTL);
639 	}
640 	return (0);
641 };
642 
643 static void
644 ctl_ha_datamove(union ctl_io *io)
645 {
646 	struct ctl_lun *lun = CTL_LUN(io);
647 	struct ctl_sg_entry *sgl;
648 	union ctl_ha_msg msg;
649 	uint32_t sg_entries_sent;
650 	int do_sg_copy, i, j;
651 
652 	memset(&msg.dt, 0, sizeof(msg.dt));
653 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
654 	msg.hdr.original_sc = io->io_hdr.remote_io;
655 	msg.hdr.serializing_sc = io;
656 	msg.hdr.nexus = io->io_hdr.nexus;
657 	msg.hdr.status = io->io_hdr.status;
658 	msg.dt.flags = io->io_hdr.flags;
659 
660 	/*
661 	 * We convert everything into a S/G list here.  We can't
662 	 * pass by reference, only by value between controllers.
663 	 * So we can't pass a pointer to the S/G list, only as many
664 	 * S/G entries as we can fit in here.  If it's possible for
665 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
666 	 * then we need to break this up into multiple transfers.
667 	 */
668 	if (io->scsiio.kern_sg_entries == 0) {
669 		msg.dt.kern_sg_entries = 1;
670 #if 0
671 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
672 			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
673 		} else {
674 			/* XXX KDM use busdma here! */
675 			msg.dt.sg_list[0].addr =
676 			    (void *)vtophys(io->scsiio.kern_data_ptr);
677 		}
678 #else
679 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
680 		    ("HA does not support BUS_ADDR"));
681 		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
682 #endif
683 		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
684 		do_sg_copy = 0;
685 	} else {
686 		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
687 		do_sg_copy = 1;
688 	}
689 
690 	msg.dt.kern_data_len = io->scsiio.kern_data_len;
691 	msg.dt.kern_total_len = io->scsiio.kern_total_len;
692 	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
693 	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
694 	msg.dt.sg_sequence = 0;
695 
696 	/*
697 	 * Loop until we've sent all of the S/G entries.  On the
698 	 * other end, we'll recompose these S/G entries into one
699 	 * contiguous list before processing.
700 	 */
701 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
702 	    msg.dt.sg_sequence++) {
703 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
704 		    sizeof(msg.dt.sg_list[0])),
705 		    msg.dt.kern_sg_entries - sg_entries_sent);
706 		if (do_sg_copy != 0) {
707 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
708 			for (i = sg_entries_sent, j = 0;
709 			     i < msg.dt.cur_sg_entries; i++, j++) {
710 #if 0
711 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
712 					msg.dt.sg_list[j].addr = sgl[i].addr;
713 				} else {
714 					/* XXX KDM use busdma here! */
715 					msg.dt.sg_list[j].addr =
716 					    (void *)vtophys(sgl[i].addr);
717 				}
718 #else
719 				KASSERT((io->io_hdr.flags &
720 				    CTL_FLAG_BUS_ADDR) == 0,
721 				    ("HA does not support BUS_ADDR"));
722 				msg.dt.sg_list[j].addr = sgl[i].addr;
723 #endif
724 				msg.dt.sg_list[j].len = sgl[i].len;
725 			}
726 		}
727 
728 		sg_entries_sent += msg.dt.cur_sg_entries;
729 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
730 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
731 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
732 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
733 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
734 			io->io_hdr.port_status = 31341;
735 			io->scsiio.be_move_done(io);
736 			return;
737 		}
738 		msg.dt.sent_sg_entries = sg_entries_sent;
739 	}
740 
741 	/*
742 	 * Officially handover the request from us to peer.
743 	 * If failover has just happened, then we must return error.
744 	 * If failover happen just after, then it is not our problem.
745 	 */
746 	if (lun)
747 		mtx_lock(&lun->lun_lock);
748 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
749 		if (lun)
750 			mtx_unlock(&lun->lun_lock);
751 		io->io_hdr.port_status = 31342;
752 		io->scsiio.be_move_done(io);
753 		return;
754 	}
755 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
756 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
757 	if (lun)
758 		mtx_unlock(&lun->lun_lock);
759 }
760 
761 static void
762 ctl_ha_done(union ctl_io *io)
763 {
764 	union ctl_ha_msg msg;
765 
766 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
767 		memset(&msg, 0, sizeof(msg));
768 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
769 		msg.hdr.original_sc = io->io_hdr.remote_io;
770 		msg.hdr.nexus = io->io_hdr.nexus;
771 		msg.hdr.status = io->io_hdr.status;
772 		msg.scsi.scsi_status = io->scsiio.scsi_status;
773 		msg.scsi.tag_num = io->scsiio.tag_num;
774 		msg.scsi.tag_type = io->scsiio.tag_type;
775 		msg.scsi.sense_len = io->scsiio.sense_len;
776 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
777 		    io->scsiio.sense_len);
778 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
779 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
780 		    msg.scsi.sense_len, M_WAITOK);
781 	}
782 	ctl_free_io(io);
783 }
784 
785 static void
786 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
787 			    union ctl_ha_msg *msg_info)
788 {
789 	struct ctl_scsiio *ctsio;
790 
791 	if (msg_info->hdr.original_sc == NULL) {
792 		printf("%s: original_sc == NULL!\n", __func__);
793 		/* XXX KDM now what? */
794 		return;
795 	}
796 
797 	ctsio = &msg_info->hdr.original_sc->scsiio;
798 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
799 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
800 	ctsio->io_hdr.status = msg_info->hdr.status;
801 	ctsio->scsi_status = msg_info->scsi.scsi_status;
802 	ctsio->sense_len = msg_info->scsi.sense_len;
803 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
804 	       msg_info->scsi.sense_len);
805 	ctl_enqueue_isc((union ctl_io *)ctsio);
806 }
807 
808 static void
809 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
810 				union ctl_ha_msg *msg_info)
811 {
812 	struct ctl_scsiio *ctsio;
813 
814 	if (msg_info->hdr.serializing_sc == NULL) {
815 		printf("%s: serializing_sc == NULL!\n", __func__);
816 		/* XXX KDM now what? */
817 		return;
818 	}
819 
820 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
821 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
822 	ctl_enqueue_isc((union ctl_io *)ctsio);
823 }
824 
825 void
826 ctl_isc_announce_lun(struct ctl_lun *lun)
827 {
828 	struct ctl_softc *softc = lun->ctl_softc;
829 	union ctl_ha_msg *msg;
830 	struct ctl_ha_msg_lun_pr_key pr_key;
831 	int i, k;
832 
833 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
834 		return;
835 	mtx_lock(&lun->lun_lock);
836 	i = sizeof(msg->lun);
837 	if (lun->lun_devid)
838 		i += lun->lun_devid->len;
839 	i += sizeof(pr_key) * lun->pr_key_count;
840 alloc:
841 	mtx_unlock(&lun->lun_lock);
842 	msg = malloc(i, M_CTL, M_WAITOK);
843 	mtx_lock(&lun->lun_lock);
844 	k = sizeof(msg->lun);
845 	if (lun->lun_devid)
846 		k += lun->lun_devid->len;
847 	k += sizeof(pr_key) * lun->pr_key_count;
848 	if (i < k) {
849 		free(msg, M_CTL);
850 		i = k;
851 		goto alloc;
852 	}
853 	bzero(&msg->lun, sizeof(msg->lun));
854 	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
855 	msg->hdr.nexus.targ_lun = lun->lun;
856 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
857 	msg->lun.flags = lun->flags;
858 	msg->lun.pr_generation = lun->pr_generation;
859 	msg->lun.pr_res_idx = lun->pr_res_idx;
860 	msg->lun.pr_res_type = lun->pr_res_type;
861 	msg->lun.pr_key_count = lun->pr_key_count;
862 	i = 0;
863 	if (lun->lun_devid) {
864 		msg->lun.lun_devid_len = lun->lun_devid->len;
865 		memcpy(&msg->lun.data[i], lun->lun_devid->data,
866 		    msg->lun.lun_devid_len);
867 		i += msg->lun.lun_devid_len;
868 	}
869 	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
870 		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
871 			continue;
872 		pr_key.pr_iid = k;
873 		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
874 		i += sizeof(pr_key);
875 	}
876 	mtx_unlock(&lun->lun_lock);
877 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
878 	    M_WAITOK);
879 	free(msg, M_CTL);
880 
881 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
882 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
883 			ctl_isc_announce_mode(lun, -1,
884 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
885 			    lun->mode_pages.index[i].subpage);
886 		}
887 	}
888 }
889 
890 void
891 ctl_isc_announce_port(struct ctl_port *port)
892 {
893 	struct ctl_softc *softc = port->ctl_softc;
894 	union ctl_ha_msg *msg;
895 	int i;
896 
897 	if (port->targ_port < softc->port_min ||
898 	    port->targ_port >= softc->port_max ||
899 	    softc->ha_link != CTL_HA_LINK_ONLINE)
900 		return;
901 	i = sizeof(msg->port) + strlen(port->port_name) + 1;
902 	if (port->lun_map)
903 		i += port->lun_map_size * sizeof(uint32_t);
904 	if (port->port_devid)
905 		i += port->port_devid->len;
906 	if (port->target_devid)
907 		i += port->target_devid->len;
908 	if (port->init_devid)
909 		i += port->init_devid->len;
910 	msg = malloc(i, M_CTL, M_WAITOK);
911 	bzero(&msg->port, sizeof(msg->port));
912 	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
913 	msg->hdr.nexus.targ_port = port->targ_port;
914 	msg->port.port_type = port->port_type;
915 	msg->port.physical_port = port->physical_port;
916 	msg->port.virtual_port = port->virtual_port;
917 	msg->port.status = port->status;
918 	i = 0;
919 	msg->port.name_len = sprintf(&msg->port.data[i],
920 	    "%d:%s", softc->ha_id, port->port_name) + 1;
921 	i += msg->port.name_len;
922 	if (port->lun_map) {
923 		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
924 		memcpy(&msg->port.data[i], port->lun_map,
925 		    msg->port.lun_map_len);
926 		i += msg->port.lun_map_len;
927 	}
928 	if (port->port_devid) {
929 		msg->port.port_devid_len = port->port_devid->len;
930 		memcpy(&msg->port.data[i], port->port_devid->data,
931 		    msg->port.port_devid_len);
932 		i += msg->port.port_devid_len;
933 	}
934 	if (port->target_devid) {
935 		msg->port.target_devid_len = port->target_devid->len;
936 		memcpy(&msg->port.data[i], port->target_devid->data,
937 		    msg->port.target_devid_len);
938 		i += msg->port.target_devid_len;
939 	}
940 	if (port->init_devid) {
941 		msg->port.init_devid_len = port->init_devid->len;
942 		memcpy(&msg->port.data[i], port->init_devid->data,
943 		    msg->port.init_devid_len);
944 		i += msg->port.init_devid_len;
945 	}
946 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
947 	    M_WAITOK);
948 	free(msg, M_CTL);
949 }
950 
951 void
952 ctl_isc_announce_iid(struct ctl_port *port, int iid)
953 {
954 	struct ctl_softc *softc = port->ctl_softc;
955 	union ctl_ha_msg *msg;
956 	int i, l;
957 
958 	if (port->targ_port < softc->port_min ||
959 	    port->targ_port >= softc->port_max ||
960 	    softc->ha_link != CTL_HA_LINK_ONLINE)
961 		return;
962 	mtx_lock(&softc->ctl_lock);
963 	i = sizeof(msg->iid);
964 	l = 0;
965 	if (port->wwpn_iid[iid].name)
966 		l = strlen(port->wwpn_iid[iid].name) + 1;
967 	i += l;
968 	msg = malloc(i, M_CTL, M_NOWAIT);
969 	if (msg == NULL) {
970 		mtx_unlock(&softc->ctl_lock);
971 		return;
972 	}
973 	bzero(&msg->iid, sizeof(msg->iid));
974 	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
975 	msg->hdr.nexus.targ_port = port->targ_port;
976 	msg->hdr.nexus.initid = iid;
977 	msg->iid.in_use = port->wwpn_iid[iid].in_use;
978 	msg->iid.name_len = l;
979 	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
980 	if (port->wwpn_iid[iid].name)
981 		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
982 	mtx_unlock(&softc->ctl_lock);
983 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
984 	free(msg, M_CTL);
985 }
986 
987 void
988 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
989     uint8_t page, uint8_t subpage)
990 {
991 	struct ctl_softc *softc = lun->ctl_softc;
992 	union ctl_ha_msg msg;
993 	u_int i;
994 
995 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
996 		return;
997 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
998 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
999 		    page && lun->mode_pages.index[i].subpage == subpage)
1000 			break;
1001 	}
1002 	if (i == CTL_NUM_MODE_PAGES)
1003 		return;
1004 
1005 	/* Don't try to replicate pages not present on this device. */
1006 	if (lun->mode_pages.index[i].page_data == NULL)
1007 		return;
1008 
1009 	bzero(&msg.mode, sizeof(msg.mode));
1010 	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
1011 	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
1012 	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
1013 	msg.hdr.nexus.targ_lun = lun->lun;
1014 	msg.hdr.nexus.targ_mapped_lun = lun->lun;
1015 	msg.mode.page_code = page;
1016 	msg.mode.subpage = subpage;
1017 	msg.mode.page_len = lun->mode_pages.index[i].page_len;
1018 	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
1019 	    msg.mode.page_len);
1020 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
1021 	    M_WAITOK);
1022 }
1023 
1024 static void
1025 ctl_isc_ha_link_up(struct ctl_softc *softc)
1026 {
1027 	struct ctl_port *port;
1028 	struct ctl_lun *lun;
1029 	union ctl_ha_msg msg;
1030 	int i;
1031 
1032 	/* Announce this node parameters to peer for validation. */
1033 	msg.login.msg_type = CTL_MSG_LOGIN;
1034 	msg.login.version = CTL_HA_VERSION;
1035 	msg.login.ha_mode = softc->ha_mode;
1036 	msg.login.ha_id = softc->ha_id;
1037 	msg.login.max_luns = ctl_max_luns;
1038 	msg.login.max_ports = ctl_max_ports;
1039 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1040 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1041 	    M_WAITOK);
1042 
1043 	STAILQ_FOREACH(port, &softc->port_list, links) {
1044 		ctl_isc_announce_port(port);
1045 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1046 			if (port->wwpn_iid[i].in_use)
1047 				ctl_isc_announce_iid(port, i);
1048 		}
1049 	}
1050 	STAILQ_FOREACH(lun, &softc->lun_list, links)
1051 		ctl_isc_announce_lun(lun);
1052 }
1053 
1054 static void
1055 ctl_isc_ha_link_down(struct ctl_softc *softc)
1056 {
1057 	struct ctl_port *port;
1058 	struct ctl_lun *lun;
1059 	union ctl_io *io;
1060 	int i;
1061 
1062 	mtx_lock(&softc->ctl_lock);
1063 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1064 		mtx_lock(&lun->lun_lock);
1065 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1066 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1067 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1068 		}
1069 		mtx_unlock(&lun->lun_lock);
1070 
1071 		mtx_unlock(&softc->ctl_lock);
1072 		io = ctl_alloc_io(softc->othersc_pool);
1073 		mtx_lock(&softc->ctl_lock);
1074 		ctl_zero_io(io);
1075 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1076 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1077 		ctl_enqueue_isc(io);
1078 	}
1079 
1080 	STAILQ_FOREACH(port, &softc->port_list, links) {
1081 		if (port->targ_port >= softc->port_min &&
1082 		    port->targ_port < softc->port_max)
1083 			continue;
1084 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1085 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1086 			port->wwpn_iid[i].in_use = 0;
1087 			free(port->wwpn_iid[i].name, M_CTL);
1088 			port->wwpn_iid[i].name = NULL;
1089 		}
1090 	}
1091 	mtx_unlock(&softc->ctl_lock);
1092 }
1093 
1094 static void
1095 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1096 {
1097 	struct ctl_lun *lun;
1098 	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1099 
1100 	mtx_lock(&softc->ctl_lock);
1101 	if (msg->hdr.nexus.targ_mapped_lun >= ctl_max_luns ||
1102 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1103 		mtx_unlock(&softc->ctl_lock);
1104 		return;
1105 	}
1106 	mtx_lock(&lun->lun_lock);
1107 	mtx_unlock(&softc->ctl_lock);
1108 	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1109 		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1110 	if (msg->ua.ua_all) {
1111 		if (msg->ua.ua_set)
1112 			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1113 		else
1114 			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1115 	} else {
1116 		if (msg->ua.ua_set)
1117 			ctl_est_ua(lun, iid, msg->ua.ua_type);
1118 		else
1119 			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1120 	}
1121 	mtx_unlock(&lun->lun_lock);
1122 }
1123 
1124 static void
1125 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1126 {
1127 	struct ctl_lun *lun;
1128 	struct ctl_ha_msg_lun_pr_key pr_key;
1129 	int i, k;
1130 	ctl_lun_flags oflags;
1131 	uint32_t targ_lun;
1132 
1133 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1134 	mtx_lock(&softc->ctl_lock);
1135 	if (targ_lun >= ctl_max_luns ||
1136 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1137 		mtx_unlock(&softc->ctl_lock);
1138 		return;
1139 	}
1140 	mtx_lock(&lun->lun_lock);
1141 	mtx_unlock(&softc->ctl_lock);
1142 	if (lun->flags & CTL_LUN_DISABLED) {
1143 		mtx_unlock(&lun->lun_lock);
1144 		return;
1145 	}
1146 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1147 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1148 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1149 		mtx_unlock(&lun->lun_lock);
1150 		printf("%s: Received conflicting HA LUN %d\n",
1151 		    __func__, targ_lun);
1152 		return;
1153 	} else {
1154 		/* Record whether peer is primary. */
1155 		oflags = lun->flags;
1156 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1157 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1158 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1159 		else
1160 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1161 		if (oflags != lun->flags)
1162 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1163 
1164 		/* If peer is primary and we are not -- use data */
1165 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1166 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1167 			lun->pr_generation = msg->lun.pr_generation;
1168 			lun->pr_res_idx = msg->lun.pr_res_idx;
1169 			lun->pr_res_type = msg->lun.pr_res_type;
1170 			lun->pr_key_count = msg->lun.pr_key_count;
1171 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1172 				ctl_clr_prkey(lun, k);
1173 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1174 				memcpy(&pr_key, &msg->lun.data[i],
1175 				    sizeof(pr_key));
1176 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1177 				ctl_set_prkey(lun, pr_key.pr_iid,
1178 				    pr_key.pr_key);
1179 				i += sizeof(pr_key);
1180 			}
1181 		}
1182 
1183 		mtx_unlock(&lun->lun_lock);
1184 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1185 		    __func__, targ_lun,
1186 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1187 		    "primary" : "secondary"));
1188 
1189 		/* If we are primary but peer doesn't know -- notify */
1190 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1191 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1192 			ctl_isc_announce_lun(lun);
1193 	}
1194 }
1195 
1196 static void
1197 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1198 {
1199 	struct ctl_port *port;
1200 	struct ctl_lun *lun;
1201 	int i, new;
1202 
1203 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1204 	if (port == NULL) {
1205 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1206 		    msg->hdr.nexus.targ_port));
1207 		new = 1;
1208 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1209 		port->frontend = &ha_frontend;
1210 		port->targ_port = msg->hdr.nexus.targ_port;
1211 		port->fe_datamove = ctl_ha_datamove;
1212 		port->fe_done = ctl_ha_done;
1213 	} else if (port->frontend == &ha_frontend) {
1214 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1215 		    msg->hdr.nexus.targ_port));
1216 		new = 0;
1217 	} else {
1218 		printf("%s: Received conflicting HA port %d\n",
1219 		    __func__, msg->hdr.nexus.targ_port);
1220 		return;
1221 	}
1222 	port->port_type = msg->port.port_type;
1223 	port->physical_port = msg->port.physical_port;
1224 	port->virtual_port = msg->port.virtual_port;
1225 	port->status = msg->port.status;
1226 	i = 0;
1227 	free(port->port_name, M_CTL);
1228 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1229 	    M_CTL);
1230 	i += msg->port.name_len;
1231 	if (msg->port.lun_map_len != 0) {
1232 		if (port->lun_map == NULL ||
1233 		    port->lun_map_size * sizeof(uint32_t) <
1234 		    msg->port.lun_map_len) {
1235 			port->lun_map_size = 0;
1236 			free(port->lun_map, M_CTL);
1237 			port->lun_map = malloc(msg->port.lun_map_len,
1238 			    M_CTL, M_WAITOK);
1239 		}
1240 		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1241 		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1242 		i += msg->port.lun_map_len;
1243 	} else {
1244 		port->lun_map_size = 0;
1245 		free(port->lun_map, M_CTL);
1246 		port->lun_map = NULL;
1247 	}
1248 	if (msg->port.port_devid_len != 0) {
1249 		if (port->port_devid == NULL ||
1250 		    port->port_devid->len < msg->port.port_devid_len) {
1251 			free(port->port_devid, M_CTL);
1252 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1253 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1254 		}
1255 		memcpy(port->port_devid->data, &msg->port.data[i],
1256 		    msg->port.port_devid_len);
1257 		port->port_devid->len = msg->port.port_devid_len;
1258 		i += msg->port.port_devid_len;
1259 	} else {
1260 		free(port->port_devid, M_CTL);
1261 		port->port_devid = NULL;
1262 	}
1263 	if (msg->port.target_devid_len != 0) {
1264 		if (port->target_devid == NULL ||
1265 		    port->target_devid->len < msg->port.target_devid_len) {
1266 			free(port->target_devid, M_CTL);
1267 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1268 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1269 		}
1270 		memcpy(port->target_devid->data, &msg->port.data[i],
1271 		    msg->port.target_devid_len);
1272 		port->target_devid->len = msg->port.target_devid_len;
1273 		i += msg->port.target_devid_len;
1274 	} else {
1275 		free(port->target_devid, M_CTL);
1276 		port->target_devid = NULL;
1277 	}
1278 	if (msg->port.init_devid_len != 0) {
1279 		if (port->init_devid == NULL ||
1280 		    port->init_devid->len < msg->port.init_devid_len) {
1281 			free(port->init_devid, M_CTL);
1282 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1283 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1284 		}
1285 		memcpy(port->init_devid->data, &msg->port.data[i],
1286 		    msg->port.init_devid_len);
1287 		port->init_devid->len = msg->port.init_devid_len;
1288 		i += msg->port.init_devid_len;
1289 	} else {
1290 		free(port->init_devid, M_CTL);
1291 		port->init_devid = NULL;
1292 	}
1293 	if (new) {
1294 		if (ctl_port_register(port) != 0) {
1295 			printf("%s: ctl_port_register() failed with error\n",
1296 			    __func__);
1297 		}
1298 	}
1299 	mtx_lock(&softc->ctl_lock);
1300 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1301 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1302 			continue;
1303 		mtx_lock(&lun->lun_lock);
1304 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1305 		mtx_unlock(&lun->lun_lock);
1306 	}
1307 	mtx_unlock(&softc->ctl_lock);
1308 }
1309 
1310 static void
1311 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1312 {
1313 	struct ctl_port *port;
1314 	int iid;
1315 
1316 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1317 	if (port == NULL) {
1318 		printf("%s: Received IID for unknown port %d\n",
1319 		    __func__, msg->hdr.nexus.targ_port);
1320 		return;
1321 	}
1322 	iid = msg->hdr.nexus.initid;
1323 	if (port->wwpn_iid[iid].in_use != 0 &&
1324 	    msg->iid.in_use == 0)
1325 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1326 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1327 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1328 	free(port->wwpn_iid[iid].name, M_CTL);
1329 	if (msg->iid.name_len) {
1330 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1331 		    msg->iid.name_len, M_CTL);
1332 	} else
1333 		port->wwpn_iid[iid].name = NULL;
1334 }
1335 
1336 static void
1337 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1338 {
1339 
1340 	if (msg->login.version != CTL_HA_VERSION) {
1341 		printf("CTL HA peers have different versions %d != %d\n",
1342 		    msg->login.version, CTL_HA_VERSION);
1343 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1344 		return;
1345 	}
1346 	if (msg->login.ha_mode != softc->ha_mode) {
1347 		printf("CTL HA peers have different ha_mode %d != %d\n",
1348 		    msg->login.ha_mode, softc->ha_mode);
1349 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1350 		return;
1351 	}
1352 	if (msg->login.ha_id == softc->ha_id) {
1353 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1354 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1355 		return;
1356 	}
1357 	if (msg->login.max_luns != ctl_max_luns ||
1358 	    msg->login.max_ports != ctl_max_ports ||
1359 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1360 		printf("CTL HA peers have different limits\n");
1361 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1362 		return;
1363 	}
1364 }
1365 
1366 static void
1367 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1368 {
1369 	struct ctl_lun *lun;
1370 	u_int i;
1371 	uint32_t initidx, targ_lun;
1372 
1373 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1374 	mtx_lock(&softc->ctl_lock);
1375 	if (targ_lun >= ctl_max_luns ||
1376 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1377 		mtx_unlock(&softc->ctl_lock);
1378 		return;
1379 	}
1380 	mtx_lock(&lun->lun_lock);
1381 	mtx_unlock(&softc->ctl_lock);
1382 	if (lun->flags & CTL_LUN_DISABLED) {
1383 		mtx_unlock(&lun->lun_lock);
1384 		return;
1385 	}
1386 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1387 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1388 		    msg->mode.page_code &&
1389 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1390 			break;
1391 	}
1392 	if (i == CTL_NUM_MODE_PAGES) {
1393 		mtx_unlock(&lun->lun_lock);
1394 		return;
1395 	}
1396 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1397 	    lun->mode_pages.index[i].page_len);
1398 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1399 	if (initidx != -1)
1400 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1401 	mtx_unlock(&lun->lun_lock);
1402 }
1403 
1404 /*
1405  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1406  * subsystem come in here.
1407  */
1408 static void
1409 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1410 {
1411 	struct ctl_softc *softc = control_softc;
1412 	union ctl_io *io;
1413 	struct ctl_prio *presio;
1414 	ctl_ha_status isc_status;
1415 
1416 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1417 	if (event == CTL_HA_EVT_MSG_RECV) {
1418 		union ctl_ha_msg *msg, msgbuf;
1419 
1420 		if (param > sizeof(msgbuf))
1421 			msg = malloc(param, M_CTL, M_WAITOK);
1422 		else
1423 			msg = &msgbuf;
1424 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1425 		    M_WAITOK);
1426 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1427 			printf("%s: Error receiving message: %d\n",
1428 			    __func__, isc_status);
1429 			if (msg != &msgbuf)
1430 				free(msg, M_CTL);
1431 			return;
1432 		}
1433 
1434 		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1435 		switch (msg->hdr.msg_type) {
1436 		case CTL_MSG_SERIALIZE:
1437 			io = ctl_alloc_io(softc->othersc_pool);
1438 			ctl_zero_io(io);
1439 			// populate ctsio from msg
1440 			io->io_hdr.io_type = CTL_IO_SCSI;
1441 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1442 			io->io_hdr.remote_io = msg->hdr.original_sc;
1443 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1444 					    CTL_FLAG_IO_ACTIVE;
1445 			/*
1446 			 * If we're in serialization-only mode, we don't
1447 			 * want to go through full done processing.  Thus
1448 			 * the COPY flag.
1449 			 *
1450 			 * XXX KDM add another flag that is more specific.
1451 			 */
1452 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1453 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1454 			io->io_hdr.nexus = msg->hdr.nexus;
1455 			io->scsiio.tag_num = msg->scsi.tag_num;
1456 			io->scsiio.tag_type = msg->scsi.tag_type;
1457 #ifdef CTL_TIME_IO
1458 			io->io_hdr.start_time = time_uptime;
1459 			getbinuptime(&io->io_hdr.start_bt);
1460 #endif /* CTL_TIME_IO */
1461 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1462 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1463 			       CTL_MAX_CDBLEN);
1464 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1465 				const struct ctl_cmd_entry *entry;
1466 
1467 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1468 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1469 				io->io_hdr.flags |=
1470 					entry->flags & CTL_FLAG_DATA_MASK;
1471 			}
1472 			ctl_enqueue_isc(io);
1473 			break;
1474 
1475 		/* Performed on the Originating SC, XFER mode only */
1476 		case CTL_MSG_DATAMOVE: {
1477 			struct ctl_sg_entry *sgl;
1478 			int i, j;
1479 
1480 			io = msg->hdr.original_sc;
1481 			if (io == NULL) {
1482 				printf("%s: original_sc == NULL!\n", __func__);
1483 				/* XXX KDM do something here */
1484 				break;
1485 			}
1486 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1487 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1488 			/*
1489 			 * Keep track of this, we need to send it back over
1490 			 * when the datamove is complete.
1491 			 */
1492 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1493 			if (msg->hdr.status == CTL_SUCCESS)
1494 				io->io_hdr.status = msg->hdr.status;
1495 
1496 			if (msg->dt.sg_sequence == 0) {
1497 #ifdef CTL_TIME_IO
1498 				getbinuptime(&io->io_hdr.dma_start_bt);
1499 #endif
1500 				i = msg->dt.kern_sg_entries +
1501 				    msg->dt.kern_data_len /
1502 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1503 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1504 				    M_WAITOK | M_ZERO);
1505 				CTL_RSGL(io) = sgl;
1506 				CTL_LSGL(io) = &sgl[msg->dt.kern_sg_entries];
1507 
1508 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1509 
1510 				io->scsiio.kern_sg_entries =
1511 					msg->dt.kern_sg_entries;
1512 				io->scsiio.rem_sg_entries =
1513 					msg->dt.kern_sg_entries;
1514 				io->scsiio.kern_data_len =
1515 					msg->dt.kern_data_len;
1516 				io->scsiio.kern_total_len =
1517 					msg->dt.kern_total_len;
1518 				io->scsiio.kern_data_resid =
1519 					msg->dt.kern_data_resid;
1520 				io->scsiio.kern_rel_offset =
1521 					msg->dt.kern_rel_offset;
1522 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1523 				io->io_hdr.flags |= msg->dt.flags &
1524 				    CTL_FLAG_BUS_ADDR;
1525 			} else
1526 				sgl = (struct ctl_sg_entry *)
1527 					io->scsiio.kern_data_ptr;
1528 
1529 			for (i = msg->dt.sent_sg_entries, j = 0;
1530 			     i < (msg->dt.sent_sg_entries +
1531 			     msg->dt.cur_sg_entries); i++, j++) {
1532 				sgl[i].addr = msg->dt.sg_list[j].addr;
1533 				sgl[i].len = msg->dt.sg_list[j].len;
1534 			}
1535 
1536 			/*
1537 			 * If this is the last piece of the I/O, we've got
1538 			 * the full S/G list.  Queue processing in the thread.
1539 			 * Otherwise wait for the next piece.
1540 			 */
1541 			if (msg->dt.sg_last != 0)
1542 				ctl_enqueue_isc(io);
1543 			break;
1544 		}
1545 		/* Performed on the Serializing (primary) SC, XFER mode only */
1546 		case CTL_MSG_DATAMOVE_DONE: {
1547 			if (msg->hdr.serializing_sc == NULL) {
1548 				printf("%s: serializing_sc == NULL!\n",
1549 				       __func__);
1550 				/* XXX KDM now what? */
1551 				break;
1552 			}
1553 			/*
1554 			 * We grab the sense information here in case
1555 			 * there was a failure, so we can return status
1556 			 * back to the initiator.
1557 			 */
1558 			io = msg->hdr.serializing_sc;
1559 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1560 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1561 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1562 			io->io_hdr.port_status = msg->scsi.port_status;
1563 			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1564 			if (msg->hdr.status != CTL_STATUS_NONE) {
1565 				io->io_hdr.status = msg->hdr.status;
1566 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1567 				io->scsiio.sense_len = msg->scsi.sense_len;
1568 				memcpy(&io->scsiio.sense_data,
1569 				    &msg->scsi.sense_data,
1570 				    msg->scsi.sense_len);
1571 				if (msg->hdr.status == CTL_SUCCESS)
1572 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1573 			}
1574 			ctl_enqueue_isc(io);
1575 			break;
1576 		}
1577 
1578 		/* Preformed on Originating SC, SER_ONLY mode */
1579 		case CTL_MSG_R2R:
1580 			io = msg->hdr.original_sc;
1581 			if (io == NULL) {
1582 				printf("%s: original_sc == NULL!\n",
1583 				    __func__);
1584 				break;
1585 			}
1586 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1587 			io->io_hdr.msg_type = CTL_MSG_R2R;
1588 			io->io_hdr.remote_io = msg->hdr.serializing_sc;
1589 			ctl_enqueue_isc(io);
1590 			break;
1591 
1592 		/*
1593 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1594 		 * mode.
1595 		 * Performed on the Originating (i.e. secondary) SC in XFER
1596 		 * mode
1597 		 */
1598 		case CTL_MSG_FINISH_IO:
1599 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1600 				ctl_isc_handler_finish_xfer(softc, msg);
1601 			else
1602 				ctl_isc_handler_finish_ser_only(softc, msg);
1603 			break;
1604 
1605 		/* Preformed on Originating SC */
1606 		case CTL_MSG_BAD_JUJU:
1607 			io = msg->hdr.original_sc;
1608 			if (io == NULL) {
1609 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1610 				       __func__);
1611 				break;
1612 			}
1613 			ctl_copy_sense_data(msg, io);
1614 			/*
1615 			 * IO should have already been cleaned up on other
1616 			 * SC so clear this flag so we won't send a message
1617 			 * back to finish the IO there.
1618 			 */
1619 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1620 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1621 
1622 			/* io = msg->hdr.serializing_sc; */
1623 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1624 			ctl_enqueue_isc(io);
1625 			break;
1626 
1627 		/* Handle resets sent from the other side */
1628 		case CTL_MSG_MANAGE_TASKS: {
1629 			struct ctl_taskio *taskio;
1630 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1631 			    softc->othersc_pool);
1632 			ctl_zero_io((union ctl_io *)taskio);
1633 			taskio->io_hdr.io_type = CTL_IO_TASK;
1634 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1635 			taskio->io_hdr.nexus = msg->hdr.nexus;
1636 			taskio->task_action = msg->task.task_action;
1637 			taskio->tag_num = msg->task.tag_num;
1638 			taskio->tag_type = msg->task.tag_type;
1639 #ifdef CTL_TIME_IO
1640 			taskio->io_hdr.start_time = time_uptime;
1641 			getbinuptime(&taskio->io_hdr.start_bt);
1642 #endif /* CTL_TIME_IO */
1643 			ctl_run_task((union ctl_io *)taskio);
1644 			break;
1645 		}
1646 		/* Persistent Reserve action which needs attention */
1647 		case CTL_MSG_PERS_ACTION:
1648 			presio = (struct ctl_prio *)ctl_alloc_io(
1649 			    softc->othersc_pool);
1650 			ctl_zero_io((union ctl_io *)presio);
1651 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1652 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1653 			presio->io_hdr.nexus = msg->hdr.nexus;
1654 			presio->pr_msg = msg->pr;
1655 			ctl_enqueue_isc((union ctl_io *)presio);
1656 			break;
1657 		case CTL_MSG_UA:
1658 			ctl_isc_ua(softc, msg, param);
1659 			break;
1660 		case CTL_MSG_PORT_SYNC:
1661 			ctl_isc_port_sync(softc, msg, param);
1662 			break;
1663 		case CTL_MSG_LUN_SYNC:
1664 			ctl_isc_lun_sync(softc, msg, param);
1665 			break;
1666 		case CTL_MSG_IID_SYNC:
1667 			ctl_isc_iid_sync(softc, msg, param);
1668 			break;
1669 		case CTL_MSG_LOGIN:
1670 			ctl_isc_login(softc, msg, param);
1671 			break;
1672 		case CTL_MSG_MODE_SYNC:
1673 			ctl_isc_mode_sync(softc, msg, param);
1674 			break;
1675 		default:
1676 			printf("Received HA message of unknown type %d\n",
1677 			    msg->hdr.msg_type);
1678 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1679 			break;
1680 		}
1681 		if (msg != &msgbuf)
1682 			free(msg, M_CTL);
1683 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1684 		printf("CTL: HA link status changed from %d to %d\n",
1685 		    softc->ha_link, param);
1686 		if (param == softc->ha_link)
1687 			return;
1688 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1689 			softc->ha_link = param;
1690 			ctl_isc_ha_link_down(softc);
1691 		} else {
1692 			softc->ha_link = param;
1693 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1694 				ctl_isc_ha_link_up(softc);
1695 		}
1696 		return;
1697 	} else {
1698 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1699 		return;
1700 	}
1701 }
1702 
1703 static void
1704 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1705 {
1706 
1707 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1708 	    src->scsi.sense_len);
1709 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1710 	dest->scsiio.sense_len = src->scsi.sense_len;
1711 	dest->io_hdr.status = src->hdr.status;
1712 }
1713 
1714 static void
1715 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1716 {
1717 
1718 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1719 	    src->scsiio.sense_len);
1720 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1721 	dest->scsi.sense_len = src->scsiio.sense_len;
1722 	dest->hdr.status = src->io_hdr.status;
1723 }
1724 
1725 void
1726 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1727 {
1728 	struct ctl_softc *softc = lun->ctl_softc;
1729 	ctl_ua_type *pu;
1730 
1731 	if (initidx < softc->init_min || initidx >= softc->init_max)
1732 		return;
1733 	mtx_assert(&lun->lun_lock, MA_OWNED);
1734 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1735 	if (pu == NULL)
1736 		return;
1737 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1738 }
1739 
1740 void
1741 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1742 {
1743 	int i;
1744 
1745 	mtx_assert(&lun->lun_lock, MA_OWNED);
1746 	if (lun->pending_ua[port] == NULL)
1747 		return;
1748 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1749 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1750 			continue;
1751 		lun->pending_ua[port][i] |= ua;
1752 	}
1753 }
1754 
1755 void
1756 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1757 {
1758 	struct ctl_softc *softc = lun->ctl_softc;
1759 	int i;
1760 
1761 	mtx_assert(&lun->lun_lock, MA_OWNED);
1762 	for (i = softc->port_min; i < softc->port_max; i++)
1763 		ctl_est_ua_port(lun, i, except, ua);
1764 }
1765 
1766 void
1767 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1768 {
1769 	struct ctl_softc *softc = lun->ctl_softc;
1770 	ctl_ua_type *pu;
1771 
1772 	if (initidx < softc->init_min || initidx >= softc->init_max)
1773 		return;
1774 	mtx_assert(&lun->lun_lock, MA_OWNED);
1775 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1776 	if (pu == NULL)
1777 		return;
1778 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1779 }
1780 
1781 void
1782 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1783 {
1784 	struct ctl_softc *softc = lun->ctl_softc;
1785 	int i, j;
1786 
1787 	mtx_assert(&lun->lun_lock, MA_OWNED);
1788 	for (i = softc->port_min; i < softc->port_max; i++) {
1789 		if (lun->pending_ua[i] == NULL)
1790 			continue;
1791 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1792 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1793 				continue;
1794 			lun->pending_ua[i][j] &= ~ua;
1795 		}
1796 	}
1797 }
1798 
1799 void
1800 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1801     ctl_ua_type ua_type)
1802 {
1803 	struct ctl_lun *lun;
1804 
1805 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1806 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1807 		mtx_lock(&lun->lun_lock);
1808 		ctl_clr_ua(lun, initidx, ua_type);
1809 		mtx_unlock(&lun->lun_lock);
1810 	}
1811 }
1812 
1813 static int
1814 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1815 {
1816 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1817 	struct ctl_lun *lun;
1818 	struct ctl_lun_req ireq;
1819 	int error, value;
1820 
1821 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1822 	error = sysctl_handle_int(oidp, &value, 0, req);
1823 	if ((error != 0) || (req->newptr == NULL))
1824 		return (error);
1825 
1826 	mtx_lock(&softc->ctl_lock);
1827 	if (value == 0)
1828 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1829 	else
1830 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1831 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1832 		mtx_unlock(&softc->ctl_lock);
1833 		bzero(&ireq, sizeof(ireq));
1834 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1835 		ireq.reqdata.modify.lun_id = lun->lun;
1836 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1837 		    curthread);
1838 		if (ireq.status != CTL_LUN_OK) {
1839 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1840 			    __func__, ireq.status, ireq.error_str);
1841 		}
1842 		mtx_lock(&softc->ctl_lock);
1843 	}
1844 	mtx_unlock(&softc->ctl_lock);
1845 	return (0);
1846 }
1847 
1848 static int
1849 ctl_init(void)
1850 {
1851 	struct make_dev_args args;
1852 	struct ctl_softc *softc;
1853 	int i, error;
1854 
1855 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1856 			       M_WAITOK | M_ZERO);
1857 
1858 	make_dev_args_init(&args);
1859 	args.mda_devsw = &ctl_cdevsw;
1860 	args.mda_uid = UID_ROOT;
1861 	args.mda_gid = GID_OPERATOR;
1862 	args.mda_mode = 0600;
1863 	args.mda_si_drv1 = softc;
1864 	args.mda_si_drv2 = NULL;
1865 	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1866 	if (error != 0) {
1867 		free(softc, M_DEVBUF);
1868 		control_softc = NULL;
1869 		return (error);
1870 	}
1871 
1872 	sysctl_ctx_init(&softc->sysctl_ctx);
1873 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1874 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1875 		CTLFLAG_RD, 0, "CAM Target Layer");
1876 
1877 	if (softc->sysctl_tree == NULL) {
1878 		printf("%s: unable to allocate sysctl tree\n", __func__);
1879 		destroy_dev(softc->dev);
1880 		free(softc, M_DEVBUF);
1881 		control_softc = NULL;
1882 		return (ENOMEM);
1883 	}
1884 
1885 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1886 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1887 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1888 	softc->flags = 0;
1889 
1890 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1891 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1892 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1893 
1894 	if (ctl_max_luns <= 0 || powerof2(ctl_max_luns) == 0) {
1895 		printf("Bad value %d for kern.cam.ctl.max_luns, must be a power of two, using %d\n",
1896 		    ctl_max_luns, CTL_DEFAULT_MAX_LUNS);
1897 		ctl_max_luns = CTL_DEFAULT_MAX_LUNS;
1898 	}
1899 	softc->ctl_luns = malloc(sizeof(struct ctl_lun *) * ctl_max_luns,
1900 	    M_DEVBUF, M_WAITOK | M_ZERO);
1901 	softc->ctl_lun_mask = malloc(sizeof(uint32_t) *
1902 	    ((ctl_max_luns + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1903 	if (ctl_max_ports <= 0 || powerof2(ctl_max_ports) == 0) {
1904 		printf("Bad value %d for kern.cam.ctl.max_ports, must be a power of two, using %d\n",
1905 		    ctl_max_ports, CTL_DEFAULT_MAX_PORTS);
1906 		ctl_max_ports = CTL_DEFAULT_MAX_PORTS;
1907 	}
1908 	softc->ctl_port_mask = malloc(sizeof(uint32_t) *
1909 	  ((ctl_max_ports + 31) / 32), M_DEVBUF, M_WAITOK | M_ZERO);
1910 	softc->ctl_ports = malloc(sizeof(struct ctl_port *) * ctl_max_ports,
1911 	     M_DEVBUF, M_WAITOK | M_ZERO);
1912 
1913 
1914 	/*
1915 	 * In Copan's HA scheme, the "master" and "slave" roles are
1916 	 * figured out through the slot the controller is in.  Although it
1917 	 * is an active/active system, someone has to be in charge.
1918 	 */
1919 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1920 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1921 	    "HA head ID (0 - no HA)");
1922 	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1923 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1924 		softc->is_single = 1;
1925 		softc->port_cnt = ctl_max_ports;
1926 		softc->port_min = 0;
1927 	} else {
1928 		softc->port_cnt = ctl_max_ports / NUM_HA_SHELVES;
1929 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1930 	}
1931 	softc->port_max = softc->port_min + softc->port_cnt;
1932 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1933 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1934 
1935 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1936 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1937 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1938 
1939 	STAILQ_INIT(&softc->lun_list);
1940 	STAILQ_INIT(&softc->pending_lun_queue);
1941 	STAILQ_INIT(&softc->fe_list);
1942 	STAILQ_INIT(&softc->port_list);
1943 	STAILQ_INIT(&softc->be_list);
1944 	ctl_tpc_init(softc);
1945 
1946 	if (worker_threads <= 0)
1947 		worker_threads = max(1, mp_ncpus / 4);
1948 	if (worker_threads > CTL_MAX_THREADS)
1949 		worker_threads = CTL_MAX_THREADS;
1950 
1951 	for (i = 0; i < worker_threads; i++) {
1952 		struct ctl_thread *thr = &softc->threads[i];
1953 
1954 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1955 		thr->ctl_softc = softc;
1956 		STAILQ_INIT(&thr->incoming_queue);
1957 		STAILQ_INIT(&thr->rtr_queue);
1958 		STAILQ_INIT(&thr->done_queue);
1959 		STAILQ_INIT(&thr->isc_queue);
1960 
1961 		error = kproc_kthread_add(ctl_work_thread, thr,
1962 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1963 		if (error != 0) {
1964 			printf("error creating CTL work thread!\n");
1965 			return (error);
1966 		}
1967 	}
1968 	error = kproc_kthread_add(ctl_lun_thread, softc,
1969 	    &softc->ctl_proc, &softc->lun_thread, 0, 0, "ctl", "lun");
1970 	if (error != 0) {
1971 		printf("error creating CTL lun thread!\n");
1972 		return (error);
1973 	}
1974 	error = kproc_kthread_add(ctl_thresh_thread, softc,
1975 	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
1976 	if (error != 0) {
1977 		printf("error creating CTL threshold thread!\n");
1978 		return (error);
1979 	}
1980 
1981 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1982 	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1983 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1984 
1985 	if (softc->is_single == 0) {
1986 		if (ctl_frontend_register(&ha_frontend) != 0)
1987 			softc->is_single = 1;
1988 	}
1989 	return (0);
1990 }
1991 
1992 static int
1993 ctl_shutdown(void)
1994 {
1995 	struct ctl_softc *softc = control_softc;
1996 	int i;
1997 
1998 	if (softc->is_single == 0)
1999 		ctl_frontend_deregister(&ha_frontend);
2000 
2001 	destroy_dev(softc->dev);
2002 
2003 	/* Shutdown CTL threads. */
2004 	softc->shutdown = 1;
2005 	for (i = 0; i < worker_threads; i++) {
2006 		struct ctl_thread *thr = &softc->threads[i];
2007 		while (thr->thread != NULL) {
2008 			wakeup(thr);
2009 			if (thr->thread != NULL)
2010 				pause("CTL thr shutdown", 1);
2011 		}
2012 		mtx_destroy(&thr->queue_lock);
2013 	}
2014 	while (softc->lun_thread != NULL) {
2015 		wakeup(&softc->pending_lun_queue);
2016 		if (softc->lun_thread != NULL)
2017 			pause("CTL thr shutdown", 1);
2018 	}
2019 	while (softc->thresh_thread != NULL) {
2020 		wakeup(softc->thresh_thread);
2021 		if (softc->thresh_thread != NULL)
2022 			pause("CTL thr shutdown", 1);
2023 	}
2024 
2025 	ctl_tpc_shutdown(softc);
2026 	uma_zdestroy(softc->io_zone);
2027 	mtx_destroy(&softc->ctl_lock);
2028 
2029 	free(softc->ctl_luns, M_DEVBUF);
2030 	free(softc->ctl_lun_mask, M_DEVBUF);
2031 	free(softc->ctl_port_mask, M_DEVBUF);
2032 	free(softc->ctl_ports, M_DEVBUF);
2033 
2034 	sysctl_ctx_free(&softc->sysctl_ctx);
2035 
2036 	free(softc, M_DEVBUF);
2037 	control_softc = NULL;
2038 	return (0);
2039 }
2040 
2041 static int
2042 ctl_module_event_handler(module_t mod, int what, void *arg)
2043 {
2044 
2045 	switch (what) {
2046 	case MOD_LOAD:
2047 		return (ctl_init());
2048 	case MOD_UNLOAD:
2049 		return (ctl_shutdown());
2050 	default:
2051 		return (EOPNOTSUPP);
2052 	}
2053 }
2054 
2055 /*
2056  * XXX KDM should we do some access checks here?  Bump a reference count to
2057  * prevent a CTL module from being unloaded while someone has it open?
2058  */
2059 static int
2060 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2061 {
2062 	return (0);
2063 }
2064 
2065 static int
2066 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2067 {
2068 	return (0);
2069 }
2070 
2071 /*
2072  * Remove an initiator by port number and initiator ID.
2073  * Returns 0 for success, -1 for failure.
2074  */
2075 int
2076 ctl_remove_initiator(struct ctl_port *port, int iid)
2077 {
2078 	struct ctl_softc *softc = port->ctl_softc;
2079 	int last;
2080 
2081 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2082 
2083 	if (iid > CTL_MAX_INIT_PER_PORT) {
2084 		printf("%s: initiator ID %u > maximun %u!\n",
2085 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2086 		return (-1);
2087 	}
2088 
2089 	mtx_lock(&softc->ctl_lock);
2090 	last = (--port->wwpn_iid[iid].in_use == 0);
2091 	port->wwpn_iid[iid].last_use = time_uptime;
2092 	mtx_unlock(&softc->ctl_lock);
2093 	if (last)
2094 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2095 	ctl_isc_announce_iid(port, iid);
2096 
2097 	return (0);
2098 }
2099 
2100 /*
2101  * Add an initiator to the initiator map.
2102  * Returns iid for success, < 0 for failure.
2103  */
2104 int
2105 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2106 {
2107 	struct ctl_softc *softc = port->ctl_softc;
2108 	time_t best_time;
2109 	int i, best;
2110 
2111 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2112 
2113 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2114 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2115 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2116 		free(name, M_CTL);
2117 		return (-1);
2118 	}
2119 
2120 	mtx_lock(&softc->ctl_lock);
2121 
2122 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2123 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2124 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2125 				iid = i;
2126 				break;
2127 			}
2128 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2129 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2130 				iid = i;
2131 				break;
2132 			}
2133 		}
2134 	}
2135 
2136 	if (iid < 0) {
2137 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2138 			if (port->wwpn_iid[i].in_use == 0 &&
2139 			    port->wwpn_iid[i].wwpn == 0 &&
2140 			    port->wwpn_iid[i].name == NULL) {
2141 				iid = i;
2142 				break;
2143 			}
2144 		}
2145 	}
2146 
2147 	if (iid < 0) {
2148 		best = -1;
2149 		best_time = INT32_MAX;
2150 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2151 			if (port->wwpn_iid[i].in_use == 0) {
2152 				if (port->wwpn_iid[i].last_use < best_time) {
2153 					best = i;
2154 					best_time = port->wwpn_iid[i].last_use;
2155 				}
2156 			}
2157 		}
2158 		iid = best;
2159 	}
2160 
2161 	if (iid < 0) {
2162 		mtx_unlock(&softc->ctl_lock);
2163 		free(name, M_CTL);
2164 		return (-2);
2165 	}
2166 
2167 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2168 		/*
2169 		 * This is not an error yet.
2170 		 */
2171 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2172 #if 0
2173 			printf("%s: port %d iid %u WWPN %#jx arrived"
2174 			    " again\n", __func__, port->targ_port,
2175 			    iid, (uintmax_t)wwpn);
2176 #endif
2177 			goto take;
2178 		}
2179 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2180 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2181 #if 0
2182 			printf("%s: port %d iid %u name '%s' arrived"
2183 			    " again\n", __func__, port->targ_port,
2184 			    iid, name);
2185 #endif
2186 			goto take;
2187 		}
2188 
2189 		/*
2190 		 * This is an error, but what do we do about it?  The
2191 		 * driver is telling us we have a new WWPN for this
2192 		 * initiator ID, so we pretty much need to use it.
2193 		 */
2194 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2195 		    " but WWPN %#jx '%s' is still at that address\n",
2196 		    __func__, port->targ_port, iid, wwpn, name,
2197 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2198 		    port->wwpn_iid[iid].name);
2199 	}
2200 take:
2201 	free(port->wwpn_iid[iid].name, M_CTL);
2202 	port->wwpn_iid[iid].name = name;
2203 	port->wwpn_iid[iid].wwpn = wwpn;
2204 	port->wwpn_iid[iid].in_use++;
2205 	mtx_unlock(&softc->ctl_lock);
2206 	ctl_isc_announce_iid(port, iid);
2207 
2208 	return (iid);
2209 }
2210 
2211 static int
2212 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2213 {
2214 	int len;
2215 
2216 	switch (port->port_type) {
2217 	case CTL_PORT_FC:
2218 	{
2219 		struct scsi_transportid_fcp *id =
2220 		    (struct scsi_transportid_fcp *)buf;
2221 		if (port->wwpn_iid[iid].wwpn == 0)
2222 			return (0);
2223 		memset(id, 0, sizeof(*id));
2224 		id->format_protocol = SCSI_PROTO_FC;
2225 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2226 		return (sizeof(*id));
2227 	}
2228 	case CTL_PORT_ISCSI:
2229 	{
2230 		struct scsi_transportid_iscsi_port *id =
2231 		    (struct scsi_transportid_iscsi_port *)buf;
2232 		if (port->wwpn_iid[iid].name == NULL)
2233 			return (0);
2234 		memset(id, 0, 256);
2235 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2236 		    SCSI_PROTO_ISCSI;
2237 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2238 		len = roundup2(min(len, 252), 4);
2239 		scsi_ulto2b(len, id->additional_length);
2240 		return (sizeof(*id) + len);
2241 	}
2242 	case CTL_PORT_SAS:
2243 	{
2244 		struct scsi_transportid_sas *id =
2245 		    (struct scsi_transportid_sas *)buf;
2246 		if (port->wwpn_iid[iid].wwpn == 0)
2247 			return (0);
2248 		memset(id, 0, sizeof(*id));
2249 		id->format_protocol = SCSI_PROTO_SAS;
2250 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2251 		return (sizeof(*id));
2252 	}
2253 	default:
2254 	{
2255 		struct scsi_transportid_spi *id =
2256 		    (struct scsi_transportid_spi *)buf;
2257 		memset(id, 0, sizeof(*id));
2258 		id->format_protocol = SCSI_PROTO_SPI;
2259 		scsi_ulto2b(iid, id->scsi_addr);
2260 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2261 		return (sizeof(*id));
2262 	}
2263 	}
2264 }
2265 
2266 /*
2267  * Serialize a command that went down the "wrong" side, and so was sent to
2268  * this controller for execution.  The logic is a little different than the
2269  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2270  * sent back to the other side, but in the success case, we execute the
2271  * command on this side (XFER mode) or tell the other side to execute it
2272  * (SER_ONLY mode).
2273  */
2274 static void
2275 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2276 {
2277 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2278 	struct ctl_port *port = CTL_PORT(ctsio);
2279 	union ctl_ha_msg msg_info;
2280 	struct ctl_lun *lun;
2281 	const struct ctl_cmd_entry *entry;
2282 	uint32_t targ_lun;
2283 
2284 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2285 
2286 	/* Make sure that we know about this port. */
2287 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2288 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2289 					 /*retry_count*/ 1);
2290 		goto badjuju;
2291 	}
2292 
2293 	/* Make sure that we know about this LUN. */
2294 	mtx_lock(&softc->ctl_lock);
2295 	if (targ_lun >= ctl_max_luns ||
2296 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2297 		mtx_unlock(&softc->ctl_lock);
2298 
2299 		/*
2300 		 * The other node would not send this request to us unless
2301 		 * received announce that we are primary node for this LUN.
2302 		 * If this LUN does not exist now, it is probably result of
2303 		 * a race, so respond to initiator in the most opaque way.
2304 		 */
2305 		ctl_set_busy(ctsio);
2306 		goto badjuju;
2307 	}
2308 	mtx_lock(&lun->lun_lock);
2309 	mtx_unlock(&softc->ctl_lock);
2310 
2311 	/*
2312 	 * If the LUN is invalid, pretend that it doesn't exist.
2313 	 * It will go away as soon as all pending I/Os completed.
2314 	 */
2315 	if (lun->flags & CTL_LUN_DISABLED) {
2316 		mtx_unlock(&lun->lun_lock);
2317 		ctl_set_busy(ctsio);
2318 		goto badjuju;
2319 	}
2320 
2321 	entry = ctl_get_cmd_entry(ctsio, NULL);
2322 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2323 		mtx_unlock(&lun->lun_lock);
2324 		goto badjuju;
2325 	}
2326 
2327 	CTL_LUN(ctsio) = lun;
2328 	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2329 
2330 	/*
2331 	 * Every I/O goes into the OOA queue for a
2332 	 * particular LUN, and stays there until completion.
2333 	 */
2334 #ifdef CTL_TIME_IO
2335 	if (TAILQ_EMPTY(&lun->ooa_queue))
2336 		lun->idle_time += getsbinuptime() - lun->last_busy;
2337 #endif
2338 	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2339 
2340 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2341 		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2342 		 ooa_links))) {
2343 	case CTL_ACTION_BLOCK:
2344 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2345 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2346 				  blocked_links);
2347 		mtx_unlock(&lun->lun_lock);
2348 		break;
2349 	case CTL_ACTION_PASS:
2350 	case CTL_ACTION_SKIP:
2351 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2352 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2353 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2354 			mtx_unlock(&lun->lun_lock);
2355 		} else {
2356 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2357 			mtx_unlock(&lun->lun_lock);
2358 
2359 			/* send msg back to other side */
2360 			msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2361 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2362 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2363 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2364 			    sizeof(msg_info.hdr), M_WAITOK);
2365 		}
2366 		break;
2367 	case CTL_ACTION_OVERLAP:
2368 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2369 		mtx_unlock(&lun->lun_lock);
2370 		ctl_set_overlapped_cmd(ctsio);
2371 		goto badjuju;
2372 	case CTL_ACTION_OVERLAP_TAG:
2373 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2374 		mtx_unlock(&lun->lun_lock);
2375 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2376 		goto badjuju;
2377 	case CTL_ACTION_ERROR:
2378 	default:
2379 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2380 		mtx_unlock(&lun->lun_lock);
2381 
2382 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2383 					 /*retry_count*/ 0);
2384 badjuju:
2385 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2386 		msg_info.hdr.original_sc = ctsio->io_hdr.remote_io;
2387 		msg_info.hdr.serializing_sc = NULL;
2388 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2389 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2390 		    sizeof(msg_info.scsi), M_WAITOK);
2391 		ctl_free_io((union ctl_io *)ctsio);
2392 		break;
2393 	}
2394 }
2395 
2396 /*
2397  * Returns 0 for success, errno for failure.
2398  */
2399 static void
2400 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2401 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2402 {
2403 	union ctl_io *io;
2404 
2405 	mtx_lock(&lun->lun_lock);
2406 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2407 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2408 	     ooa_links)) {
2409 		struct ctl_ooa_entry *entry;
2410 
2411 		/*
2412 		 * If we've got more than we can fit, just count the
2413 		 * remaining entries.
2414 		 */
2415 		if (*cur_fill_num >= ooa_hdr->alloc_num)
2416 			continue;
2417 
2418 		entry = &kern_entries[*cur_fill_num];
2419 
2420 		entry->tag_num = io->scsiio.tag_num;
2421 		entry->lun_num = lun->lun;
2422 #ifdef CTL_TIME_IO
2423 		entry->start_bt = io->io_hdr.start_bt;
2424 #endif
2425 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2426 		entry->cdb_len = io->scsiio.cdb_len;
2427 		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2428 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2429 
2430 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2431 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2432 
2433 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2434 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2435 
2436 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2437 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2438 
2439 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2440 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2441 	}
2442 	mtx_unlock(&lun->lun_lock);
2443 }
2444 
2445 /*
2446  * Escape characters that are illegal or not recommended in XML.
2447  */
2448 int
2449 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2450 {
2451 	char *end = str + size;
2452 	int retval;
2453 
2454 	retval = 0;
2455 
2456 	for (; *str && str < end; str++) {
2457 		switch (*str) {
2458 		case '&':
2459 			retval = sbuf_printf(sb, "&amp;");
2460 			break;
2461 		case '>':
2462 			retval = sbuf_printf(sb, "&gt;");
2463 			break;
2464 		case '<':
2465 			retval = sbuf_printf(sb, "&lt;");
2466 			break;
2467 		default:
2468 			retval = sbuf_putc(sb, *str);
2469 			break;
2470 		}
2471 
2472 		if (retval != 0)
2473 			break;
2474 
2475 	}
2476 
2477 	return (retval);
2478 }
2479 
2480 static void
2481 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2482 {
2483 	struct scsi_vpd_id_descriptor *desc;
2484 	int i;
2485 
2486 	if (id == NULL || id->len < 4)
2487 		return;
2488 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2489 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2490 	case SVPD_ID_TYPE_T10:
2491 		sbuf_printf(sb, "t10.");
2492 		break;
2493 	case SVPD_ID_TYPE_EUI64:
2494 		sbuf_printf(sb, "eui.");
2495 		break;
2496 	case SVPD_ID_TYPE_NAA:
2497 		sbuf_printf(sb, "naa.");
2498 		break;
2499 	case SVPD_ID_TYPE_SCSI_NAME:
2500 		break;
2501 	}
2502 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2503 	case SVPD_ID_CODESET_BINARY:
2504 		for (i = 0; i < desc->length; i++)
2505 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2506 		break;
2507 	case SVPD_ID_CODESET_ASCII:
2508 		sbuf_printf(sb, "%.*s", (int)desc->length,
2509 		    (char *)desc->identifier);
2510 		break;
2511 	case SVPD_ID_CODESET_UTF8:
2512 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2513 		break;
2514 	}
2515 }
2516 
2517 static int
2518 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2519 	  struct thread *td)
2520 {
2521 	struct ctl_softc *softc = dev->si_drv1;
2522 	struct ctl_port *port;
2523 	struct ctl_lun *lun;
2524 	int retval;
2525 
2526 	retval = 0;
2527 
2528 	switch (cmd) {
2529 	case CTL_IO:
2530 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2531 		break;
2532 	case CTL_ENABLE_PORT:
2533 	case CTL_DISABLE_PORT:
2534 	case CTL_SET_PORT_WWNS: {
2535 		struct ctl_port *port;
2536 		struct ctl_port_entry *entry;
2537 
2538 		entry = (struct ctl_port_entry *)addr;
2539 
2540 		mtx_lock(&softc->ctl_lock);
2541 		STAILQ_FOREACH(port, &softc->port_list, links) {
2542 			int action, done;
2543 
2544 			if (port->targ_port < softc->port_min ||
2545 			    port->targ_port >= softc->port_max)
2546 				continue;
2547 
2548 			action = 0;
2549 			done = 0;
2550 			if ((entry->port_type == CTL_PORT_NONE)
2551 			 && (entry->targ_port == port->targ_port)) {
2552 				/*
2553 				 * If the user only wants to enable or
2554 				 * disable or set WWNs on a specific port,
2555 				 * do the operation and we're done.
2556 				 */
2557 				action = 1;
2558 				done = 1;
2559 			} else if (entry->port_type & port->port_type) {
2560 				/*
2561 				 * Compare the user's type mask with the
2562 				 * particular frontend type to see if we
2563 				 * have a match.
2564 				 */
2565 				action = 1;
2566 				done = 0;
2567 
2568 				/*
2569 				 * Make sure the user isn't trying to set
2570 				 * WWNs on multiple ports at the same time.
2571 				 */
2572 				if (cmd == CTL_SET_PORT_WWNS) {
2573 					printf("%s: Can't set WWNs on "
2574 					       "multiple ports\n", __func__);
2575 					retval = EINVAL;
2576 					break;
2577 				}
2578 			}
2579 			if (action == 0)
2580 				continue;
2581 
2582 			/*
2583 			 * XXX KDM we have to drop the lock here, because
2584 			 * the online/offline operations can potentially
2585 			 * block.  We need to reference count the frontends
2586 			 * so they can't go away,
2587 			 */
2588 			if (cmd == CTL_ENABLE_PORT) {
2589 				mtx_unlock(&softc->ctl_lock);
2590 				ctl_port_online(port);
2591 				mtx_lock(&softc->ctl_lock);
2592 			} else if (cmd == CTL_DISABLE_PORT) {
2593 				mtx_unlock(&softc->ctl_lock);
2594 				ctl_port_offline(port);
2595 				mtx_lock(&softc->ctl_lock);
2596 			} else if (cmd == CTL_SET_PORT_WWNS) {
2597 				ctl_port_set_wwns(port,
2598 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2599 				    1 : 0, entry->wwnn,
2600 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2601 				    1 : 0, entry->wwpn);
2602 			}
2603 			if (done != 0)
2604 				break;
2605 		}
2606 		mtx_unlock(&softc->ctl_lock);
2607 		break;
2608 	}
2609 	case CTL_GET_OOA: {
2610 		struct ctl_ooa *ooa_hdr;
2611 		struct ctl_ooa_entry *entries;
2612 		uint32_t cur_fill_num;
2613 
2614 		ooa_hdr = (struct ctl_ooa *)addr;
2615 
2616 		if ((ooa_hdr->alloc_len == 0)
2617 		 || (ooa_hdr->alloc_num == 0)) {
2618 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2619 			       "must be non-zero\n", __func__,
2620 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2621 			retval = EINVAL;
2622 			break;
2623 		}
2624 
2625 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2626 		    sizeof(struct ctl_ooa_entry))) {
2627 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2628 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2629 			       __func__, ooa_hdr->alloc_len,
2630 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2631 			retval = EINVAL;
2632 			break;
2633 		}
2634 
2635 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2636 		if (entries == NULL) {
2637 			printf("%s: could not allocate %d bytes for OOA "
2638 			       "dump\n", __func__, ooa_hdr->alloc_len);
2639 			retval = ENOMEM;
2640 			break;
2641 		}
2642 
2643 		mtx_lock(&softc->ctl_lock);
2644 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2645 		    (ooa_hdr->lun_num >= ctl_max_luns ||
2646 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2647 			mtx_unlock(&softc->ctl_lock);
2648 			free(entries, M_CTL);
2649 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2650 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2651 			retval = EINVAL;
2652 			break;
2653 		}
2654 
2655 		cur_fill_num = 0;
2656 
2657 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2658 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2659 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2660 				    ooa_hdr, entries);
2661 			}
2662 		} else {
2663 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2664 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2665 			    entries);
2666 		}
2667 		mtx_unlock(&softc->ctl_lock);
2668 
2669 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2670 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2671 			sizeof(struct ctl_ooa_entry);
2672 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2673 		if (retval != 0) {
2674 			printf("%s: error copying out %d bytes for OOA dump\n",
2675 			       __func__, ooa_hdr->fill_len);
2676 		}
2677 
2678 		getbinuptime(&ooa_hdr->cur_bt);
2679 
2680 		if (cur_fill_num > ooa_hdr->alloc_num) {
2681 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2682 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2683 		} else {
2684 			ooa_hdr->dropped_num = 0;
2685 			ooa_hdr->status = CTL_OOA_OK;
2686 		}
2687 
2688 		free(entries, M_CTL);
2689 		break;
2690 	}
2691 	case CTL_DELAY_IO: {
2692 		struct ctl_io_delay_info *delay_info;
2693 
2694 		delay_info = (struct ctl_io_delay_info *)addr;
2695 
2696 #ifdef CTL_IO_DELAY
2697 		mtx_lock(&softc->ctl_lock);
2698 		if (delay_info->lun_id >= ctl_max_luns ||
2699 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2700 			mtx_unlock(&softc->ctl_lock);
2701 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2702 			break;
2703 		}
2704 		mtx_lock(&lun->lun_lock);
2705 		mtx_unlock(&softc->ctl_lock);
2706 		delay_info->status = CTL_DELAY_STATUS_OK;
2707 		switch (delay_info->delay_type) {
2708 		case CTL_DELAY_TYPE_CONT:
2709 		case CTL_DELAY_TYPE_ONESHOT:
2710 			break;
2711 		default:
2712 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2713 			break;
2714 		}
2715 		switch (delay_info->delay_loc) {
2716 		case CTL_DELAY_LOC_DATAMOVE:
2717 			lun->delay_info.datamove_type = delay_info->delay_type;
2718 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2719 			break;
2720 		case CTL_DELAY_LOC_DONE:
2721 			lun->delay_info.done_type = delay_info->delay_type;
2722 			lun->delay_info.done_delay = delay_info->delay_secs;
2723 			break;
2724 		default:
2725 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2726 			break;
2727 		}
2728 		mtx_unlock(&lun->lun_lock);
2729 #else
2730 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2731 #endif /* CTL_IO_DELAY */
2732 		break;
2733 	}
2734 	case CTL_ERROR_INJECT: {
2735 		struct ctl_error_desc *err_desc, *new_err_desc;
2736 
2737 		err_desc = (struct ctl_error_desc *)addr;
2738 
2739 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2740 				      M_WAITOK | M_ZERO);
2741 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2742 
2743 		mtx_lock(&softc->ctl_lock);
2744 		if (err_desc->lun_id >= ctl_max_luns ||
2745 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2746 			mtx_unlock(&softc->ctl_lock);
2747 			free(new_err_desc, M_CTL);
2748 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2749 			       __func__, (uintmax_t)err_desc->lun_id);
2750 			retval = EINVAL;
2751 			break;
2752 		}
2753 		mtx_lock(&lun->lun_lock);
2754 		mtx_unlock(&softc->ctl_lock);
2755 
2756 		/*
2757 		 * We could do some checking here to verify the validity
2758 		 * of the request, but given the complexity of error
2759 		 * injection requests, the checking logic would be fairly
2760 		 * complex.
2761 		 *
2762 		 * For now, if the request is invalid, it just won't get
2763 		 * executed and might get deleted.
2764 		 */
2765 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2766 
2767 		/*
2768 		 * XXX KDM check to make sure the serial number is unique,
2769 		 * in case we somehow manage to wrap.  That shouldn't
2770 		 * happen for a very long time, but it's the right thing to
2771 		 * do.
2772 		 */
2773 		new_err_desc->serial = lun->error_serial;
2774 		err_desc->serial = lun->error_serial;
2775 		lun->error_serial++;
2776 
2777 		mtx_unlock(&lun->lun_lock);
2778 		break;
2779 	}
2780 	case CTL_ERROR_INJECT_DELETE: {
2781 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2782 		int delete_done;
2783 
2784 		delete_desc = (struct ctl_error_desc *)addr;
2785 		delete_done = 0;
2786 
2787 		mtx_lock(&softc->ctl_lock);
2788 		if (delete_desc->lun_id >= ctl_max_luns ||
2789 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2790 			mtx_unlock(&softc->ctl_lock);
2791 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2792 			       __func__, (uintmax_t)delete_desc->lun_id);
2793 			retval = EINVAL;
2794 			break;
2795 		}
2796 		mtx_lock(&lun->lun_lock);
2797 		mtx_unlock(&softc->ctl_lock);
2798 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2799 			if (desc->serial != delete_desc->serial)
2800 				continue;
2801 
2802 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2803 				      links);
2804 			free(desc, M_CTL);
2805 			delete_done = 1;
2806 		}
2807 		mtx_unlock(&lun->lun_lock);
2808 		if (delete_done == 0) {
2809 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2810 			       "error serial %ju on LUN %u\n", __func__,
2811 			       delete_desc->serial, delete_desc->lun_id);
2812 			retval = EINVAL;
2813 			break;
2814 		}
2815 		break;
2816 	}
2817 	case CTL_DUMP_STRUCTS: {
2818 		int j, k;
2819 		struct ctl_port *port;
2820 		struct ctl_frontend *fe;
2821 
2822 		mtx_lock(&softc->ctl_lock);
2823 		printf("CTL Persistent Reservation information start:\n");
2824 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2825 			mtx_lock(&lun->lun_lock);
2826 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2827 				mtx_unlock(&lun->lun_lock);
2828 				continue;
2829 			}
2830 
2831 			for (j = 0; j < ctl_max_ports; j++) {
2832 				if (lun->pr_keys[j] == NULL)
2833 					continue;
2834 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2835 					if (lun->pr_keys[j][k] == 0)
2836 						continue;
2837 					printf("  LUN %ju port %d iid %d key "
2838 					       "%#jx\n", lun->lun, j, k,
2839 					       (uintmax_t)lun->pr_keys[j][k]);
2840 				}
2841 			}
2842 			mtx_unlock(&lun->lun_lock);
2843 		}
2844 		printf("CTL Persistent Reservation information end\n");
2845 		printf("CTL Ports:\n");
2846 		STAILQ_FOREACH(port, &softc->port_list, links) {
2847 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2848 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2849 			       port->frontend->name, port->port_type,
2850 			       port->physical_port, port->virtual_port,
2851 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2852 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2853 				if (port->wwpn_iid[j].in_use == 0 &&
2854 				    port->wwpn_iid[j].wwpn == 0 &&
2855 				    port->wwpn_iid[j].name == NULL)
2856 					continue;
2857 
2858 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2859 				    j, port->wwpn_iid[j].in_use,
2860 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2861 				    port->wwpn_iid[j].name);
2862 			}
2863 		}
2864 		printf("CTL Port information end\n");
2865 		mtx_unlock(&softc->ctl_lock);
2866 		/*
2867 		 * XXX KDM calling this without a lock.  We'd likely want
2868 		 * to drop the lock before calling the frontend's dump
2869 		 * routine anyway.
2870 		 */
2871 		printf("CTL Frontends:\n");
2872 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2873 			printf("  Frontend '%s'\n", fe->name);
2874 			if (fe->fe_dump != NULL)
2875 				fe->fe_dump();
2876 		}
2877 		printf("CTL Frontend information end\n");
2878 		break;
2879 	}
2880 	case CTL_LUN_REQ: {
2881 		struct ctl_lun_req *lun_req;
2882 		struct ctl_backend_driver *backend;
2883 		void *packed;
2884 		nvlist_t *tmp_args_nvl;
2885 		size_t packed_len;
2886 
2887 		lun_req = (struct ctl_lun_req *)addr;
2888 		tmp_args_nvl = lun_req->args_nvl;
2889 
2890 		backend = ctl_backend_find(lun_req->backend);
2891 		if (backend == NULL) {
2892 			lun_req->status = CTL_LUN_ERROR;
2893 			snprintf(lun_req->error_str,
2894 				 sizeof(lun_req->error_str),
2895 				 "Backend \"%s\" not found.",
2896 				 lun_req->backend);
2897 			break;
2898 		}
2899 
2900 		if (lun_req->args != NULL) {
2901 			packed = malloc(lun_req->args_len, M_CTL, M_WAITOK);
2902 			if (copyin(lun_req->args, packed, lun_req->args_len) != 0) {
2903 				free(packed, M_CTL);
2904 				lun_req->status = CTL_LUN_ERROR;
2905 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2906 				    "Cannot copyin args.");
2907 				break;
2908 			}
2909 			lun_req->args_nvl = nvlist_unpack(packed,
2910 			    lun_req->args_len, 0);
2911 			free(packed, M_CTL);
2912 
2913 			if (lun_req->args_nvl == NULL) {
2914 				lun_req->status = CTL_LUN_ERROR;
2915 				snprintf(lun_req->error_str, sizeof(lun_req->error_str),
2916 				    "Cannot unpack args nvlist.");
2917 				break;
2918 			}
2919 		} else
2920 			lun_req->args_nvl = nvlist_create(0);
2921 
2922 		retval = backend->ioctl(dev, cmd, addr, flag, td);
2923 		nvlist_destroy(lun_req->args_nvl);
2924 		lun_req->args_nvl = tmp_args_nvl;
2925 
2926 		if (lun_req->result_nvl != NULL) {
2927 			if (lun_req->result != NULL) {
2928 				packed = nvlist_pack(lun_req->result_nvl,
2929 				    &packed_len);
2930 				if (packed == NULL) {
2931 					lun_req->status = CTL_LUN_ERROR;
2932 					snprintf(lun_req->error_str,
2933 					    sizeof(lun_req->error_str),
2934 					    "Cannot pack result nvlist.");
2935 					break;
2936 				}
2937 
2938 				if (packed_len > lun_req->result_len) {
2939 					lun_req->status = CTL_LUN_ERROR;
2940 					snprintf(lun_req->error_str,
2941 					    sizeof(lun_req->error_str),
2942 					    "Result nvlist too large.");
2943 					free(packed, M_NVLIST);
2944 					break;
2945 				}
2946 
2947 				if (copyout(packed, lun_req->result, packed_len)) {
2948 					lun_req->status = CTL_LUN_ERROR;
2949 					snprintf(lun_req->error_str,
2950 					    sizeof(lun_req->error_str),
2951 					    "Cannot copyout() the result.");
2952 					free(packed, M_NVLIST);
2953 					break;
2954 				}
2955 
2956 				lun_req->result_len = packed_len;
2957 				free(packed, M_NVLIST);
2958 			}
2959 
2960 			nvlist_destroy(lun_req->result_nvl);
2961 		}
2962 		break;
2963 	}
2964 	case CTL_LUN_LIST: {
2965 		struct sbuf *sb;
2966 		struct ctl_lun_list *list;
2967 		const char *name, *value;
2968 		void *cookie;
2969 		int type;
2970 
2971 		list = (struct ctl_lun_list *)addr;
2972 
2973 		/*
2974 		 * Allocate a fixed length sbuf here, based on the length
2975 		 * of the user's buffer.  We could allocate an auto-extending
2976 		 * buffer, and then tell the user how much larger our
2977 		 * amount of data is than his buffer, but that presents
2978 		 * some problems:
2979 		 *
2980 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2981 		 *     we can't hold a lock while calling them with an
2982 		 *     auto-extending buffer.
2983  		 *
2984 		 * 2.  There is not currently a LUN reference counting
2985 		 *     mechanism, outside of outstanding transactions on
2986 		 *     the LUN's OOA queue.  So a LUN could go away on us
2987 		 *     while we're getting the LUN number, backend-specific
2988 		 *     information, etc.  Thus, given the way things
2989 		 *     currently work, we need to hold the CTL lock while
2990 		 *     grabbing LUN information.
2991 		 *
2992 		 * So, from the user's standpoint, the best thing to do is
2993 		 * allocate what he thinks is a reasonable buffer length,
2994 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
2995 		 * double the buffer length and try again.  (And repeat
2996 		 * that until he succeeds.)
2997 		 */
2998 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
2999 		if (sb == NULL) {
3000 			list->status = CTL_LUN_LIST_ERROR;
3001 			snprintf(list->error_str, sizeof(list->error_str),
3002 				 "Unable to allocate %d bytes for LUN list",
3003 				 list->alloc_len);
3004 			break;
3005 		}
3006 
3007 		sbuf_printf(sb, "<ctllunlist>\n");
3008 
3009 		mtx_lock(&softc->ctl_lock);
3010 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3011 			mtx_lock(&lun->lun_lock);
3012 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3013 					     (uintmax_t)lun->lun);
3014 
3015 			/*
3016 			 * Bail out as soon as we see that we've overfilled
3017 			 * the buffer.
3018 			 */
3019 			if (retval != 0)
3020 				break;
3021 
3022 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3023 					     "</backend_type>\n",
3024 					     (lun->backend == NULL) ?  "none" :
3025 					     lun->backend->name);
3026 
3027 			if (retval != 0)
3028 				break;
3029 
3030 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3031 					     lun->be_lun->lun_type);
3032 
3033 			if (retval != 0)
3034 				break;
3035 
3036 			if (lun->backend == NULL) {
3037 				retval = sbuf_printf(sb, "</lun>\n");
3038 				if (retval != 0)
3039 					break;
3040 				continue;
3041 			}
3042 
3043 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3044 					     (lun->be_lun->maxlba > 0) ?
3045 					     lun->be_lun->maxlba + 1 : 0);
3046 
3047 			if (retval != 0)
3048 				break;
3049 
3050 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3051 					     lun->be_lun->blocksize);
3052 
3053 			if (retval != 0)
3054 				break;
3055 
3056 			retval = sbuf_printf(sb, "\t<serial_number>");
3057 
3058 			if (retval != 0)
3059 				break;
3060 
3061 			retval = ctl_sbuf_printf_esc(sb,
3062 			    lun->be_lun->serial_num,
3063 			    sizeof(lun->be_lun->serial_num));
3064 
3065 			if (retval != 0)
3066 				break;
3067 
3068 			retval = sbuf_printf(sb, "</serial_number>\n");
3069 
3070 			if (retval != 0)
3071 				break;
3072 
3073 			retval = sbuf_printf(sb, "\t<device_id>");
3074 
3075 			if (retval != 0)
3076 				break;
3077 
3078 			retval = ctl_sbuf_printf_esc(sb,
3079 			    lun->be_lun->device_id,
3080 			    sizeof(lun->be_lun->device_id));
3081 
3082 			if (retval != 0)
3083 				break;
3084 
3085 			retval = sbuf_printf(sb, "</device_id>\n");
3086 
3087 			if (retval != 0)
3088 				break;
3089 
3090 			if (lun->backend->lun_info != NULL) {
3091 				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3092 				if (retval != 0)
3093 					break;
3094 			}
3095 
3096 			cookie = NULL;
3097 			while ((name = nvlist_next(lun->be_lun->options, &type,
3098 			    &cookie)) != NULL) {
3099 				sbuf_printf(sb, "\t<%s>", name);
3100 
3101 				if (type == NV_TYPE_STRING) {
3102 					value = dnvlist_get_string(
3103 					    lun->be_lun->options, name, NULL);
3104 					if (value != NULL)
3105 						sbuf_printf(sb, "%s", value);
3106 				}
3107 
3108 				sbuf_printf(sb, "</%s>\n", name);
3109 			}
3110 
3111 			retval = sbuf_printf(sb, "</lun>\n");
3112 
3113 			if (retval != 0)
3114 				break;
3115 			mtx_unlock(&lun->lun_lock);
3116 		}
3117 		if (lun != NULL)
3118 			mtx_unlock(&lun->lun_lock);
3119 		mtx_unlock(&softc->ctl_lock);
3120 
3121 		if ((retval != 0)
3122 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3123 			retval = 0;
3124 			sbuf_delete(sb);
3125 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3126 			snprintf(list->error_str, sizeof(list->error_str),
3127 				 "Out of space, %d bytes is too small",
3128 				 list->alloc_len);
3129 			break;
3130 		}
3131 
3132 		sbuf_finish(sb);
3133 
3134 		retval = copyout(sbuf_data(sb), list->lun_xml,
3135 				 sbuf_len(sb) + 1);
3136 
3137 		list->fill_len = sbuf_len(sb) + 1;
3138 		list->status = CTL_LUN_LIST_OK;
3139 		sbuf_delete(sb);
3140 		break;
3141 	}
3142 	case CTL_ISCSI: {
3143 		struct ctl_iscsi *ci;
3144 		struct ctl_frontend *fe;
3145 
3146 		ci = (struct ctl_iscsi *)addr;
3147 
3148 		fe = ctl_frontend_find("iscsi");
3149 		if (fe == NULL) {
3150 			ci->status = CTL_ISCSI_ERROR;
3151 			snprintf(ci->error_str, sizeof(ci->error_str),
3152 			    "Frontend \"iscsi\" not found.");
3153 			break;
3154 		}
3155 
3156 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3157 		break;
3158 	}
3159 	case CTL_PORT_REQ: {
3160 		struct ctl_req *req;
3161 		struct ctl_frontend *fe;
3162 		void *packed;
3163 		nvlist_t *tmp_args_nvl;
3164 		size_t packed_len;
3165 
3166 		req = (struct ctl_req *)addr;
3167 		tmp_args_nvl = req->args_nvl;
3168 
3169 		fe = ctl_frontend_find(req->driver);
3170 		if (fe == NULL) {
3171 			req->status = CTL_LUN_ERROR;
3172 			snprintf(req->error_str, sizeof(req->error_str),
3173 			    "Frontend \"%s\" not found.", req->driver);
3174 			break;
3175 		}
3176 
3177 		if (req->args != NULL) {
3178 			packed = malloc(req->args_len, M_CTL, M_WAITOK);
3179 			if (copyin(req->args, packed, req->args_len) != 0) {
3180 				free(packed, M_CTL);
3181 				req->status = CTL_LUN_ERROR;
3182 				snprintf(req->error_str, sizeof(req->error_str),
3183 				    "Cannot copyin args.");
3184 				break;
3185 			}
3186 			req->args_nvl = nvlist_unpack(packed,
3187 			    req->args_len, 0);
3188 			free(packed, M_CTL);
3189 
3190 			if (req->args_nvl == NULL) {
3191 				req->status = CTL_LUN_ERROR;
3192 				snprintf(req->error_str, sizeof(req->error_str),
3193 				    "Cannot unpack args nvlist.");
3194 				break;
3195 			}
3196 		} else
3197 			req->args_nvl = nvlist_create(0);
3198 
3199 		if (fe->ioctl)
3200 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3201 		else
3202 			retval = ENODEV;
3203 
3204 		nvlist_destroy(req->args_nvl);
3205 		req->args_nvl = tmp_args_nvl;
3206 
3207 		if (req->result_nvl != NULL) {
3208 			if (req->result != NULL) {
3209 				packed = nvlist_pack(req->result_nvl,
3210 				    &packed_len);
3211 				if (packed == NULL) {
3212 					req->status = CTL_LUN_ERROR;
3213 					snprintf(req->error_str,
3214 					    sizeof(req->error_str),
3215 					    "Cannot pack result nvlist.");
3216 					break;
3217 				}
3218 
3219 				if (packed_len > req->result_len) {
3220 					req->status = CTL_LUN_ERROR;
3221 					snprintf(req->error_str,
3222 					    sizeof(req->error_str),
3223 					    "Result nvlist too large.");
3224 					free(packed, M_NVLIST);
3225 					break;
3226 				}
3227 
3228 				if (copyout(packed, req->result, packed_len)) {
3229 					req->status = CTL_LUN_ERROR;
3230 					snprintf(req->error_str,
3231 					    sizeof(req->error_str),
3232 					    "Cannot copyout() the result.");
3233 					free(packed, M_NVLIST);
3234 					break;
3235 				}
3236 
3237 				req->result_len = packed_len;
3238 				free(packed, M_NVLIST);
3239 			}
3240 
3241 			nvlist_destroy(req->result_nvl);
3242 		}
3243 		break;
3244 	}
3245 	case CTL_PORT_LIST: {
3246 		struct sbuf *sb;
3247 		struct ctl_port *port;
3248 		struct ctl_lun_list *list;
3249 		const char *name, *value;
3250 		void *cookie;
3251 		int j, type;
3252 		uint32_t plun;
3253 
3254 		list = (struct ctl_lun_list *)addr;
3255 
3256 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3257 		if (sb == NULL) {
3258 			list->status = CTL_LUN_LIST_ERROR;
3259 			snprintf(list->error_str, sizeof(list->error_str),
3260 				 "Unable to allocate %d bytes for LUN list",
3261 				 list->alloc_len);
3262 			break;
3263 		}
3264 
3265 		sbuf_printf(sb, "<ctlportlist>\n");
3266 
3267 		mtx_lock(&softc->ctl_lock);
3268 		STAILQ_FOREACH(port, &softc->port_list, links) {
3269 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3270 					     (uintmax_t)port->targ_port);
3271 
3272 			/*
3273 			 * Bail out as soon as we see that we've overfilled
3274 			 * the buffer.
3275 			 */
3276 			if (retval != 0)
3277 				break;
3278 
3279 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3280 			    "</frontend_type>\n", port->frontend->name);
3281 			if (retval != 0)
3282 				break;
3283 
3284 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3285 					     port->port_type);
3286 			if (retval != 0)
3287 				break;
3288 
3289 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3290 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3291 			if (retval != 0)
3292 				break;
3293 
3294 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3295 			    port->port_name);
3296 			if (retval != 0)
3297 				break;
3298 
3299 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3300 			    port->physical_port);
3301 			if (retval != 0)
3302 				break;
3303 
3304 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3305 			    port->virtual_port);
3306 			if (retval != 0)
3307 				break;
3308 
3309 			if (port->target_devid != NULL) {
3310 				sbuf_printf(sb, "\t<target>");
3311 				ctl_id_sbuf(port->target_devid, sb);
3312 				sbuf_printf(sb, "</target>\n");
3313 			}
3314 
3315 			if (port->port_devid != NULL) {
3316 				sbuf_printf(sb, "\t<port>");
3317 				ctl_id_sbuf(port->port_devid, sb);
3318 				sbuf_printf(sb, "</port>\n");
3319 			}
3320 
3321 			if (port->port_info != NULL) {
3322 				retval = port->port_info(port->onoff_arg, sb);
3323 				if (retval != 0)
3324 					break;
3325 			}
3326 
3327 			cookie = NULL;
3328 			while ((name = nvlist_next(port->options, &type,
3329 			    &cookie)) != NULL) {
3330 				sbuf_printf(sb, "\t<%s>", name);
3331 
3332 				if (type == NV_TYPE_STRING) {
3333 					value = dnvlist_get_string(port->options,
3334 					    name, NULL);
3335 					if (value != NULL)
3336 						sbuf_printf(sb, "%s", value);
3337 				}
3338 
3339 				sbuf_printf(sb, "</%s>\n", name);
3340 			}
3341 
3342 			if (port->lun_map != NULL) {
3343 				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3344 				for (j = 0; j < port->lun_map_size; j++) {
3345 					plun = ctl_lun_map_from_port(port, j);
3346 					if (plun == UINT32_MAX)
3347 						continue;
3348 					sbuf_printf(sb,
3349 					    "\t<lun id=\"%u\">%u</lun>\n",
3350 					    j, plun);
3351 				}
3352 			}
3353 
3354 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3355 				if (port->wwpn_iid[j].in_use == 0 ||
3356 				    (port->wwpn_iid[j].wwpn == 0 &&
3357 				     port->wwpn_iid[j].name == NULL))
3358 					continue;
3359 
3360 				if (port->wwpn_iid[j].name != NULL)
3361 					retval = sbuf_printf(sb,
3362 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3363 					    j, port->wwpn_iid[j].name);
3364 				else
3365 					retval = sbuf_printf(sb,
3366 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3367 					    j, port->wwpn_iid[j].wwpn);
3368 				if (retval != 0)
3369 					break;
3370 			}
3371 			if (retval != 0)
3372 				break;
3373 
3374 			retval = sbuf_printf(sb, "</targ_port>\n");
3375 			if (retval != 0)
3376 				break;
3377 		}
3378 		mtx_unlock(&softc->ctl_lock);
3379 
3380 		if ((retval != 0)
3381 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3382 			retval = 0;
3383 			sbuf_delete(sb);
3384 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3385 			snprintf(list->error_str, sizeof(list->error_str),
3386 				 "Out of space, %d bytes is too small",
3387 				 list->alloc_len);
3388 			break;
3389 		}
3390 
3391 		sbuf_finish(sb);
3392 
3393 		retval = copyout(sbuf_data(sb), list->lun_xml,
3394 				 sbuf_len(sb) + 1);
3395 
3396 		list->fill_len = sbuf_len(sb) + 1;
3397 		list->status = CTL_LUN_LIST_OK;
3398 		sbuf_delete(sb);
3399 		break;
3400 	}
3401 	case CTL_LUN_MAP: {
3402 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3403 		struct ctl_port *port;
3404 
3405 		mtx_lock(&softc->ctl_lock);
3406 		if (lm->port < softc->port_min ||
3407 		    lm->port >= softc->port_max ||
3408 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3409 			mtx_unlock(&softc->ctl_lock);
3410 			return (ENXIO);
3411 		}
3412 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3413 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3414 				if (ctl_lun_map_to_port(port, lun->lun) ==
3415 				    UINT32_MAX)
3416 					continue;
3417 				mtx_lock(&lun->lun_lock);
3418 				ctl_est_ua_port(lun, lm->port, -1,
3419 				    CTL_UA_LUN_CHANGE);
3420 				mtx_unlock(&lun->lun_lock);
3421 			}
3422 		}
3423 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3424 		if (lm->plun != UINT32_MAX) {
3425 			if (lm->lun == UINT32_MAX)
3426 				retval = ctl_lun_map_unset(port, lm->plun);
3427 			else if (lm->lun < ctl_max_luns &&
3428 			    softc->ctl_luns[lm->lun] != NULL)
3429 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3430 			else
3431 				return (ENXIO);
3432 		} else {
3433 			if (lm->lun == UINT32_MAX)
3434 				retval = ctl_lun_map_deinit(port);
3435 			else
3436 				retval = ctl_lun_map_init(port);
3437 		}
3438 		if (port->status & CTL_PORT_STATUS_ONLINE)
3439 			ctl_isc_announce_port(port);
3440 		break;
3441 	}
3442 	case CTL_GET_LUN_STATS: {
3443 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3444 		int i;
3445 
3446 		/*
3447 		 * XXX KDM no locking here.  If the LUN list changes,
3448 		 * things can blow up.
3449 		 */
3450 		i = 0;
3451 		stats->status = CTL_SS_OK;
3452 		stats->fill_len = 0;
3453 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3454 			if (lun->lun < stats->first_item)
3455 				continue;
3456 			if (stats->fill_len + sizeof(lun->stats) >
3457 			    stats->alloc_len) {
3458 				stats->status = CTL_SS_NEED_MORE_SPACE;
3459 				break;
3460 			}
3461 			retval = copyout(&lun->stats, &stats->stats[i++],
3462 					 sizeof(lun->stats));
3463 			if (retval != 0)
3464 				break;
3465 			stats->fill_len += sizeof(lun->stats);
3466 		}
3467 		stats->num_items = softc->num_luns;
3468 		stats->flags = CTL_STATS_FLAG_NONE;
3469 #ifdef CTL_TIME_IO
3470 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3471 #endif
3472 		getnanouptime(&stats->timestamp);
3473 		break;
3474 	}
3475 	case CTL_GET_PORT_STATS: {
3476 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3477 		int i;
3478 
3479 		/*
3480 		 * XXX KDM no locking here.  If the LUN list changes,
3481 		 * things can blow up.
3482 		 */
3483 		i = 0;
3484 		stats->status = CTL_SS_OK;
3485 		stats->fill_len = 0;
3486 		STAILQ_FOREACH(port, &softc->port_list, links) {
3487 			if (port->targ_port < stats->first_item)
3488 				continue;
3489 			if (stats->fill_len + sizeof(port->stats) >
3490 			    stats->alloc_len) {
3491 				stats->status = CTL_SS_NEED_MORE_SPACE;
3492 				break;
3493 			}
3494 			retval = copyout(&port->stats, &stats->stats[i++],
3495 					 sizeof(port->stats));
3496 			if (retval != 0)
3497 				break;
3498 			stats->fill_len += sizeof(port->stats);
3499 		}
3500 		stats->num_items = softc->num_ports;
3501 		stats->flags = CTL_STATS_FLAG_NONE;
3502 #ifdef CTL_TIME_IO
3503 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3504 #endif
3505 		getnanouptime(&stats->timestamp);
3506 		break;
3507 	}
3508 	default: {
3509 		/* XXX KDM should we fix this? */
3510 #if 0
3511 		struct ctl_backend_driver *backend;
3512 		unsigned int type;
3513 		int found;
3514 
3515 		found = 0;
3516 
3517 		/*
3518 		 * We encode the backend type as the ioctl type for backend
3519 		 * ioctls.  So parse it out here, and then search for a
3520 		 * backend of this type.
3521 		 */
3522 		type = _IOC_TYPE(cmd);
3523 
3524 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3525 			if (backend->type == type) {
3526 				found = 1;
3527 				break;
3528 			}
3529 		}
3530 		if (found == 0) {
3531 			printf("ctl: unknown ioctl command %#lx or backend "
3532 			       "%d\n", cmd, type);
3533 			retval = EINVAL;
3534 			break;
3535 		}
3536 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3537 #endif
3538 		retval = ENOTTY;
3539 		break;
3540 	}
3541 	}
3542 	return (retval);
3543 }
3544 
3545 uint32_t
3546 ctl_get_initindex(struct ctl_nexus *nexus)
3547 {
3548 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3549 }
3550 
3551 int
3552 ctl_lun_map_init(struct ctl_port *port)
3553 {
3554 	struct ctl_softc *softc = port->ctl_softc;
3555 	struct ctl_lun *lun;
3556 	int size = ctl_lun_map_size;
3557 	uint32_t i;
3558 
3559 	if (port->lun_map == NULL || port->lun_map_size < size) {
3560 		port->lun_map_size = 0;
3561 		free(port->lun_map, M_CTL);
3562 		port->lun_map = malloc(size * sizeof(uint32_t),
3563 		    M_CTL, M_NOWAIT);
3564 	}
3565 	if (port->lun_map == NULL)
3566 		return (ENOMEM);
3567 	for (i = 0; i < size; i++)
3568 		port->lun_map[i] = UINT32_MAX;
3569 	port->lun_map_size = size;
3570 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3571 		if (port->lun_disable != NULL) {
3572 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3573 				port->lun_disable(port->targ_lun_arg, lun->lun);
3574 		}
3575 		ctl_isc_announce_port(port);
3576 	}
3577 	return (0);
3578 }
3579 
3580 int
3581 ctl_lun_map_deinit(struct ctl_port *port)
3582 {
3583 	struct ctl_softc *softc = port->ctl_softc;
3584 	struct ctl_lun *lun;
3585 
3586 	if (port->lun_map == NULL)
3587 		return (0);
3588 	port->lun_map_size = 0;
3589 	free(port->lun_map, M_CTL);
3590 	port->lun_map = NULL;
3591 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3592 		if (port->lun_enable != NULL) {
3593 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3594 				port->lun_enable(port->targ_lun_arg, lun->lun);
3595 		}
3596 		ctl_isc_announce_port(port);
3597 	}
3598 	return (0);
3599 }
3600 
3601 int
3602 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3603 {
3604 	int status;
3605 	uint32_t old;
3606 
3607 	if (port->lun_map == NULL) {
3608 		status = ctl_lun_map_init(port);
3609 		if (status != 0)
3610 			return (status);
3611 	}
3612 	if (plun >= port->lun_map_size)
3613 		return (EINVAL);
3614 	old = port->lun_map[plun];
3615 	port->lun_map[plun] = glun;
3616 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3617 		if (port->lun_enable != NULL)
3618 			port->lun_enable(port->targ_lun_arg, plun);
3619 		ctl_isc_announce_port(port);
3620 	}
3621 	return (0);
3622 }
3623 
3624 int
3625 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3626 {
3627 	uint32_t old;
3628 
3629 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3630 		return (0);
3631 	old = port->lun_map[plun];
3632 	port->lun_map[plun] = UINT32_MAX;
3633 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3634 		if (port->lun_disable != NULL)
3635 			port->lun_disable(port->targ_lun_arg, plun);
3636 		ctl_isc_announce_port(port);
3637 	}
3638 	return (0);
3639 }
3640 
3641 uint32_t
3642 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3643 {
3644 
3645 	if (port == NULL)
3646 		return (UINT32_MAX);
3647 	if (port->lun_map == NULL)
3648 		return (lun_id);
3649 	if (lun_id > port->lun_map_size)
3650 		return (UINT32_MAX);
3651 	return (port->lun_map[lun_id]);
3652 }
3653 
3654 uint32_t
3655 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3656 {
3657 	uint32_t i;
3658 
3659 	if (port == NULL)
3660 		return (UINT32_MAX);
3661 	if (port->lun_map == NULL)
3662 		return (lun_id);
3663 	for (i = 0; i < port->lun_map_size; i++) {
3664 		if (port->lun_map[i] == lun_id)
3665 			return (i);
3666 	}
3667 	return (UINT32_MAX);
3668 }
3669 
3670 uint32_t
3671 ctl_decode_lun(uint64_t encoded)
3672 {
3673 	uint8_t lun[8];
3674 	uint32_t result = 0xffffffff;
3675 
3676 	be64enc(lun, encoded);
3677 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3678 	case RPL_LUNDATA_ATYP_PERIPH:
3679 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3680 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3681 			result = lun[1];
3682 		break;
3683 	case RPL_LUNDATA_ATYP_FLAT:
3684 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3685 		    lun[6] == 0 && lun[7] == 0)
3686 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3687 		break;
3688 	case RPL_LUNDATA_ATYP_EXTLUN:
3689 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3690 		case 0x02:
3691 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3692 			case 0x00:
3693 				result = lun[1];
3694 				break;
3695 			case 0x10:
3696 				result = (lun[1] << 16) + (lun[2] << 8) +
3697 				    lun[3];
3698 				break;
3699 			case 0x20:
3700 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3701 					result = (lun[2] << 24) +
3702 					    (lun[3] << 16) + (lun[4] << 8) +
3703 					    lun[5];
3704 				break;
3705 			}
3706 			break;
3707 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3708 			result = 0xffffffff;
3709 			break;
3710 		}
3711 		break;
3712 	}
3713 	return (result);
3714 }
3715 
3716 uint64_t
3717 ctl_encode_lun(uint32_t decoded)
3718 {
3719 	uint64_t l = decoded;
3720 
3721 	if (l <= 0xff)
3722 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3723 	if (l <= 0x3fff)
3724 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3725 	if (l <= 0xffffff)
3726 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3727 		    (l << 32));
3728 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3729 }
3730 
3731 int
3732 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3733 {
3734 	int i;
3735 
3736 	for (i = first; i < last; i++) {
3737 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3738 			return (i);
3739 	}
3740 	return (-1);
3741 }
3742 
3743 int
3744 ctl_set_mask(uint32_t *mask, uint32_t bit)
3745 {
3746 	uint32_t chunk, piece;
3747 
3748 	chunk = bit >> 5;
3749 	piece = bit % (sizeof(uint32_t) * 8);
3750 
3751 	if ((mask[chunk] & (1 << piece)) != 0)
3752 		return (-1);
3753 	else
3754 		mask[chunk] |= (1 << piece);
3755 
3756 	return (0);
3757 }
3758 
3759 int
3760 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3761 {
3762 	uint32_t chunk, piece;
3763 
3764 	chunk = bit >> 5;
3765 	piece = bit % (sizeof(uint32_t) * 8);
3766 
3767 	if ((mask[chunk] & (1 << piece)) == 0)
3768 		return (-1);
3769 	else
3770 		mask[chunk] &= ~(1 << piece);
3771 
3772 	return (0);
3773 }
3774 
3775 int
3776 ctl_is_set(uint32_t *mask, uint32_t bit)
3777 {
3778 	uint32_t chunk, piece;
3779 
3780 	chunk = bit >> 5;
3781 	piece = bit % (sizeof(uint32_t) * 8);
3782 
3783 	if ((mask[chunk] & (1 << piece)) == 0)
3784 		return (0);
3785 	else
3786 		return (1);
3787 }
3788 
3789 static uint64_t
3790 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3791 {
3792 	uint64_t *t;
3793 
3794 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3795 	if (t == NULL)
3796 		return (0);
3797 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3798 }
3799 
3800 static void
3801 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3802 {
3803 	uint64_t *t;
3804 
3805 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3806 	if (t == NULL)
3807 		return;
3808 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3809 }
3810 
3811 static void
3812 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3813 {
3814 	uint64_t *p;
3815 	u_int i;
3816 
3817 	i = residx/CTL_MAX_INIT_PER_PORT;
3818 	if (lun->pr_keys[i] != NULL)
3819 		return;
3820 	mtx_unlock(&lun->lun_lock);
3821 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3822 	    M_WAITOK | M_ZERO);
3823 	mtx_lock(&lun->lun_lock);
3824 	if (lun->pr_keys[i] == NULL)
3825 		lun->pr_keys[i] = p;
3826 	else
3827 		free(p, M_CTL);
3828 }
3829 
3830 static void
3831 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3832 {
3833 	uint64_t *t;
3834 
3835 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3836 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3837 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3838 }
3839 
3840 /*
3841  * ctl_softc, pool_name, total_ctl_io are passed in.
3842  * npool is passed out.
3843  */
3844 int
3845 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3846 		uint32_t total_ctl_io, void **npool)
3847 {
3848 	struct ctl_io_pool *pool;
3849 
3850 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3851 					    M_NOWAIT | M_ZERO);
3852 	if (pool == NULL)
3853 		return (ENOMEM);
3854 
3855 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3856 	pool->ctl_softc = ctl_softc;
3857 #ifdef IO_POOLS
3858 	pool->zone = uma_zsecond_create(pool->name, NULL,
3859 	    NULL, NULL, NULL, ctl_softc->io_zone);
3860 	/* uma_prealloc(pool->zone, total_ctl_io); */
3861 #else
3862 	pool->zone = ctl_softc->io_zone;
3863 #endif
3864 
3865 	*npool = pool;
3866 	return (0);
3867 }
3868 
3869 void
3870 ctl_pool_free(struct ctl_io_pool *pool)
3871 {
3872 
3873 	if (pool == NULL)
3874 		return;
3875 
3876 #ifdef IO_POOLS
3877 	uma_zdestroy(pool->zone);
3878 #endif
3879 	free(pool, M_CTL);
3880 }
3881 
3882 union ctl_io *
3883 ctl_alloc_io(void *pool_ref)
3884 {
3885 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3886 	union ctl_io *io;
3887 
3888 	io = uma_zalloc(pool->zone, M_WAITOK);
3889 	if (io != NULL) {
3890 		io->io_hdr.pool = pool_ref;
3891 		CTL_SOFTC(io) = pool->ctl_softc;
3892 	}
3893 	return (io);
3894 }
3895 
3896 union ctl_io *
3897 ctl_alloc_io_nowait(void *pool_ref)
3898 {
3899 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3900 	union ctl_io *io;
3901 
3902 	io = uma_zalloc(pool->zone, M_NOWAIT);
3903 	if (io != NULL) {
3904 		io->io_hdr.pool = pool_ref;
3905 		CTL_SOFTC(io) = pool->ctl_softc;
3906 	}
3907 	return (io);
3908 }
3909 
3910 void
3911 ctl_free_io(union ctl_io *io)
3912 {
3913 	struct ctl_io_pool *pool;
3914 
3915 	if (io == NULL)
3916 		return;
3917 
3918 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3919 	uma_zfree(pool->zone, io);
3920 }
3921 
3922 void
3923 ctl_zero_io(union ctl_io *io)
3924 {
3925 	struct ctl_io_pool *pool;
3926 
3927 	if (io == NULL)
3928 		return;
3929 
3930 	/*
3931 	 * May need to preserve linked list pointers at some point too.
3932 	 */
3933 	pool = io->io_hdr.pool;
3934 	memset(io, 0, sizeof(*io));
3935 	io->io_hdr.pool = pool;
3936 	CTL_SOFTC(io) = pool->ctl_softc;
3937 }
3938 
3939 int
3940 ctl_expand_number(const char *buf, uint64_t *num)
3941 {
3942 	char *endptr;
3943 	uint64_t number;
3944 	unsigned shift;
3945 
3946 	number = strtoq(buf, &endptr, 0);
3947 
3948 	switch (tolower((unsigned char)*endptr)) {
3949 	case 'e':
3950 		shift = 60;
3951 		break;
3952 	case 'p':
3953 		shift = 50;
3954 		break;
3955 	case 't':
3956 		shift = 40;
3957 		break;
3958 	case 'g':
3959 		shift = 30;
3960 		break;
3961 	case 'm':
3962 		shift = 20;
3963 		break;
3964 	case 'k':
3965 		shift = 10;
3966 		break;
3967 	case 'b':
3968 	case '\0': /* No unit. */
3969 		*num = number;
3970 		return (0);
3971 	default:
3972 		/* Unrecognized unit. */
3973 		return (-1);
3974 	}
3975 
3976 	if ((number << shift) >> shift != number) {
3977 		/* Overflow */
3978 		return (-1);
3979 	}
3980 	*num = number << shift;
3981 	return (0);
3982 }
3983 
3984 
3985 /*
3986  * This routine could be used in the future to load default and/or saved
3987  * mode page parameters for a particuar lun.
3988  */
3989 static int
3990 ctl_init_page_index(struct ctl_lun *lun)
3991 {
3992 	int i, page_code;
3993 	struct ctl_page_index *page_index;
3994 	const char *value;
3995 	uint64_t ival;
3996 
3997 	memcpy(&lun->mode_pages.index, page_index_template,
3998 	       sizeof(page_index_template));
3999 
4000 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4001 
4002 		page_index = &lun->mode_pages.index[i];
4003 		if (lun->be_lun->lun_type == T_DIRECT &&
4004 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4005 			continue;
4006 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4007 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4008 			continue;
4009 		if (lun->be_lun->lun_type == T_CDROM &&
4010 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4011 			continue;
4012 
4013 		page_code = page_index->page_code & SMPH_PC_MASK;
4014 		switch (page_code) {
4015 		case SMS_RW_ERROR_RECOVERY_PAGE: {
4016 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4017 			    ("subpage %#x for page %#x is incorrect!",
4018 			    page_index->subpage, page_code));
4019 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4020 			       &rw_er_page_default,
4021 			       sizeof(rw_er_page_default));
4022 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4023 			       &rw_er_page_changeable,
4024 			       sizeof(rw_er_page_changeable));
4025 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4026 			       &rw_er_page_default,
4027 			       sizeof(rw_er_page_default));
4028 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4029 			       &rw_er_page_default,
4030 			       sizeof(rw_er_page_default));
4031 			page_index->page_data =
4032 				(uint8_t *)lun->mode_pages.rw_er_page;
4033 			break;
4034 		}
4035 		case SMS_FORMAT_DEVICE_PAGE: {
4036 			struct scsi_format_page *format_page;
4037 
4038 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4039 			    ("subpage %#x for page %#x is incorrect!",
4040 			    page_index->subpage, page_code));
4041 
4042 			/*
4043 			 * Sectors per track are set above.  Bytes per
4044 			 * sector need to be set here on a per-LUN basis.
4045 			 */
4046 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4047 			       &format_page_default,
4048 			       sizeof(format_page_default));
4049 			memcpy(&lun->mode_pages.format_page[
4050 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4051 			       sizeof(format_page_changeable));
4052 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4053 			       &format_page_default,
4054 			       sizeof(format_page_default));
4055 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4056 			       &format_page_default,
4057 			       sizeof(format_page_default));
4058 
4059 			format_page = &lun->mode_pages.format_page[
4060 				CTL_PAGE_CURRENT];
4061 			scsi_ulto2b(lun->be_lun->blocksize,
4062 				    format_page->bytes_per_sector);
4063 
4064 			format_page = &lun->mode_pages.format_page[
4065 				CTL_PAGE_DEFAULT];
4066 			scsi_ulto2b(lun->be_lun->blocksize,
4067 				    format_page->bytes_per_sector);
4068 
4069 			format_page = &lun->mode_pages.format_page[
4070 				CTL_PAGE_SAVED];
4071 			scsi_ulto2b(lun->be_lun->blocksize,
4072 				    format_page->bytes_per_sector);
4073 
4074 			page_index->page_data =
4075 				(uint8_t *)lun->mode_pages.format_page;
4076 			break;
4077 		}
4078 		case SMS_RIGID_DISK_PAGE: {
4079 			struct scsi_rigid_disk_page *rigid_disk_page;
4080 			uint32_t sectors_per_cylinder;
4081 			uint64_t cylinders;
4082 #ifndef	__XSCALE__
4083 			int shift;
4084 #endif /* !__XSCALE__ */
4085 
4086 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4087 			    ("subpage %#x for page %#x is incorrect!",
4088 			    page_index->subpage, page_code));
4089 
4090 			/*
4091 			 * Rotation rate and sectors per track are set
4092 			 * above.  We calculate the cylinders here based on
4093 			 * capacity.  Due to the number of heads and
4094 			 * sectors per track we're using, smaller arrays
4095 			 * may turn out to have 0 cylinders.  Linux and
4096 			 * FreeBSD don't pay attention to these mode pages
4097 			 * to figure out capacity, but Solaris does.  It
4098 			 * seems to deal with 0 cylinders just fine, and
4099 			 * works out a fake geometry based on the capacity.
4100 			 */
4101 			memcpy(&lun->mode_pages.rigid_disk_page[
4102 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4103 			       sizeof(rigid_disk_page_default));
4104 			memcpy(&lun->mode_pages.rigid_disk_page[
4105 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4106 			       sizeof(rigid_disk_page_changeable));
4107 
4108 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4109 				CTL_DEFAULT_HEADS;
4110 
4111 			/*
4112 			 * The divide method here will be more accurate,
4113 			 * probably, but results in floating point being
4114 			 * used in the kernel on i386 (__udivdi3()).  On the
4115 			 * XScale, though, __udivdi3() is implemented in
4116 			 * software.
4117 			 *
4118 			 * The shift method for cylinder calculation is
4119 			 * accurate if sectors_per_cylinder is a power of
4120 			 * 2.  Otherwise it might be slightly off -- you
4121 			 * might have a bit of a truncation problem.
4122 			 */
4123 #ifdef	__XSCALE__
4124 			cylinders = (lun->be_lun->maxlba + 1) /
4125 				sectors_per_cylinder;
4126 #else
4127 			for (shift = 31; shift > 0; shift--) {
4128 				if (sectors_per_cylinder & (1 << shift))
4129 					break;
4130 			}
4131 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4132 #endif
4133 
4134 			/*
4135 			 * We've basically got 3 bytes, or 24 bits for the
4136 			 * cylinder size in the mode page.  If we're over,
4137 			 * just round down to 2^24.
4138 			 */
4139 			if (cylinders > 0xffffff)
4140 				cylinders = 0xffffff;
4141 
4142 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4143 				CTL_PAGE_DEFAULT];
4144 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4145 
4146 			if ((value = dnvlist_get_string(lun->be_lun->options,
4147 			    "rpm", NULL)) != NULL) {
4148 				scsi_ulto2b(strtol(value, NULL, 0),
4149 				     rigid_disk_page->rotation_rate);
4150 			}
4151 
4152 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4153 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4154 			       sizeof(rigid_disk_page_default));
4155 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4156 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4157 			       sizeof(rigid_disk_page_default));
4158 
4159 			page_index->page_data =
4160 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4161 			break;
4162 		}
4163 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4164 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4165 			    ("subpage %#x for page %#x is incorrect!",
4166 			    page_index->subpage, page_code));
4167 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4168 			       &verify_er_page_default,
4169 			       sizeof(verify_er_page_default));
4170 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4171 			       &verify_er_page_changeable,
4172 			       sizeof(verify_er_page_changeable));
4173 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4174 			       &verify_er_page_default,
4175 			       sizeof(verify_er_page_default));
4176 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4177 			       &verify_er_page_default,
4178 			       sizeof(verify_er_page_default));
4179 			page_index->page_data =
4180 				(uint8_t *)lun->mode_pages.verify_er_page;
4181 			break;
4182 		}
4183 		case SMS_CACHING_PAGE: {
4184 			struct scsi_caching_page *caching_page;
4185 
4186 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4187 			    ("subpage %#x for page %#x is incorrect!",
4188 			    page_index->subpage, page_code));
4189 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4190 			       &caching_page_default,
4191 			       sizeof(caching_page_default));
4192 			memcpy(&lun->mode_pages.caching_page[
4193 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4194 			       sizeof(caching_page_changeable));
4195 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4196 			       &caching_page_default,
4197 			       sizeof(caching_page_default));
4198 			caching_page = &lun->mode_pages.caching_page[
4199 			    CTL_PAGE_SAVED];
4200 			value = dnvlist_get_string(lun->be_lun->options,
4201 			    "writecache", NULL);
4202 			if (value != NULL && strcmp(value, "off") == 0)
4203 				caching_page->flags1 &= ~SCP_WCE;
4204 			value = dnvlist_get_string(lun->be_lun->options,
4205 			    "readcache", NULL);
4206 			if (value != NULL && strcmp(value, "off") == 0)
4207 				caching_page->flags1 |= SCP_RCD;
4208 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4209 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4210 			       sizeof(caching_page_default));
4211 			page_index->page_data =
4212 				(uint8_t *)lun->mode_pages.caching_page;
4213 			break;
4214 		}
4215 		case SMS_CONTROL_MODE_PAGE: {
4216 			switch (page_index->subpage) {
4217 			case SMS_SUBPAGE_PAGE_0: {
4218 				struct scsi_control_page *control_page;
4219 
4220 				memcpy(&lun->mode_pages.control_page[
4221 				    CTL_PAGE_DEFAULT],
4222 				       &control_page_default,
4223 				       sizeof(control_page_default));
4224 				memcpy(&lun->mode_pages.control_page[
4225 				    CTL_PAGE_CHANGEABLE],
4226 				       &control_page_changeable,
4227 				       sizeof(control_page_changeable));
4228 				memcpy(&lun->mode_pages.control_page[
4229 				    CTL_PAGE_SAVED],
4230 				       &control_page_default,
4231 				       sizeof(control_page_default));
4232 				control_page = &lun->mode_pages.control_page[
4233 				    CTL_PAGE_SAVED];
4234 				value = dnvlist_get_string(lun->be_lun->options,
4235 				    "reordering", NULL);
4236 				if (value != NULL &&
4237 				    strcmp(value, "unrestricted") == 0) {
4238 					control_page->queue_flags &=
4239 					    ~SCP_QUEUE_ALG_MASK;
4240 					control_page->queue_flags |=
4241 					    SCP_QUEUE_ALG_UNRESTRICTED;
4242 				}
4243 				memcpy(&lun->mode_pages.control_page[
4244 				    CTL_PAGE_CURRENT],
4245 				       &lun->mode_pages.control_page[
4246 				    CTL_PAGE_SAVED],
4247 				       sizeof(control_page_default));
4248 				page_index->page_data =
4249 				    (uint8_t *)lun->mode_pages.control_page;
4250 				break;
4251 			}
4252 			case 0x01:
4253 				memcpy(&lun->mode_pages.control_ext_page[
4254 				    CTL_PAGE_DEFAULT],
4255 				       &control_ext_page_default,
4256 				       sizeof(control_ext_page_default));
4257 				memcpy(&lun->mode_pages.control_ext_page[
4258 				    CTL_PAGE_CHANGEABLE],
4259 				       &control_ext_page_changeable,
4260 				       sizeof(control_ext_page_changeable));
4261 				memcpy(&lun->mode_pages.control_ext_page[
4262 				    CTL_PAGE_SAVED],
4263 				       &control_ext_page_default,
4264 				       sizeof(control_ext_page_default));
4265 				memcpy(&lun->mode_pages.control_ext_page[
4266 				    CTL_PAGE_CURRENT],
4267 				       &lun->mode_pages.control_ext_page[
4268 				    CTL_PAGE_SAVED],
4269 				       sizeof(control_ext_page_default));
4270 				page_index->page_data =
4271 				    (uint8_t *)lun->mode_pages.control_ext_page;
4272 				break;
4273 			default:
4274 				panic("subpage %#x for page %#x is incorrect!",
4275 				      page_index->subpage, page_code);
4276 			}
4277 			break;
4278 		}
4279 		case SMS_INFO_EXCEPTIONS_PAGE: {
4280 			switch (page_index->subpage) {
4281 			case SMS_SUBPAGE_PAGE_0:
4282 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4283 				       &ie_page_default,
4284 				       sizeof(ie_page_default));
4285 				memcpy(&lun->mode_pages.ie_page[
4286 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4287 				       sizeof(ie_page_changeable));
4288 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4289 				       &ie_page_default,
4290 				       sizeof(ie_page_default));
4291 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4292 				       &ie_page_default,
4293 				       sizeof(ie_page_default));
4294 				page_index->page_data =
4295 					(uint8_t *)lun->mode_pages.ie_page;
4296 				break;
4297 			case 0x02: {
4298 				struct ctl_logical_block_provisioning_page *page;
4299 
4300 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4301 				       &lbp_page_default,
4302 				       sizeof(lbp_page_default));
4303 				memcpy(&lun->mode_pages.lbp_page[
4304 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4305 				       sizeof(lbp_page_changeable));
4306 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4307 				       &lbp_page_default,
4308 				       sizeof(lbp_page_default));
4309 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4310 				value = dnvlist_get_string(lun->be_lun->options,
4311 				    "avail-threshold", NULL);
4312 				if (value != NULL &&
4313 				    ctl_expand_number(value, &ival) == 0) {
4314 					page->descr[0].flags |= SLBPPD_ENABLED |
4315 					    SLBPPD_ARMING_DEC;
4316 					if (lun->be_lun->blocksize)
4317 						ival /= lun->be_lun->blocksize;
4318 					else
4319 						ival /= 512;
4320 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4321 					    page->descr[0].count);
4322 				}
4323 				value = dnvlist_get_string(lun->be_lun->options,
4324 				    "used-threshold", NULL);
4325 				if (value != NULL &&
4326 				    ctl_expand_number(value, &ival) == 0) {
4327 					page->descr[1].flags |= SLBPPD_ENABLED |
4328 					    SLBPPD_ARMING_INC;
4329 					if (lun->be_lun->blocksize)
4330 						ival /= lun->be_lun->blocksize;
4331 					else
4332 						ival /= 512;
4333 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4334 					    page->descr[1].count);
4335 				}
4336 				value = dnvlist_get_string(lun->be_lun->options,
4337 				    "pool-avail-threshold", NULL);
4338 				if (value != NULL &&
4339 				    ctl_expand_number(value, &ival) == 0) {
4340 					page->descr[2].flags |= SLBPPD_ENABLED |
4341 					    SLBPPD_ARMING_DEC;
4342 					if (lun->be_lun->blocksize)
4343 						ival /= lun->be_lun->blocksize;
4344 					else
4345 						ival /= 512;
4346 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4347 					    page->descr[2].count);
4348 				}
4349 				value = dnvlist_get_string(lun->be_lun->options,
4350 				    "pool-used-threshold", NULL);
4351 				if (value != NULL &&
4352 				    ctl_expand_number(value, &ival) == 0) {
4353 					page->descr[3].flags |= SLBPPD_ENABLED |
4354 					    SLBPPD_ARMING_INC;
4355 					if (lun->be_lun->blocksize)
4356 						ival /= lun->be_lun->blocksize;
4357 					else
4358 						ival /= 512;
4359 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4360 					    page->descr[3].count);
4361 				}
4362 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4363 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4364 				       sizeof(lbp_page_default));
4365 				page_index->page_data =
4366 					(uint8_t *)lun->mode_pages.lbp_page;
4367 				break;
4368 			}
4369 			default:
4370 				panic("subpage %#x for page %#x is incorrect!",
4371 				      page_index->subpage, page_code);
4372 			}
4373 			break;
4374 		}
4375 		case SMS_CDDVD_CAPS_PAGE:{
4376 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4377 			    ("subpage %#x for page %#x is incorrect!",
4378 			    page_index->subpage, page_code));
4379 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4380 			       &cddvd_page_default,
4381 			       sizeof(cddvd_page_default));
4382 			memcpy(&lun->mode_pages.cddvd_page[
4383 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4384 			       sizeof(cddvd_page_changeable));
4385 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4386 			       &cddvd_page_default,
4387 			       sizeof(cddvd_page_default));
4388 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4389 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4390 			       sizeof(cddvd_page_default));
4391 			page_index->page_data =
4392 				(uint8_t *)lun->mode_pages.cddvd_page;
4393 			break;
4394 		}
4395 		default:
4396 			panic("invalid page code value %#x", page_code);
4397 		}
4398 	}
4399 
4400 	return (CTL_RETVAL_COMPLETE);
4401 }
4402 
4403 static int
4404 ctl_init_log_page_index(struct ctl_lun *lun)
4405 {
4406 	struct ctl_page_index *page_index;
4407 	int i, j, k, prev;
4408 
4409 	memcpy(&lun->log_pages.index, log_page_index_template,
4410 	       sizeof(log_page_index_template));
4411 
4412 	prev = -1;
4413 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4414 
4415 		page_index = &lun->log_pages.index[i];
4416 		if (lun->be_lun->lun_type == T_DIRECT &&
4417 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4418 			continue;
4419 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4420 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4421 			continue;
4422 		if (lun->be_lun->lun_type == T_CDROM &&
4423 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4424 			continue;
4425 
4426 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4427 		    lun->backend->lun_attr == NULL)
4428 			continue;
4429 
4430 		if (page_index->page_code != prev) {
4431 			lun->log_pages.pages_page[j] = page_index->page_code;
4432 			prev = page_index->page_code;
4433 			j++;
4434 		}
4435 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4436 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4437 		k++;
4438 	}
4439 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4440 	lun->log_pages.index[0].page_len = j;
4441 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4442 	lun->log_pages.index[1].page_len = k * 2;
4443 	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4444 	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4445 	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4446 	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4447 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4448 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4449 
4450 	return (CTL_RETVAL_COMPLETE);
4451 }
4452 
4453 static int
4454 hex2bin(const char *str, uint8_t *buf, int buf_size)
4455 {
4456 	int i;
4457 	u_char c;
4458 
4459 	memset(buf, 0, buf_size);
4460 	while (isspace(str[0]))
4461 		str++;
4462 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4463 		str += 2;
4464 	buf_size *= 2;
4465 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4466 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4467 			str++;
4468 		c = str[i];
4469 		if (isdigit(c))
4470 			c -= '0';
4471 		else if (isalpha(c))
4472 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4473 		else
4474 			break;
4475 		if (c >= 16)
4476 			break;
4477 		if ((i & 1) == 0)
4478 			buf[i / 2] |= (c << 4);
4479 		else
4480 			buf[i / 2] |= c;
4481 	}
4482 	return ((i + 1) / 2);
4483 }
4484 
4485 /*
4486  * LUN allocation.
4487  *
4488  * Requirements:
4489  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4490  *   wants us to allocate the LUN and he can block.
4491  * - ctl_softc is always set
4492  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4493  *
4494  * Returns 0 for success, non-zero (errno) for failure.
4495  */
4496 static int
4497 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4498 	      struct ctl_be_lun *const be_lun)
4499 {
4500 	struct ctl_lun *nlun, *lun;
4501 	struct scsi_vpd_id_descriptor *desc;
4502 	struct scsi_vpd_id_t10 *t10id;
4503 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4504 	int lun_number, lun_malloced;
4505 	int devidlen, idlen1, idlen2 = 0, len;
4506 
4507 	if (be_lun == NULL)
4508 		return (EINVAL);
4509 
4510 	/*
4511 	 * We currently only support Direct Access or Processor LUN types.
4512 	 */
4513 	switch (be_lun->lun_type) {
4514 	case T_DIRECT:
4515 	case T_PROCESSOR:
4516 	case T_CDROM:
4517 		break;
4518 	case T_SEQUENTIAL:
4519 	case T_CHANGER:
4520 	default:
4521 		be_lun->lun_config_status(be_lun->be_lun,
4522 					  CTL_LUN_CONFIG_FAILURE);
4523 		break;
4524 	}
4525 	if (ctl_lun == NULL) {
4526 		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4527 		lun_malloced = 1;
4528 	} else {
4529 		lun_malloced = 0;
4530 		lun = ctl_lun;
4531 	}
4532 
4533 	memset(lun, 0, sizeof(*lun));
4534 	if (lun_malloced)
4535 		lun->flags = CTL_LUN_MALLOCED;
4536 
4537 	lun->pending_sense = malloc(sizeof(struct scsi_sense_data *) *
4538 	    ctl_max_ports, M_DEVBUF, M_WAITOK | M_ZERO);
4539 	lun->pending_ua = malloc(sizeof(ctl_ua_type *) * ctl_max_ports,
4540 	    M_DEVBUF, M_WAITOK | M_ZERO);
4541 	lun->pr_keys = malloc(sizeof(uint64_t *) * ctl_max_ports,
4542 	    M_DEVBUF, M_WAITOK | M_ZERO);
4543 
4544 	/* Generate LUN ID. */
4545 	devidlen = max(CTL_DEVID_MIN_LEN,
4546 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4547 	idlen1 = sizeof(*t10id) + devidlen;
4548 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4549 	scsiname = dnvlist_get_string(be_lun->options, "scsiname", NULL);
4550 	if (scsiname != NULL) {
4551 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4552 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4553 	}
4554 	eui = dnvlist_get_string(be_lun->options, "eui", NULL);
4555 	if (eui != NULL) {
4556 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4557 	}
4558 	naa = dnvlist_get_string(be_lun->options, "naa", NULL);
4559 	if (naa != NULL) {
4560 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4561 	}
4562 	uuid = dnvlist_get_string(be_lun->options, "uuid", NULL);
4563 	if (uuid != NULL) {
4564 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4565 	}
4566 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4567 	    M_CTL, M_WAITOK | M_ZERO);
4568 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4569 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4570 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4571 	desc->length = idlen1;
4572 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4573 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4574 	if ((vendor = dnvlist_get_string(be_lun->options, "vendor", NULL)) == NULL) {
4575 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4576 	} else {
4577 		strncpy(t10id->vendor, vendor,
4578 		    min(sizeof(t10id->vendor), strlen(vendor)));
4579 	}
4580 	strncpy((char *)t10id->vendor_spec_id,
4581 	    (char *)be_lun->device_id, devidlen);
4582 	if (scsiname != NULL) {
4583 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4584 		    desc->length);
4585 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4586 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4587 		    SVPD_ID_TYPE_SCSI_NAME;
4588 		desc->length = idlen2;
4589 		strlcpy(desc->identifier, scsiname, idlen2);
4590 	}
4591 	if (eui != NULL) {
4592 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4593 		    desc->length);
4594 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4595 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4596 		    SVPD_ID_TYPE_EUI64;
4597 		desc->length = hex2bin(eui, desc->identifier, 16);
4598 		desc->length = desc->length > 12 ? 16 :
4599 		    (desc->length > 8 ? 12 : 8);
4600 		len -= 16 - desc->length;
4601 	}
4602 	if (naa != NULL) {
4603 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4604 		    desc->length);
4605 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4606 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4607 		    SVPD_ID_TYPE_NAA;
4608 		desc->length = hex2bin(naa, desc->identifier, 16);
4609 		desc->length = desc->length > 8 ? 16 : 8;
4610 		len -= 16 - desc->length;
4611 	}
4612 	if (uuid != NULL) {
4613 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4614 		    desc->length);
4615 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4616 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4617 		    SVPD_ID_TYPE_UUID;
4618 		desc->identifier[0] = 0x10;
4619 		hex2bin(uuid, &desc->identifier[2], 16);
4620 		desc->length = 18;
4621 	}
4622 	lun->lun_devid->len = len;
4623 
4624 	mtx_lock(&ctl_softc->ctl_lock);
4625 	/*
4626 	 * See if the caller requested a particular LUN number.  If so, see
4627 	 * if it is available.  Otherwise, allocate the first available LUN.
4628 	 */
4629 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4630 		if ((be_lun->req_lun_id > (ctl_max_luns - 1))
4631 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4632 			mtx_unlock(&ctl_softc->ctl_lock);
4633 			if (be_lun->req_lun_id > (ctl_max_luns - 1)) {
4634 				printf("ctl: requested LUN ID %d is higher "
4635 				       "than ctl_max_luns - 1 (%d)\n",
4636 				       be_lun->req_lun_id, ctl_max_luns - 1);
4637 			} else {
4638 				/*
4639 				 * XXX KDM return an error, or just assign
4640 				 * another LUN ID in this case??
4641 				 */
4642 				printf("ctl: requested LUN ID %d is already "
4643 				       "in use\n", be_lun->req_lun_id);
4644 			}
4645 fail:
4646 			free(lun->lun_devid, M_CTL);
4647 			if (lun->flags & CTL_LUN_MALLOCED)
4648 				free(lun, M_CTL);
4649 			be_lun->lun_config_status(be_lun->be_lun,
4650 						  CTL_LUN_CONFIG_FAILURE);
4651 			return (ENOSPC);
4652 		}
4653 		lun_number = be_lun->req_lun_id;
4654 	} else {
4655 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, ctl_max_luns);
4656 		if (lun_number == -1) {
4657 			mtx_unlock(&ctl_softc->ctl_lock);
4658 			printf("ctl: can't allocate LUN, out of LUNs\n");
4659 			goto fail;
4660 		}
4661 	}
4662 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4663 	mtx_unlock(&ctl_softc->ctl_lock);
4664 
4665 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4666 	lun->lun = lun_number;
4667 	lun->be_lun = be_lun;
4668 	/*
4669 	 * The processor LUN is always enabled.  Disk LUNs come on line
4670 	 * disabled, and must be enabled by the backend.
4671 	 */
4672 	lun->flags |= CTL_LUN_DISABLED;
4673 	lun->backend = be_lun->be;
4674 	be_lun->ctl_lun = lun;
4675 	be_lun->lun_id = lun_number;
4676 	atomic_add_int(&be_lun->be->num_luns, 1);
4677 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4678 		lun->flags |= CTL_LUN_EJECTED;
4679 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4680 		lun->flags |= CTL_LUN_NO_MEDIA;
4681 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4682 		lun->flags |= CTL_LUN_STOPPED;
4683 
4684 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4685 		lun->flags |= CTL_LUN_PRIMARY_SC;
4686 
4687 	value = dnvlist_get_string(be_lun->options, "removable", NULL);
4688 	if (value != NULL) {
4689 		if (strcmp(value, "on") == 0)
4690 			lun->flags |= CTL_LUN_REMOVABLE;
4691 	} else if (be_lun->lun_type == T_CDROM)
4692 		lun->flags |= CTL_LUN_REMOVABLE;
4693 
4694 	lun->ctl_softc = ctl_softc;
4695 #ifdef CTL_TIME_IO
4696 	lun->last_busy = getsbinuptime();
4697 #endif
4698 	TAILQ_INIT(&lun->ooa_queue);
4699 	TAILQ_INIT(&lun->blocked_queue);
4700 	STAILQ_INIT(&lun->error_list);
4701 	lun->ie_reported = 1;
4702 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4703 	ctl_tpc_lun_init(lun);
4704 	if (lun->flags & CTL_LUN_REMOVABLE) {
4705 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4706 		    M_CTL, M_WAITOK);
4707 	}
4708 
4709 	/*
4710 	 * Initialize the mode and log page index.
4711 	 */
4712 	ctl_init_page_index(lun);
4713 	ctl_init_log_page_index(lun);
4714 
4715 	/* Setup statistics gathering */
4716 	lun->stats.item = lun_number;
4717 
4718 	/*
4719 	 * Now, before we insert this lun on the lun list, set the lun
4720 	 * inventory changed UA for all other luns.
4721 	 */
4722 	mtx_lock(&ctl_softc->ctl_lock);
4723 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4724 		mtx_lock(&nlun->lun_lock);
4725 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4726 		mtx_unlock(&nlun->lun_lock);
4727 	}
4728 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4729 	ctl_softc->ctl_luns[lun_number] = lun;
4730 	ctl_softc->num_luns++;
4731 	mtx_unlock(&ctl_softc->ctl_lock);
4732 
4733 	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4734 	return (0);
4735 }
4736 
4737 /*
4738  * Delete a LUN.
4739  * Assumptions:
4740  * - LUN has already been marked invalid and any pending I/O has been taken
4741  *   care of.
4742  */
4743 static int
4744 ctl_free_lun(struct ctl_lun *lun)
4745 {
4746 	struct ctl_softc *softc = lun->ctl_softc;
4747 	struct ctl_lun *nlun;
4748 	int i;
4749 
4750 	KASSERT(TAILQ_EMPTY(&lun->ooa_queue),
4751 	    ("Freeing a LUN %p with outstanding I/O!\n", lun));
4752 
4753 	mtx_lock(&softc->ctl_lock);
4754 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4755 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4756 	softc->ctl_luns[lun->lun] = NULL;
4757 	softc->num_luns--;
4758 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4759 		mtx_lock(&nlun->lun_lock);
4760 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4761 		mtx_unlock(&nlun->lun_lock);
4762 	}
4763 	mtx_unlock(&softc->ctl_lock);
4764 
4765 	/*
4766 	 * Tell the backend to free resources, if this LUN has a backend.
4767 	 */
4768 	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4769 	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4770 
4771 	lun->ie_reportcnt = UINT32_MAX;
4772 	callout_drain(&lun->ie_callout);
4773 	ctl_tpc_lun_shutdown(lun);
4774 	mtx_destroy(&lun->lun_lock);
4775 	free(lun->lun_devid, M_CTL);
4776 	for (i = 0; i < ctl_max_ports; i++)
4777 		free(lun->pending_ua[i], M_CTL);
4778 	free(lun->pending_ua, M_DEVBUF);
4779 	for (i = 0; i < ctl_max_ports; i++)
4780 		free(lun->pr_keys[i], M_CTL);
4781 	free(lun->pr_keys, M_DEVBUF);
4782 	free(lun->write_buffer, M_CTL);
4783 	free(lun->prevent, M_CTL);
4784 	if (lun->flags & CTL_LUN_MALLOCED)
4785 		free(lun, M_CTL);
4786 
4787 	return (0);
4788 }
4789 
4790 static void
4791 ctl_create_lun(struct ctl_be_lun *be_lun)
4792 {
4793 
4794 	/*
4795 	 * ctl_alloc_lun() should handle all potential failure cases.
4796 	 */
4797 	ctl_alloc_lun(control_softc, NULL, be_lun);
4798 }
4799 
4800 int
4801 ctl_add_lun(struct ctl_be_lun *be_lun)
4802 {
4803 	struct ctl_softc *softc = control_softc;
4804 
4805 	mtx_lock(&softc->ctl_lock);
4806 	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4807 	mtx_unlock(&softc->ctl_lock);
4808 	wakeup(&softc->pending_lun_queue);
4809 
4810 	return (0);
4811 }
4812 
4813 int
4814 ctl_enable_lun(struct ctl_be_lun *be_lun)
4815 {
4816 	struct ctl_softc *softc;
4817 	struct ctl_port *port, *nport;
4818 	struct ctl_lun *lun;
4819 	int retval;
4820 
4821 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4822 	softc = lun->ctl_softc;
4823 
4824 	mtx_lock(&softc->ctl_lock);
4825 	mtx_lock(&lun->lun_lock);
4826 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4827 		/*
4828 		 * eh?  Why did we get called if the LUN is already
4829 		 * enabled?
4830 		 */
4831 		mtx_unlock(&lun->lun_lock);
4832 		mtx_unlock(&softc->ctl_lock);
4833 		return (0);
4834 	}
4835 	lun->flags &= ~CTL_LUN_DISABLED;
4836 	mtx_unlock(&lun->lun_lock);
4837 
4838 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4839 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4840 		    port->lun_map != NULL || port->lun_enable == NULL)
4841 			continue;
4842 
4843 		/*
4844 		 * Drop the lock while we call the FETD's enable routine.
4845 		 * This can lead to a callback into CTL (at least in the
4846 		 * case of the internal initiator frontend.
4847 		 */
4848 		mtx_unlock(&softc->ctl_lock);
4849 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4850 		mtx_lock(&softc->ctl_lock);
4851 		if (retval != 0) {
4852 			printf("%s: FETD %s port %d returned error "
4853 			       "%d for lun_enable on lun %jd\n",
4854 			       __func__, port->port_name, port->targ_port,
4855 			       retval, (intmax_t)lun->lun);
4856 		}
4857 	}
4858 
4859 	mtx_unlock(&softc->ctl_lock);
4860 	ctl_isc_announce_lun(lun);
4861 
4862 	return (0);
4863 }
4864 
4865 int
4866 ctl_disable_lun(struct ctl_be_lun *be_lun)
4867 {
4868 	struct ctl_softc *softc;
4869 	struct ctl_port *port;
4870 	struct ctl_lun *lun;
4871 	int retval;
4872 
4873 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4874 	softc = lun->ctl_softc;
4875 
4876 	mtx_lock(&softc->ctl_lock);
4877 	mtx_lock(&lun->lun_lock);
4878 	if (lun->flags & CTL_LUN_DISABLED) {
4879 		mtx_unlock(&lun->lun_lock);
4880 		mtx_unlock(&softc->ctl_lock);
4881 		return (0);
4882 	}
4883 	lun->flags |= CTL_LUN_DISABLED;
4884 	mtx_unlock(&lun->lun_lock);
4885 
4886 	STAILQ_FOREACH(port, &softc->port_list, links) {
4887 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4888 		    port->lun_map != NULL || port->lun_disable == NULL)
4889 			continue;
4890 
4891 		/*
4892 		 * Drop the lock before we call the frontend's disable
4893 		 * routine, to avoid lock order reversals.
4894 		 *
4895 		 * XXX KDM what happens if the frontend list changes while
4896 		 * we're traversing it?  It's unlikely, but should be handled.
4897 		 */
4898 		mtx_unlock(&softc->ctl_lock);
4899 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4900 		mtx_lock(&softc->ctl_lock);
4901 		if (retval != 0) {
4902 			printf("%s: FETD %s port %d returned error "
4903 			       "%d for lun_disable on lun %jd\n",
4904 			       __func__, port->port_name, port->targ_port,
4905 			       retval, (intmax_t)lun->lun);
4906 		}
4907 	}
4908 
4909 	mtx_unlock(&softc->ctl_lock);
4910 	ctl_isc_announce_lun(lun);
4911 
4912 	return (0);
4913 }
4914 
4915 int
4916 ctl_start_lun(struct ctl_be_lun *be_lun)
4917 {
4918 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4919 
4920 	mtx_lock(&lun->lun_lock);
4921 	lun->flags &= ~CTL_LUN_STOPPED;
4922 	mtx_unlock(&lun->lun_lock);
4923 	return (0);
4924 }
4925 
4926 int
4927 ctl_stop_lun(struct ctl_be_lun *be_lun)
4928 {
4929 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4930 
4931 	mtx_lock(&lun->lun_lock);
4932 	lun->flags |= CTL_LUN_STOPPED;
4933 	mtx_unlock(&lun->lun_lock);
4934 	return (0);
4935 }
4936 
4937 int
4938 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4939 {
4940 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4941 
4942 	mtx_lock(&lun->lun_lock);
4943 	lun->flags |= CTL_LUN_NO_MEDIA;
4944 	mtx_unlock(&lun->lun_lock);
4945 	return (0);
4946 }
4947 
4948 int
4949 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4950 {
4951 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4952 	union ctl_ha_msg msg;
4953 
4954 	mtx_lock(&lun->lun_lock);
4955 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4956 	if (lun->flags & CTL_LUN_REMOVABLE)
4957 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4958 	mtx_unlock(&lun->lun_lock);
4959 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4960 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4961 		bzero(&msg.ua, sizeof(msg.ua));
4962 		msg.hdr.msg_type = CTL_MSG_UA;
4963 		msg.hdr.nexus.initid = -1;
4964 		msg.hdr.nexus.targ_port = -1;
4965 		msg.hdr.nexus.targ_lun = lun->lun;
4966 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4967 		msg.ua.ua_all = 1;
4968 		msg.ua.ua_set = 1;
4969 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4970 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4971 		    M_WAITOK);
4972 	}
4973 	return (0);
4974 }
4975 
4976 int
4977 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4978 {
4979 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4980 
4981 	mtx_lock(&lun->lun_lock);
4982 	lun->flags |= CTL_LUN_EJECTED;
4983 	mtx_unlock(&lun->lun_lock);
4984 	return (0);
4985 }
4986 
4987 int
4988 ctl_lun_primary(struct ctl_be_lun *be_lun)
4989 {
4990 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4991 
4992 	mtx_lock(&lun->lun_lock);
4993 	lun->flags |= CTL_LUN_PRIMARY_SC;
4994 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4995 	mtx_unlock(&lun->lun_lock);
4996 	ctl_isc_announce_lun(lun);
4997 	return (0);
4998 }
4999 
5000 int
5001 ctl_lun_secondary(struct ctl_be_lun *be_lun)
5002 {
5003 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5004 
5005 	mtx_lock(&lun->lun_lock);
5006 	lun->flags &= ~CTL_LUN_PRIMARY_SC;
5007 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
5008 	mtx_unlock(&lun->lun_lock);
5009 	ctl_isc_announce_lun(lun);
5010 	return (0);
5011 }
5012 
5013 int
5014 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
5015 {
5016 	struct ctl_lun *lun;
5017 
5018 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5019 
5020 	mtx_lock(&lun->lun_lock);
5021 
5022 	/*
5023 	 * The LUN needs to be disabled before it can be marked invalid.
5024 	 */
5025 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5026 		mtx_unlock(&lun->lun_lock);
5027 		return (-1);
5028 	}
5029 	/*
5030 	 * Mark the LUN invalid.
5031 	 */
5032 	lun->flags |= CTL_LUN_INVALID;
5033 
5034 	/*
5035 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5036 	 * If we have something in the OOA queue, we'll free it when the
5037 	 * last I/O completes.
5038 	 */
5039 	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5040 		mtx_unlock(&lun->lun_lock);
5041 		ctl_free_lun(lun);
5042 	} else
5043 		mtx_unlock(&lun->lun_lock);
5044 
5045 	return (0);
5046 }
5047 
5048 void
5049 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5050 {
5051 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5052 	union ctl_ha_msg msg;
5053 
5054 	mtx_lock(&lun->lun_lock);
5055 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5056 	mtx_unlock(&lun->lun_lock);
5057 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5058 		/* Send msg to other side. */
5059 		bzero(&msg.ua, sizeof(msg.ua));
5060 		msg.hdr.msg_type = CTL_MSG_UA;
5061 		msg.hdr.nexus.initid = -1;
5062 		msg.hdr.nexus.targ_port = -1;
5063 		msg.hdr.nexus.targ_lun = lun->lun;
5064 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5065 		msg.ua.ua_all = 1;
5066 		msg.ua.ua_set = 1;
5067 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5068 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5069 		    M_WAITOK);
5070 	}
5071 }
5072 
5073 /*
5074  * Backend "memory move is complete" callback for requests that never
5075  * make it down to say RAIDCore's configuration code.
5076  */
5077 int
5078 ctl_config_move_done(union ctl_io *io)
5079 {
5080 	int retval;
5081 
5082 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5083 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5084 	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5085 
5086 	if ((io->io_hdr.port_status != 0) &&
5087 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5088 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5089 		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
5090 		    /*retry_count*/ io->io_hdr.port_status);
5091 	} else if (io->scsiio.kern_data_resid != 0 &&
5092 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
5093 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5094 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5095 		ctl_set_invalid_field_ciu(&io->scsiio);
5096 	}
5097 
5098 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5099 		ctl_data_print(io);
5100 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5101 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5102 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5103 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5104 		/*
5105 		 * XXX KDM just assuming a single pointer here, and not a
5106 		 * S/G list.  If we start using S/G lists for config data,
5107 		 * we'll need to know how to clean them up here as well.
5108 		 */
5109 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5110 			free(io->scsiio.kern_data_ptr, M_CTL);
5111 		ctl_done(io);
5112 		retval = CTL_RETVAL_COMPLETE;
5113 	} else {
5114 		/*
5115 		 * XXX KDM now we need to continue data movement.  Some
5116 		 * options:
5117 		 * - call ctl_scsiio() again?  We don't do this for data
5118 		 *   writes, because for those at least we know ahead of
5119 		 *   time where the write will go and how long it is.  For
5120 		 *   config writes, though, that information is largely
5121 		 *   contained within the write itself, thus we need to
5122 		 *   parse out the data again.
5123 		 *
5124 		 * - Call some other function once the data is in?
5125 		 */
5126 
5127 		/*
5128 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5129 		 * bits to see whether we're allocated or not.
5130 		 */
5131 		retval = ctl_scsiio(&io->scsiio);
5132 	}
5133 	return (retval);
5134 }
5135 
5136 /*
5137  * This gets called by a backend driver when it is done with a
5138  * data_submit method.
5139  */
5140 void
5141 ctl_data_submit_done(union ctl_io *io)
5142 {
5143 	/*
5144 	 * If the IO_CONT flag is set, we need to call the supplied
5145 	 * function to continue processing the I/O, instead of completing
5146 	 * the I/O just yet.
5147 	 *
5148 	 * If there is an error, though, we don't want to keep processing.
5149 	 * Instead, just send status back to the initiator.
5150 	 */
5151 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5152 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5153 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5154 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5155 		io->scsiio.io_cont(io);
5156 		return;
5157 	}
5158 	ctl_done(io);
5159 }
5160 
5161 /*
5162  * This gets called by a backend driver when it is done with a
5163  * configuration write.
5164  */
5165 void
5166 ctl_config_write_done(union ctl_io *io)
5167 {
5168 	uint8_t *buf;
5169 
5170 	/*
5171 	 * If the IO_CONT flag is set, we need to call the supplied
5172 	 * function to continue processing the I/O, instead of completing
5173 	 * the I/O just yet.
5174 	 *
5175 	 * If there is an error, though, we don't want to keep processing.
5176 	 * Instead, just send status back to the initiator.
5177 	 */
5178 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5179 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5180 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5181 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5182 		io->scsiio.io_cont(io);
5183 		return;
5184 	}
5185 	/*
5186 	 * Since a configuration write can be done for commands that actually
5187 	 * have data allocated, like write buffer, and commands that have
5188 	 * no data, like start/stop unit, we need to check here.
5189 	 */
5190 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5191 		buf = io->scsiio.kern_data_ptr;
5192 	else
5193 		buf = NULL;
5194 	ctl_done(io);
5195 	if (buf)
5196 		free(buf, M_CTL);
5197 }
5198 
5199 void
5200 ctl_config_read_done(union ctl_io *io)
5201 {
5202 	uint8_t *buf;
5203 
5204 	/*
5205 	 * If there is some error -- we are done, skip data transfer.
5206 	 */
5207 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5208 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5209 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5210 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5211 			buf = io->scsiio.kern_data_ptr;
5212 		else
5213 			buf = NULL;
5214 		ctl_done(io);
5215 		if (buf)
5216 			free(buf, M_CTL);
5217 		return;
5218 	}
5219 
5220 	/*
5221 	 * If the IO_CONT flag is set, we need to call the supplied
5222 	 * function to continue processing the I/O, instead of completing
5223 	 * the I/O just yet.
5224 	 */
5225 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5226 		io->scsiio.io_cont(io);
5227 		return;
5228 	}
5229 
5230 	ctl_datamove(io);
5231 }
5232 
5233 /*
5234  * SCSI release command.
5235  */
5236 int
5237 ctl_scsi_release(struct ctl_scsiio *ctsio)
5238 {
5239 	struct ctl_lun *lun = CTL_LUN(ctsio);
5240 	uint32_t residx;
5241 
5242 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5243 
5244 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5245 
5246 	/*
5247 	 * XXX KDM right now, we only support LUN reservation.  We don't
5248 	 * support 3rd party reservations, or extent reservations, which
5249 	 * might actually need the parameter list.  If we've gotten this
5250 	 * far, we've got a LUN reservation.  Anything else got kicked out
5251 	 * above.  So, according to SPC, ignore the length.
5252 	 */
5253 
5254 	mtx_lock(&lun->lun_lock);
5255 
5256 	/*
5257 	 * According to SPC, it is not an error for an intiator to attempt
5258 	 * to release a reservation on a LUN that isn't reserved, or that
5259 	 * is reserved by another initiator.  The reservation can only be
5260 	 * released, though, by the initiator who made it or by one of
5261 	 * several reset type events.
5262 	 */
5263 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5264 			lun->flags &= ~CTL_LUN_RESERVED;
5265 
5266 	mtx_unlock(&lun->lun_lock);
5267 
5268 	ctl_set_success(ctsio);
5269 	ctl_done((union ctl_io *)ctsio);
5270 	return (CTL_RETVAL_COMPLETE);
5271 }
5272 
5273 int
5274 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5275 {
5276 	struct ctl_lun *lun = CTL_LUN(ctsio);
5277 	uint32_t residx;
5278 
5279 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5280 
5281 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5282 
5283 	/*
5284 	 * XXX KDM right now, we only support LUN reservation.  We don't
5285 	 * support 3rd party reservations, or extent reservations, which
5286 	 * might actually need the parameter list.  If we've gotten this
5287 	 * far, we've got a LUN reservation.  Anything else got kicked out
5288 	 * above.  So, according to SPC, ignore the length.
5289 	 */
5290 
5291 	mtx_lock(&lun->lun_lock);
5292 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5293 		ctl_set_reservation_conflict(ctsio);
5294 		goto bailout;
5295 	}
5296 
5297 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5298 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5299 		ctl_set_success(ctsio);
5300 		goto bailout;
5301 	}
5302 
5303 	lun->flags |= CTL_LUN_RESERVED;
5304 	lun->res_idx = residx;
5305 	ctl_set_success(ctsio);
5306 
5307 bailout:
5308 	mtx_unlock(&lun->lun_lock);
5309 	ctl_done((union ctl_io *)ctsio);
5310 	return (CTL_RETVAL_COMPLETE);
5311 }
5312 
5313 int
5314 ctl_start_stop(struct ctl_scsiio *ctsio)
5315 {
5316 	struct ctl_lun *lun = CTL_LUN(ctsio);
5317 	struct scsi_start_stop_unit *cdb;
5318 	int retval;
5319 
5320 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5321 
5322 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5323 
5324 	if ((cdb->how & SSS_PC_MASK) == 0) {
5325 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5326 		    (cdb->how & SSS_START) == 0) {
5327 			uint32_t residx;
5328 
5329 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5330 			if (ctl_get_prkey(lun, residx) == 0 ||
5331 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5332 
5333 				ctl_set_reservation_conflict(ctsio);
5334 				ctl_done((union ctl_io *)ctsio);
5335 				return (CTL_RETVAL_COMPLETE);
5336 			}
5337 		}
5338 
5339 		if ((cdb->how & SSS_LOEJ) &&
5340 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5341 			ctl_set_invalid_field(ctsio,
5342 					      /*sks_valid*/ 1,
5343 					      /*command*/ 1,
5344 					      /*field*/ 4,
5345 					      /*bit_valid*/ 1,
5346 					      /*bit*/ 1);
5347 			ctl_done((union ctl_io *)ctsio);
5348 			return (CTL_RETVAL_COMPLETE);
5349 		}
5350 
5351 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5352 		    lun->prevent_count > 0) {
5353 			/* "Medium removal prevented" */
5354 			ctl_set_sense(ctsio, /*current_error*/ 1,
5355 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5356 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5357 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5358 			ctl_done((union ctl_io *)ctsio);
5359 			return (CTL_RETVAL_COMPLETE);
5360 		}
5361 	}
5362 
5363 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5364 	return (retval);
5365 }
5366 
5367 int
5368 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5369 {
5370 	struct ctl_lun *lun = CTL_LUN(ctsio);
5371 	struct scsi_prevent *cdb;
5372 	int retval;
5373 	uint32_t initidx;
5374 
5375 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5376 
5377 	cdb = (struct scsi_prevent *)ctsio->cdb;
5378 
5379 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5380 		ctl_set_invalid_opcode(ctsio);
5381 		ctl_done((union ctl_io *)ctsio);
5382 		return (CTL_RETVAL_COMPLETE);
5383 	}
5384 
5385 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5386 	mtx_lock(&lun->lun_lock);
5387 	if ((cdb->how & PR_PREVENT) &&
5388 	    ctl_is_set(lun->prevent, initidx) == 0) {
5389 		ctl_set_mask(lun->prevent, initidx);
5390 		lun->prevent_count++;
5391 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5392 	    ctl_is_set(lun->prevent, initidx)) {
5393 		ctl_clear_mask(lun->prevent, initidx);
5394 		lun->prevent_count--;
5395 	}
5396 	mtx_unlock(&lun->lun_lock);
5397 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5398 	return (retval);
5399 }
5400 
5401 /*
5402  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5403  * we don't really do anything with the LBA and length fields if the user
5404  * passes them in.  Instead we'll just flush out the cache for the entire
5405  * LUN.
5406  */
5407 int
5408 ctl_sync_cache(struct ctl_scsiio *ctsio)
5409 {
5410 	struct ctl_lun *lun = CTL_LUN(ctsio);
5411 	struct ctl_lba_len_flags *lbalen;
5412 	uint64_t starting_lba;
5413 	uint32_t block_count;
5414 	int retval;
5415 	uint8_t byte2;
5416 
5417 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5418 
5419 	retval = 0;
5420 
5421 	switch (ctsio->cdb[0]) {
5422 	case SYNCHRONIZE_CACHE: {
5423 		struct scsi_sync_cache *cdb;
5424 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5425 
5426 		starting_lba = scsi_4btoul(cdb->begin_lba);
5427 		block_count = scsi_2btoul(cdb->lb_count);
5428 		byte2 = cdb->byte2;
5429 		break;
5430 	}
5431 	case SYNCHRONIZE_CACHE_16: {
5432 		struct scsi_sync_cache_16 *cdb;
5433 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5434 
5435 		starting_lba = scsi_8btou64(cdb->begin_lba);
5436 		block_count = scsi_4btoul(cdb->lb_count);
5437 		byte2 = cdb->byte2;
5438 		break;
5439 	}
5440 	default:
5441 		ctl_set_invalid_opcode(ctsio);
5442 		ctl_done((union ctl_io *)ctsio);
5443 		goto bailout;
5444 		break; /* NOTREACHED */
5445 	}
5446 
5447 	/*
5448 	 * We check the LBA and length, but don't do anything with them.
5449 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5450 	 * get flushed.  This check will just help satisfy anyone who wants
5451 	 * to see an error for an out of range LBA.
5452 	 */
5453 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5454 		ctl_set_lba_out_of_range(ctsio,
5455 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5456 		ctl_done((union ctl_io *)ctsio);
5457 		goto bailout;
5458 	}
5459 
5460 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5461 	lbalen->lba = starting_lba;
5462 	lbalen->len = block_count;
5463 	lbalen->flags = byte2;
5464 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5465 
5466 bailout:
5467 	return (retval);
5468 }
5469 
5470 int
5471 ctl_format(struct ctl_scsiio *ctsio)
5472 {
5473 	struct scsi_format *cdb;
5474 	int length, defect_list_len;
5475 
5476 	CTL_DEBUG_PRINT(("ctl_format\n"));
5477 
5478 	cdb = (struct scsi_format *)ctsio->cdb;
5479 
5480 	length = 0;
5481 	if (cdb->byte2 & SF_FMTDATA) {
5482 		if (cdb->byte2 & SF_LONGLIST)
5483 			length = sizeof(struct scsi_format_header_long);
5484 		else
5485 			length = sizeof(struct scsi_format_header_short);
5486 	}
5487 
5488 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5489 	 && (length > 0)) {
5490 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5491 		ctsio->kern_data_len = length;
5492 		ctsio->kern_total_len = length;
5493 		ctsio->kern_rel_offset = 0;
5494 		ctsio->kern_sg_entries = 0;
5495 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5496 		ctsio->be_move_done = ctl_config_move_done;
5497 		ctl_datamove((union ctl_io *)ctsio);
5498 
5499 		return (CTL_RETVAL_COMPLETE);
5500 	}
5501 
5502 	defect_list_len = 0;
5503 
5504 	if (cdb->byte2 & SF_FMTDATA) {
5505 		if (cdb->byte2 & SF_LONGLIST) {
5506 			struct scsi_format_header_long *header;
5507 
5508 			header = (struct scsi_format_header_long *)
5509 				ctsio->kern_data_ptr;
5510 
5511 			defect_list_len = scsi_4btoul(header->defect_list_len);
5512 			if (defect_list_len != 0) {
5513 				ctl_set_invalid_field(ctsio,
5514 						      /*sks_valid*/ 1,
5515 						      /*command*/ 0,
5516 						      /*field*/ 2,
5517 						      /*bit_valid*/ 0,
5518 						      /*bit*/ 0);
5519 				goto bailout;
5520 			}
5521 		} else {
5522 			struct scsi_format_header_short *header;
5523 
5524 			header = (struct scsi_format_header_short *)
5525 				ctsio->kern_data_ptr;
5526 
5527 			defect_list_len = scsi_2btoul(header->defect_list_len);
5528 			if (defect_list_len != 0) {
5529 				ctl_set_invalid_field(ctsio,
5530 						      /*sks_valid*/ 1,
5531 						      /*command*/ 0,
5532 						      /*field*/ 2,
5533 						      /*bit_valid*/ 0,
5534 						      /*bit*/ 0);
5535 				goto bailout;
5536 			}
5537 		}
5538 	}
5539 
5540 	ctl_set_success(ctsio);
5541 bailout:
5542 
5543 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5544 		free(ctsio->kern_data_ptr, M_CTL);
5545 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5546 	}
5547 
5548 	ctl_done((union ctl_io *)ctsio);
5549 	return (CTL_RETVAL_COMPLETE);
5550 }
5551 
5552 int
5553 ctl_read_buffer(struct ctl_scsiio *ctsio)
5554 {
5555 	struct ctl_lun *lun = CTL_LUN(ctsio);
5556 	uint64_t buffer_offset;
5557 	uint32_t len;
5558 	uint8_t byte2;
5559 	static uint8_t descr[4];
5560 	static uint8_t echo_descr[4] = { 0 };
5561 
5562 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5563 
5564 	switch (ctsio->cdb[0]) {
5565 	case READ_BUFFER: {
5566 		struct scsi_read_buffer *cdb;
5567 
5568 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5569 		buffer_offset = scsi_3btoul(cdb->offset);
5570 		len = scsi_3btoul(cdb->length);
5571 		byte2 = cdb->byte2;
5572 		break;
5573 	}
5574 	case READ_BUFFER_16: {
5575 		struct scsi_read_buffer_16 *cdb;
5576 
5577 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5578 		buffer_offset = scsi_8btou64(cdb->offset);
5579 		len = scsi_4btoul(cdb->length);
5580 		byte2 = cdb->byte2;
5581 		break;
5582 	}
5583 	default: /* This shouldn't happen. */
5584 		ctl_set_invalid_opcode(ctsio);
5585 		ctl_done((union ctl_io *)ctsio);
5586 		return (CTL_RETVAL_COMPLETE);
5587 	}
5588 
5589 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5590 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5591 		ctl_set_invalid_field(ctsio,
5592 				      /*sks_valid*/ 1,
5593 				      /*command*/ 1,
5594 				      /*field*/ 6,
5595 				      /*bit_valid*/ 0,
5596 				      /*bit*/ 0);
5597 		ctl_done((union ctl_io *)ctsio);
5598 		return (CTL_RETVAL_COMPLETE);
5599 	}
5600 
5601 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5602 		descr[0] = 0;
5603 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5604 		ctsio->kern_data_ptr = descr;
5605 		len = min(len, sizeof(descr));
5606 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5607 		ctsio->kern_data_ptr = echo_descr;
5608 		len = min(len, sizeof(echo_descr));
5609 	} else {
5610 		if (lun->write_buffer == NULL) {
5611 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5612 			    M_CTL, M_WAITOK);
5613 		}
5614 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5615 	}
5616 	ctsio->kern_data_len = len;
5617 	ctsio->kern_total_len = len;
5618 	ctsio->kern_rel_offset = 0;
5619 	ctsio->kern_sg_entries = 0;
5620 	ctl_set_success(ctsio);
5621 	ctsio->be_move_done = ctl_config_move_done;
5622 	ctl_datamove((union ctl_io *)ctsio);
5623 	return (CTL_RETVAL_COMPLETE);
5624 }
5625 
5626 int
5627 ctl_write_buffer(struct ctl_scsiio *ctsio)
5628 {
5629 	struct ctl_lun *lun = CTL_LUN(ctsio);
5630 	struct scsi_write_buffer *cdb;
5631 	int buffer_offset, len;
5632 
5633 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5634 
5635 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5636 
5637 	len = scsi_3btoul(cdb->length);
5638 	buffer_offset = scsi_3btoul(cdb->offset);
5639 
5640 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5641 		ctl_set_invalid_field(ctsio,
5642 				      /*sks_valid*/ 1,
5643 				      /*command*/ 1,
5644 				      /*field*/ 6,
5645 				      /*bit_valid*/ 0,
5646 				      /*bit*/ 0);
5647 		ctl_done((union ctl_io *)ctsio);
5648 		return (CTL_RETVAL_COMPLETE);
5649 	}
5650 
5651 	/*
5652 	 * If we've got a kernel request that hasn't been malloced yet,
5653 	 * malloc it and tell the caller the data buffer is here.
5654 	 */
5655 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5656 		if (lun->write_buffer == NULL) {
5657 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5658 			    M_CTL, M_WAITOK);
5659 		}
5660 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5661 		ctsio->kern_data_len = len;
5662 		ctsio->kern_total_len = len;
5663 		ctsio->kern_rel_offset = 0;
5664 		ctsio->kern_sg_entries = 0;
5665 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5666 		ctsio->be_move_done = ctl_config_move_done;
5667 		ctl_datamove((union ctl_io *)ctsio);
5668 
5669 		return (CTL_RETVAL_COMPLETE);
5670 	}
5671 
5672 	ctl_set_success(ctsio);
5673 	ctl_done((union ctl_io *)ctsio);
5674 	return (CTL_RETVAL_COMPLETE);
5675 }
5676 
5677 int
5678 ctl_write_same(struct ctl_scsiio *ctsio)
5679 {
5680 	struct ctl_lun *lun = CTL_LUN(ctsio);
5681 	struct ctl_lba_len_flags *lbalen;
5682 	uint64_t lba;
5683 	uint32_t num_blocks;
5684 	int len, retval;
5685 	uint8_t byte2;
5686 
5687 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5688 
5689 	switch (ctsio->cdb[0]) {
5690 	case WRITE_SAME_10: {
5691 		struct scsi_write_same_10 *cdb;
5692 
5693 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5694 
5695 		lba = scsi_4btoul(cdb->addr);
5696 		num_blocks = scsi_2btoul(cdb->length);
5697 		byte2 = cdb->byte2;
5698 		break;
5699 	}
5700 	case WRITE_SAME_16: {
5701 		struct scsi_write_same_16 *cdb;
5702 
5703 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5704 
5705 		lba = scsi_8btou64(cdb->addr);
5706 		num_blocks = scsi_4btoul(cdb->length);
5707 		byte2 = cdb->byte2;
5708 		break;
5709 	}
5710 	default:
5711 		/*
5712 		 * We got a command we don't support.  This shouldn't
5713 		 * happen, commands should be filtered out above us.
5714 		 */
5715 		ctl_set_invalid_opcode(ctsio);
5716 		ctl_done((union ctl_io *)ctsio);
5717 
5718 		return (CTL_RETVAL_COMPLETE);
5719 		break; /* NOTREACHED */
5720 	}
5721 
5722 	/* ANCHOR flag can be used only together with UNMAP */
5723 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5724 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5725 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5726 		ctl_done((union ctl_io *)ctsio);
5727 		return (CTL_RETVAL_COMPLETE);
5728 	}
5729 
5730 	/*
5731 	 * The first check is to make sure we're in bounds, the second
5732 	 * check is to catch wrap-around problems.  If the lba + num blocks
5733 	 * is less than the lba, then we've wrapped around and the block
5734 	 * range is invalid anyway.
5735 	 */
5736 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5737 	 || ((lba + num_blocks) < lba)) {
5738 		ctl_set_lba_out_of_range(ctsio,
5739 		    MAX(lba, lun->be_lun->maxlba + 1));
5740 		ctl_done((union ctl_io *)ctsio);
5741 		return (CTL_RETVAL_COMPLETE);
5742 	}
5743 
5744 	/* Zero number of blocks means "to the last logical block" */
5745 	if (num_blocks == 0) {
5746 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5747 			ctl_set_invalid_field(ctsio,
5748 					      /*sks_valid*/ 0,
5749 					      /*command*/ 1,
5750 					      /*field*/ 0,
5751 					      /*bit_valid*/ 0,
5752 					      /*bit*/ 0);
5753 			ctl_done((union ctl_io *)ctsio);
5754 			return (CTL_RETVAL_COMPLETE);
5755 		}
5756 		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5757 	}
5758 
5759 	len = lun->be_lun->blocksize;
5760 
5761 	/*
5762 	 * If we've got a kernel request that hasn't been malloced yet,
5763 	 * malloc it and tell the caller the data buffer is here.
5764 	 */
5765 	if ((byte2 & SWS_NDOB) == 0 &&
5766 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5767 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5768 		ctsio->kern_data_len = len;
5769 		ctsio->kern_total_len = len;
5770 		ctsio->kern_rel_offset = 0;
5771 		ctsio->kern_sg_entries = 0;
5772 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5773 		ctsio->be_move_done = ctl_config_move_done;
5774 		ctl_datamove((union ctl_io *)ctsio);
5775 
5776 		return (CTL_RETVAL_COMPLETE);
5777 	}
5778 
5779 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5780 	lbalen->lba = lba;
5781 	lbalen->len = num_blocks;
5782 	lbalen->flags = byte2;
5783 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5784 
5785 	return (retval);
5786 }
5787 
5788 int
5789 ctl_unmap(struct ctl_scsiio *ctsio)
5790 {
5791 	struct ctl_lun *lun = CTL_LUN(ctsio);
5792 	struct scsi_unmap *cdb;
5793 	struct ctl_ptr_len_flags *ptrlen;
5794 	struct scsi_unmap_header *hdr;
5795 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5796 	uint64_t lba;
5797 	uint32_t num_blocks;
5798 	int len, retval;
5799 	uint8_t byte2;
5800 
5801 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5802 
5803 	cdb = (struct scsi_unmap *)ctsio->cdb;
5804 	len = scsi_2btoul(cdb->length);
5805 	byte2 = cdb->byte2;
5806 
5807 	/*
5808 	 * If we've got a kernel request that hasn't been malloced yet,
5809 	 * malloc it and tell the caller the data buffer is here.
5810 	 */
5811 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5812 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5813 		ctsio->kern_data_len = len;
5814 		ctsio->kern_total_len = len;
5815 		ctsio->kern_rel_offset = 0;
5816 		ctsio->kern_sg_entries = 0;
5817 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5818 		ctsio->be_move_done = ctl_config_move_done;
5819 		ctl_datamove((union ctl_io *)ctsio);
5820 
5821 		return (CTL_RETVAL_COMPLETE);
5822 	}
5823 
5824 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5825 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5826 	if (len < sizeof (*hdr) ||
5827 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5828 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5829 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5830 		ctl_set_invalid_field(ctsio,
5831 				      /*sks_valid*/ 0,
5832 				      /*command*/ 0,
5833 				      /*field*/ 0,
5834 				      /*bit_valid*/ 0,
5835 				      /*bit*/ 0);
5836 		goto done;
5837 	}
5838 	len = scsi_2btoul(hdr->desc_length);
5839 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5840 	end = buf + len / sizeof(*buf);
5841 
5842 	endnz = buf;
5843 	for (range = buf; range < end; range++) {
5844 		lba = scsi_8btou64(range->lba);
5845 		num_blocks = scsi_4btoul(range->length);
5846 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5847 		 || ((lba + num_blocks) < lba)) {
5848 			ctl_set_lba_out_of_range(ctsio,
5849 			    MAX(lba, lun->be_lun->maxlba + 1));
5850 			ctl_done((union ctl_io *)ctsio);
5851 			return (CTL_RETVAL_COMPLETE);
5852 		}
5853 		if (num_blocks != 0)
5854 			endnz = range + 1;
5855 	}
5856 
5857 	/*
5858 	 * Block backend can not handle zero last range.
5859 	 * Filter it out and return if there is nothing left.
5860 	 */
5861 	len = (uint8_t *)endnz - (uint8_t *)buf;
5862 	if (len == 0) {
5863 		ctl_set_success(ctsio);
5864 		goto done;
5865 	}
5866 
5867 	mtx_lock(&lun->lun_lock);
5868 	ptrlen = (struct ctl_ptr_len_flags *)
5869 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5870 	ptrlen->ptr = (void *)buf;
5871 	ptrlen->len = len;
5872 	ptrlen->flags = byte2;
5873 	ctl_check_blocked(lun);
5874 	mtx_unlock(&lun->lun_lock);
5875 
5876 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5877 	return (retval);
5878 
5879 done:
5880 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5881 		free(ctsio->kern_data_ptr, M_CTL);
5882 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5883 	}
5884 	ctl_done((union ctl_io *)ctsio);
5885 	return (CTL_RETVAL_COMPLETE);
5886 }
5887 
5888 int
5889 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5890 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5891 {
5892 	struct ctl_lun *lun = CTL_LUN(ctsio);
5893 	uint8_t *current_cp;
5894 	int set_ua;
5895 	uint32_t initidx;
5896 
5897 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5898 	set_ua = 0;
5899 
5900 	current_cp = (page_index->page_data + (page_index->page_len *
5901 	    CTL_PAGE_CURRENT));
5902 
5903 	mtx_lock(&lun->lun_lock);
5904 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5905 		memcpy(current_cp, page_ptr, page_index->page_len);
5906 		set_ua = 1;
5907 	}
5908 	if (set_ua != 0)
5909 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5910 	mtx_unlock(&lun->lun_lock);
5911 	if (set_ua) {
5912 		ctl_isc_announce_mode(lun,
5913 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5914 		    page_index->page_code, page_index->subpage);
5915 	}
5916 	return (CTL_RETVAL_COMPLETE);
5917 }
5918 
5919 static void
5920 ctl_ie_timer(void *arg)
5921 {
5922 	struct ctl_lun *lun = arg;
5923 	uint64_t t;
5924 
5925 	if (lun->ie_asc == 0)
5926 		return;
5927 
5928 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5929 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5930 	else
5931 		lun->ie_reported = 0;
5932 
5933 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5934 		lun->ie_reportcnt++;
5935 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5936 		if (t == 0 || t == UINT32_MAX)
5937 			t = 3000;  /* 5 min */
5938 		callout_schedule(&lun->ie_callout, t * hz / 10);
5939 	}
5940 }
5941 
5942 int
5943 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5944 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5945 {
5946 	struct ctl_lun *lun = CTL_LUN(ctsio);
5947 	struct scsi_info_exceptions_page *pg;
5948 	uint64_t t;
5949 
5950 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5951 
5952 	pg = (struct scsi_info_exceptions_page *)page_ptr;
5953 	mtx_lock(&lun->lun_lock);
5954 	if (pg->info_flags & SIEP_FLAGS_TEST) {
5955 		lun->ie_asc = 0x5d;
5956 		lun->ie_ascq = 0xff;
5957 		if (pg->mrie == SIEP_MRIE_UA) {
5958 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5959 			lun->ie_reported = 1;
5960 		} else {
5961 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5962 			lun->ie_reported = -1;
5963 		}
5964 		lun->ie_reportcnt = 1;
5965 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5966 			lun->ie_reportcnt++;
5967 			t = scsi_4btoul(pg->interval_timer);
5968 			if (t == 0 || t == UINT32_MAX)
5969 				t = 3000;  /* 5 min */
5970 			callout_reset(&lun->ie_callout, t * hz / 10,
5971 			    ctl_ie_timer, lun);
5972 		}
5973 	} else {
5974 		lun->ie_asc = 0;
5975 		lun->ie_ascq = 0;
5976 		lun->ie_reported = 1;
5977 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5978 		lun->ie_reportcnt = UINT32_MAX;
5979 		callout_stop(&lun->ie_callout);
5980 	}
5981 	mtx_unlock(&lun->lun_lock);
5982 	return (CTL_RETVAL_COMPLETE);
5983 }
5984 
5985 static int
5986 ctl_do_mode_select(union ctl_io *io)
5987 {
5988 	struct ctl_lun *lun = CTL_LUN(io);
5989 	struct scsi_mode_page_header *page_header;
5990 	struct ctl_page_index *page_index;
5991 	struct ctl_scsiio *ctsio;
5992 	int page_len, page_len_offset, page_len_size;
5993 	union ctl_modepage_info *modepage_info;
5994 	uint16_t *len_left, *len_used;
5995 	int retval, i;
5996 
5997 	ctsio = &io->scsiio;
5998 	page_index = NULL;
5999 	page_len = 0;
6000 
6001 	modepage_info = (union ctl_modepage_info *)
6002 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6003 	len_left = &modepage_info->header.len_left;
6004 	len_used = &modepage_info->header.len_used;
6005 
6006 do_next_page:
6007 
6008 	page_header = (struct scsi_mode_page_header *)
6009 		(ctsio->kern_data_ptr + *len_used);
6010 
6011 	if (*len_left == 0) {
6012 		free(ctsio->kern_data_ptr, M_CTL);
6013 		ctl_set_success(ctsio);
6014 		ctl_done((union ctl_io *)ctsio);
6015 		return (CTL_RETVAL_COMPLETE);
6016 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6017 
6018 		free(ctsio->kern_data_ptr, M_CTL);
6019 		ctl_set_param_len_error(ctsio);
6020 		ctl_done((union ctl_io *)ctsio);
6021 		return (CTL_RETVAL_COMPLETE);
6022 
6023 	} else if ((page_header->page_code & SMPH_SPF)
6024 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6025 
6026 		free(ctsio->kern_data_ptr, M_CTL);
6027 		ctl_set_param_len_error(ctsio);
6028 		ctl_done((union ctl_io *)ctsio);
6029 		return (CTL_RETVAL_COMPLETE);
6030 	}
6031 
6032 
6033 	/*
6034 	 * XXX KDM should we do something with the block descriptor?
6035 	 */
6036 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6037 		page_index = &lun->mode_pages.index[i];
6038 		if (lun->be_lun->lun_type == T_DIRECT &&
6039 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6040 			continue;
6041 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6042 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6043 			continue;
6044 		if (lun->be_lun->lun_type == T_CDROM &&
6045 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6046 			continue;
6047 
6048 		if ((page_index->page_code & SMPH_PC_MASK) !=
6049 		    (page_header->page_code & SMPH_PC_MASK))
6050 			continue;
6051 
6052 		/*
6053 		 * If neither page has a subpage code, then we've got a
6054 		 * match.
6055 		 */
6056 		if (((page_index->page_code & SMPH_SPF) == 0)
6057 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6058 			page_len = page_header->page_length;
6059 			break;
6060 		}
6061 
6062 		/*
6063 		 * If both pages have subpages, then the subpage numbers
6064 		 * have to match.
6065 		 */
6066 		if ((page_index->page_code & SMPH_SPF)
6067 		  && (page_header->page_code & SMPH_SPF)) {
6068 			struct scsi_mode_page_header_sp *sph;
6069 
6070 			sph = (struct scsi_mode_page_header_sp *)page_header;
6071 			if (page_index->subpage == sph->subpage) {
6072 				page_len = scsi_2btoul(sph->page_length);
6073 				break;
6074 			}
6075 		}
6076 	}
6077 
6078 	/*
6079 	 * If we couldn't find the page, or if we don't have a mode select
6080 	 * handler for it, send back an error to the user.
6081 	 */
6082 	if ((i >= CTL_NUM_MODE_PAGES)
6083 	 || (page_index->select_handler == NULL)) {
6084 		ctl_set_invalid_field(ctsio,
6085 				      /*sks_valid*/ 1,
6086 				      /*command*/ 0,
6087 				      /*field*/ *len_used,
6088 				      /*bit_valid*/ 0,
6089 				      /*bit*/ 0);
6090 		free(ctsio->kern_data_ptr, M_CTL);
6091 		ctl_done((union ctl_io *)ctsio);
6092 		return (CTL_RETVAL_COMPLETE);
6093 	}
6094 
6095 	if (page_index->page_code & SMPH_SPF) {
6096 		page_len_offset = 2;
6097 		page_len_size = 2;
6098 	} else {
6099 		page_len_size = 1;
6100 		page_len_offset = 1;
6101 	}
6102 
6103 	/*
6104 	 * If the length the initiator gives us isn't the one we specify in
6105 	 * the mode page header, or if they didn't specify enough data in
6106 	 * the CDB to avoid truncating this page, kick out the request.
6107 	 */
6108 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6109 		ctl_set_invalid_field(ctsio,
6110 				      /*sks_valid*/ 1,
6111 				      /*command*/ 0,
6112 				      /*field*/ *len_used + page_len_offset,
6113 				      /*bit_valid*/ 0,
6114 				      /*bit*/ 0);
6115 		free(ctsio->kern_data_ptr, M_CTL);
6116 		ctl_done((union ctl_io *)ctsio);
6117 		return (CTL_RETVAL_COMPLETE);
6118 	}
6119 	if (*len_left < page_index->page_len) {
6120 		free(ctsio->kern_data_ptr, M_CTL);
6121 		ctl_set_param_len_error(ctsio);
6122 		ctl_done((union ctl_io *)ctsio);
6123 		return (CTL_RETVAL_COMPLETE);
6124 	}
6125 
6126 	/*
6127 	 * Run through the mode page, checking to make sure that the bits
6128 	 * the user changed are actually legal for him to change.
6129 	 */
6130 	for (i = 0; i < page_index->page_len; i++) {
6131 		uint8_t *user_byte, *change_mask, *current_byte;
6132 		int bad_bit;
6133 		int j;
6134 
6135 		user_byte = (uint8_t *)page_header + i;
6136 		change_mask = page_index->page_data +
6137 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6138 		current_byte = page_index->page_data +
6139 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6140 
6141 		/*
6142 		 * Check to see whether the user set any bits in this byte
6143 		 * that he is not allowed to set.
6144 		 */
6145 		if ((*user_byte & ~(*change_mask)) ==
6146 		    (*current_byte & ~(*change_mask)))
6147 			continue;
6148 
6149 		/*
6150 		 * Go through bit by bit to determine which one is illegal.
6151 		 */
6152 		bad_bit = 0;
6153 		for (j = 7; j >= 0; j--) {
6154 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6155 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6156 				bad_bit = i;
6157 				break;
6158 			}
6159 		}
6160 		ctl_set_invalid_field(ctsio,
6161 				      /*sks_valid*/ 1,
6162 				      /*command*/ 0,
6163 				      /*field*/ *len_used + i,
6164 				      /*bit_valid*/ 1,
6165 				      /*bit*/ bad_bit);
6166 		free(ctsio->kern_data_ptr, M_CTL);
6167 		ctl_done((union ctl_io *)ctsio);
6168 		return (CTL_RETVAL_COMPLETE);
6169 	}
6170 
6171 	/*
6172 	 * Decrement these before we call the page handler, since we may
6173 	 * end up getting called back one way or another before the handler
6174 	 * returns to this context.
6175 	 */
6176 	*len_left -= page_index->page_len;
6177 	*len_used += page_index->page_len;
6178 
6179 	retval = page_index->select_handler(ctsio, page_index,
6180 					    (uint8_t *)page_header);
6181 
6182 	/*
6183 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6184 	 * wait until this queued command completes to finish processing
6185 	 * the mode page.  If it returns anything other than
6186 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6187 	 * already set the sense information, freed the data pointer, and
6188 	 * completed the io for us.
6189 	 */
6190 	if (retval != CTL_RETVAL_COMPLETE)
6191 		goto bailout_no_done;
6192 
6193 	/*
6194 	 * If the initiator sent us more than one page, parse the next one.
6195 	 */
6196 	if (*len_left > 0)
6197 		goto do_next_page;
6198 
6199 	ctl_set_success(ctsio);
6200 	free(ctsio->kern_data_ptr, M_CTL);
6201 	ctl_done((union ctl_io *)ctsio);
6202 
6203 bailout_no_done:
6204 
6205 	return (CTL_RETVAL_COMPLETE);
6206 
6207 }
6208 
6209 int
6210 ctl_mode_select(struct ctl_scsiio *ctsio)
6211 {
6212 	struct ctl_lun *lun = CTL_LUN(ctsio);
6213 	union ctl_modepage_info *modepage_info;
6214 	int bd_len, i, header_size, param_len, rtd;
6215 	uint32_t initidx;
6216 
6217 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6218 	switch (ctsio->cdb[0]) {
6219 	case MODE_SELECT_6: {
6220 		struct scsi_mode_select_6 *cdb;
6221 
6222 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6223 
6224 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6225 		param_len = cdb->length;
6226 		header_size = sizeof(struct scsi_mode_header_6);
6227 		break;
6228 	}
6229 	case MODE_SELECT_10: {
6230 		struct scsi_mode_select_10 *cdb;
6231 
6232 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6233 
6234 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6235 		param_len = scsi_2btoul(cdb->length);
6236 		header_size = sizeof(struct scsi_mode_header_10);
6237 		break;
6238 	}
6239 	default:
6240 		ctl_set_invalid_opcode(ctsio);
6241 		ctl_done((union ctl_io *)ctsio);
6242 		return (CTL_RETVAL_COMPLETE);
6243 	}
6244 
6245 	if (rtd) {
6246 		if (param_len != 0) {
6247 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6248 			    /*command*/ 1, /*field*/ 0,
6249 			    /*bit_valid*/ 0, /*bit*/ 0);
6250 			ctl_done((union ctl_io *)ctsio);
6251 			return (CTL_RETVAL_COMPLETE);
6252 		}
6253 
6254 		/* Revert to defaults. */
6255 		ctl_init_page_index(lun);
6256 		mtx_lock(&lun->lun_lock);
6257 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6258 		mtx_unlock(&lun->lun_lock);
6259 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6260 			ctl_isc_announce_mode(lun, -1,
6261 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6262 			    lun->mode_pages.index[i].subpage);
6263 		}
6264 		ctl_set_success(ctsio);
6265 		ctl_done((union ctl_io *)ctsio);
6266 		return (CTL_RETVAL_COMPLETE);
6267 	}
6268 
6269 	/*
6270 	 * From SPC-3:
6271 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6272 	 * shall be empty. This condition shall not be considered as an error."
6273 	 */
6274 	if (param_len == 0) {
6275 		ctl_set_success(ctsio);
6276 		ctl_done((union ctl_io *)ctsio);
6277 		return (CTL_RETVAL_COMPLETE);
6278 	}
6279 
6280 	/*
6281 	 * Since we'll hit this the first time through, prior to
6282 	 * allocation, we don't need to free a data buffer here.
6283 	 */
6284 	if (param_len < header_size) {
6285 		ctl_set_param_len_error(ctsio);
6286 		ctl_done((union ctl_io *)ctsio);
6287 		return (CTL_RETVAL_COMPLETE);
6288 	}
6289 
6290 	/*
6291 	 * Allocate the data buffer and grab the user's data.  In theory,
6292 	 * we shouldn't have to sanity check the parameter list length here
6293 	 * because the maximum size is 64K.  We should be able to malloc
6294 	 * that much without too many problems.
6295 	 */
6296 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6297 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6298 		ctsio->kern_data_len = param_len;
6299 		ctsio->kern_total_len = param_len;
6300 		ctsio->kern_rel_offset = 0;
6301 		ctsio->kern_sg_entries = 0;
6302 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6303 		ctsio->be_move_done = ctl_config_move_done;
6304 		ctl_datamove((union ctl_io *)ctsio);
6305 
6306 		return (CTL_RETVAL_COMPLETE);
6307 	}
6308 
6309 	switch (ctsio->cdb[0]) {
6310 	case MODE_SELECT_6: {
6311 		struct scsi_mode_header_6 *mh6;
6312 
6313 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6314 		bd_len = mh6->blk_desc_len;
6315 		break;
6316 	}
6317 	case MODE_SELECT_10: {
6318 		struct scsi_mode_header_10 *mh10;
6319 
6320 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6321 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6322 		break;
6323 	}
6324 	default:
6325 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6326 	}
6327 
6328 	if (param_len < (header_size + bd_len)) {
6329 		free(ctsio->kern_data_ptr, M_CTL);
6330 		ctl_set_param_len_error(ctsio);
6331 		ctl_done((union ctl_io *)ctsio);
6332 		return (CTL_RETVAL_COMPLETE);
6333 	}
6334 
6335 	/*
6336 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6337 	 * ctl_config_write_done(), it'll get passed back to
6338 	 * ctl_do_mode_select() for further processing, or completion if
6339 	 * we're all done.
6340 	 */
6341 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6342 	ctsio->io_cont = ctl_do_mode_select;
6343 
6344 	modepage_info = (union ctl_modepage_info *)
6345 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6346 	memset(modepage_info, 0, sizeof(*modepage_info));
6347 	modepage_info->header.len_left = param_len - header_size - bd_len;
6348 	modepage_info->header.len_used = header_size + bd_len;
6349 
6350 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6351 }
6352 
6353 int
6354 ctl_mode_sense(struct ctl_scsiio *ctsio)
6355 {
6356 	struct ctl_lun *lun = CTL_LUN(ctsio);
6357 	int pc, page_code, dbd, subpage;
6358 	int alloc_len, page_len, header_len, total_len;
6359 	struct scsi_mode_block_descr *block_desc;
6360 	struct ctl_page_index *page_index;
6361 
6362 	dbd = 0;
6363 	block_desc = NULL;
6364 
6365 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6366 
6367 	switch (ctsio->cdb[0]) {
6368 	case MODE_SENSE_6: {
6369 		struct scsi_mode_sense_6 *cdb;
6370 
6371 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6372 
6373 		header_len = sizeof(struct scsi_mode_hdr_6);
6374 		if (cdb->byte2 & SMS_DBD)
6375 			dbd = 1;
6376 		else
6377 			header_len += sizeof(struct scsi_mode_block_descr);
6378 
6379 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6380 		page_code = cdb->page & SMS_PAGE_CODE;
6381 		subpage = cdb->subpage;
6382 		alloc_len = cdb->length;
6383 		break;
6384 	}
6385 	case MODE_SENSE_10: {
6386 		struct scsi_mode_sense_10 *cdb;
6387 
6388 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6389 
6390 		header_len = sizeof(struct scsi_mode_hdr_10);
6391 
6392 		if (cdb->byte2 & SMS_DBD)
6393 			dbd = 1;
6394 		else
6395 			header_len += sizeof(struct scsi_mode_block_descr);
6396 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6397 		page_code = cdb->page & SMS_PAGE_CODE;
6398 		subpage = cdb->subpage;
6399 		alloc_len = scsi_2btoul(cdb->length);
6400 		break;
6401 	}
6402 	default:
6403 		ctl_set_invalid_opcode(ctsio);
6404 		ctl_done((union ctl_io *)ctsio);
6405 		return (CTL_RETVAL_COMPLETE);
6406 		break; /* NOTREACHED */
6407 	}
6408 
6409 	/*
6410 	 * We have to make a first pass through to calculate the size of
6411 	 * the pages that match the user's query.  Then we allocate enough
6412 	 * memory to hold it, and actually copy the data into the buffer.
6413 	 */
6414 	switch (page_code) {
6415 	case SMS_ALL_PAGES_PAGE: {
6416 		u_int i;
6417 
6418 		page_len = 0;
6419 
6420 		/*
6421 		 * At the moment, values other than 0 and 0xff here are
6422 		 * reserved according to SPC-3.
6423 		 */
6424 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6425 		 && (subpage != SMS_SUBPAGE_ALL)) {
6426 			ctl_set_invalid_field(ctsio,
6427 					      /*sks_valid*/ 1,
6428 					      /*command*/ 1,
6429 					      /*field*/ 3,
6430 					      /*bit_valid*/ 0,
6431 					      /*bit*/ 0);
6432 			ctl_done((union ctl_io *)ctsio);
6433 			return (CTL_RETVAL_COMPLETE);
6434 		}
6435 
6436 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6437 			page_index = &lun->mode_pages.index[i];
6438 
6439 			/* Make sure the page is supported for this dev type */
6440 			if (lun->be_lun->lun_type == T_DIRECT &&
6441 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6442 				continue;
6443 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6444 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6445 				continue;
6446 			if (lun->be_lun->lun_type == T_CDROM &&
6447 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6448 				continue;
6449 
6450 			/*
6451 			 * We don't use this subpage if the user didn't
6452 			 * request all subpages.
6453 			 */
6454 			if ((page_index->subpage != 0)
6455 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6456 				continue;
6457 
6458 			page_len += page_index->page_len;
6459 		}
6460 		break;
6461 	}
6462 	default: {
6463 		u_int i;
6464 
6465 		page_len = 0;
6466 
6467 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6468 			page_index = &lun->mode_pages.index[i];
6469 
6470 			/* Make sure the page is supported for this dev type */
6471 			if (lun->be_lun->lun_type == T_DIRECT &&
6472 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6473 				continue;
6474 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6475 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6476 				continue;
6477 			if (lun->be_lun->lun_type == T_CDROM &&
6478 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6479 				continue;
6480 
6481 			/* Look for the right page code */
6482 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6483 				continue;
6484 
6485 			/* Look for the right subpage or the subpage wildcard*/
6486 			if ((page_index->subpage != subpage)
6487 			 && (subpage != SMS_SUBPAGE_ALL))
6488 				continue;
6489 
6490 			page_len += page_index->page_len;
6491 		}
6492 
6493 		if (page_len == 0) {
6494 			ctl_set_invalid_field(ctsio,
6495 					      /*sks_valid*/ 1,
6496 					      /*command*/ 1,
6497 					      /*field*/ 2,
6498 					      /*bit_valid*/ 1,
6499 					      /*bit*/ 5);
6500 			ctl_done((union ctl_io *)ctsio);
6501 			return (CTL_RETVAL_COMPLETE);
6502 		}
6503 		break;
6504 	}
6505 	}
6506 
6507 	total_len = header_len + page_len;
6508 
6509 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6510 	ctsio->kern_sg_entries = 0;
6511 	ctsio->kern_rel_offset = 0;
6512 	ctsio->kern_data_len = min(total_len, alloc_len);
6513 	ctsio->kern_total_len = ctsio->kern_data_len;
6514 
6515 	switch (ctsio->cdb[0]) {
6516 	case MODE_SENSE_6: {
6517 		struct scsi_mode_hdr_6 *header;
6518 
6519 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6520 
6521 		header->datalen = MIN(total_len - 1, 254);
6522 		if (lun->be_lun->lun_type == T_DIRECT) {
6523 			header->dev_specific = 0x10; /* DPOFUA */
6524 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6525 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6526 				header->dev_specific |= 0x80; /* WP */
6527 		}
6528 		if (dbd)
6529 			header->block_descr_len = 0;
6530 		else
6531 			header->block_descr_len =
6532 				sizeof(struct scsi_mode_block_descr);
6533 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6534 		break;
6535 	}
6536 	case MODE_SENSE_10: {
6537 		struct scsi_mode_hdr_10 *header;
6538 		int datalen;
6539 
6540 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6541 
6542 		datalen = MIN(total_len - 2, 65533);
6543 		scsi_ulto2b(datalen, header->datalen);
6544 		if (lun->be_lun->lun_type == T_DIRECT) {
6545 			header->dev_specific = 0x10; /* DPOFUA */
6546 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6547 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6548 				header->dev_specific |= 0x80; /* WP */
6549 		}
6550 		if (dbd)
6551 			scsi_ulto2b(0, header->block_descr_len);
6552 		else
6553 			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6554 				    header->block_descr_len);
6555 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6556 		break;
6557 	}
6558 	default:
6559 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6560 	}
6561 
6562 	/*
6563 	 * If we've got a disk, use its blocksize in the block
6564 	 * descriptor.  Otherwise, just set it to 0.
6565 	 */
6566 	if (dbd == 0) {
6567 		if (lun->be_lun->lun_type == T_DIRECT)
6568 			scsi_ulto3b(lun->be_lun->blocksize,
6569 				    block_desc->block_len);
6570 		else
6571 			scsi_ulto3b(0, block_desc->block_len);
6572 	}
6573 
6574 	switch (page_code) {
6575 	case SMS_ALL_PAGES_PAGE: {
6576 		int i, data_used;
6577 
6578 		data_used = header_len;
6579 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6580 			struct ctl_page_index *page_index;
6581 
6582 			page_index = &lun->mode_pages.index[i];
6583 			if (lun->be_lun->lun_type == T_DIRECT &&
6584 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6585 				continue;
6586 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6587 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6588 				continue;
6589 			if (lun->be_lun->lun_type == T_CDROM &&
6590 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6591 				continue;
6592 
6593 			/*
6594 			 * We don't use this subpage if the user didn't
6595 			 * request all subpages.  We already checked (above)
6596 			 * to make sure the user only specified a subpage
6597 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6598 			 */
6599 			if ((page_index->subpage != 0)
6600 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6601 				continue;
6602 
6603 			/*
6604 			 * Call the handler, if it exists, to update the
6605 			 * page to the latest values.
6606 			 */
6607 			if (page_index->sense_handler != NULL)
6608 				page_index->sense_handler(ctsio, page_index,pc);
6609 
6610 			memcpy(ctsio->kern_data_ptr + data_used,
6611 			       page_index->page_data +
6612 			       (page_index->page_len * pc),
6613 			       page_index->page_len);
6614 			data_used += page_index->page_len;
6615 		}
6616 		break;
6617 	}
6618 	default: {
6619 		int i, data_used;
6620 
6621 		data_used = header_len;
6622 
6623 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6624 			struct ctl_page_index *page_index;
6625 
6626 			page_index = &lun->mode_pages.index[i];
6627 
6628 			/* Look for the right page code */
6629 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6630 				continue;
6631 
6632 			/* Look for the right subpage or the subpage wildcard*/
6633 			if ((page_index->subpage != subpage)
6634 			 && (subpage != SMS_SUBPAGE_ALL))
6635 				continue;
6636 
6637 			/* Make sure the page is supported for this dev type */
6638 			if (lun->be_lun->lun_type == T_DIRECT &&
6639 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6640 				continue;
6641 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6642 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6643 				continue;
6644 			if (lun->be_lun->lun_type == T_CDROM &&
6645 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6646 				continue;
6647 
6648 			/*
6649 			 * Call the handler, if it exists, to update the
6650 			 * page to the latest values.
6651 			 */
6652 			if (page_index->sense_handler != NULL)
6653 				page_index->sense_handler(ctsio, page_index,pc);
6654 
6655 			memcpy(ctsio->kern_data_ptr + data_used,
6656 			       page_index->page_data +
6657 			       (page_index->page_len * pc),
6658 			       page_index->page_len);
6659 			data_used += page_index->page_len;
6660 		}
6661 		break;
6662 	}
6663 	}
6664 
6665 	ctl_set_success(ctsio);
6666 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6667 	ctsio->be_move_done = ctl_config_move_done;
6668 	ctl_datamove((union ctl_io *)ctsio);
6669 	return (CTL_RETVAL_COMPLETE);
6670 }
6671 
6672 int
6673 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6674 			       struct ctl_page_index *page_index,
6675 			       int pc)
6676 {
6677 	struct ctl_lun *lun = CTL_LUN(ctsio);
6678 	struct scsi_log_param_header *phdr;
6679 	uint8_t *data;
6680 	uint64_t val;
6681 
6682 	data = page_index->page_data;
6683 
6684 	if (lun->backend->lun_attr != NULL &&
6685 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6686 	     != UINT64_MAX) {
6687 		phdr = (struct scsi_log_param_header *)data;
6688 		scsi_ulto2b(0x0001, phdr->param_code);
6689 		phdr->param_control = SLP_LBIN | SLP_LP;
6690 		phdr->param_len = 8;
6691 		data = (uint8_t *)(phdr + 1);
6692 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6693 		data[4] = 0x02; /* per-pool */
6694 		data += phdr->param_len;
6695 	}
6696 
6697 	if (lun->backend->lun_attr != NULL &&
6698 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6699 	     != UINT64_MAX) {
6700 		phdr = (struct scsi_log_param_header *)data;
6701 		scsi_ulto2b(0x0002, phdr->param_code);
6702 		phdr->param_control = SLP_LBIN | SLP_LP;
6703 		phdr->param_len = 8;
6704 		data = (uint8_t *)(phdr + 1);
6705 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6706 		data[4] = 0x01; /* per-LUN */
6707 		data += phdr->param_len;
6708 	}
6709 
6710 	if (lun->backend->lun_attr != NULL &&
6711 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6712 	     != UINT64_MAX) {
6713 		phdr = (struct scsi_log_param_header *)data;
6714 		scsi_ulto2b(0x00f1, phdr->param_code);
6715 		phdr->param_control = SLP_LBIN | SLP_LP;
6716 		phdr->param_len = 8;
6717 		data = (uint8_t *)(phdr + 1);
6718 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6719 		data[4] = 0x02; /* per-pool */
6720 		data += phdr->param_len;
6721 	}
6722 
6723 	if (lun->backend->lun_attr != NULL &&
6724 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6725 	     != UINT64_MAX) {
6726 		phdr = (struct scsi_log_param_header *)data;
6727 		scsi_ulto2b(0x00f2, phdr->param_code);
6728 		phdr->param_control = SLP_LBIN | SLP_LP;
6729 		phdr->param_len = 8;
6730 		data = (uint8_t *)(phdr + 1);
6731 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6732 		data[4] = 0x02; /* per-pool */
6733 		data += phdr->param_len;
6734 	}
6735 
6736 	page_index->page_len = data - page_index->page_data;
6737 	return (0);
6738 }
6739 
6740 int
6741 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6742 			       struct ctl_page_index *page_index,
6743 			       int pc)
6744 {
6745 	struct ctl_lun *lun = CTL_LUN(ctsio);
6746 	struct stat_page *data;
6747 	struct bintime *t;
6748 
6749 	data = (struct stat_page *)page_index->page_data;
6750 
6751 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6752 	data->sap.hdr.param_control = SLP_LBIN;
6753 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6754 	    sizeof(struct scsi_log_param_header);
6755 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6756 	    data->sap.read_num);
6757 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6758 	    data->sap.write_num);
6759 	if (lun->be_lun->blocksize > 0) {
6760 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6761 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6762 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6763 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6764 	}
6765 	t = &lun->stats.time[CTL_STATS_READ];
6766 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6767 	    data->sap.read_int);
6768 	t = &lun->stats.time[CTL_STATS_WRITE];
6769 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6770 	    data->sap.write_int);
6771 	scsi_u64to8b(0, data->sap.weighted_num);
6772 	scsi_u64to8b(0, data->sap.weighted_int);
6773 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6774 	data->it.hdr.param_control = SLP_LBIN;
6775 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6776 	    sizeof(struct scsi_log_param_header);
6777 #ifdef CTL_TIME_IO
6778 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6779 #endif
6780 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6781 	data->it.hdr.param_control = SLP_LBIN;
6782 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6783 	    sizeof(struct scsi_log_param_header);
6784 	scsi_ulto4b(3, data->ti.exponent);
6785 	scsi_ulto4b(1, data->ti.integer);
6786 	return (0);
6787 }
6788 
6789 int
6790 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6791 			       struct ctl_page_index *page_index,
6792 			       int pc)
6793 {
6794 	struct ctl_lun *lun = CTL_LUN(ctsio);
6795 	struct scsi_log_informational_exceptions *data;
6796 
6797 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6798 
6799 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6800 	data->hdr.param_control = SLP_LBIN;
6801 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6802 	    sizeof(struct scsi_log_param_header);
6803 	data->ie_asc = lun->ie_asc;
6804 	data->ie_ascq = lun->ie_ascq;
6805 	data->temperature = 0xff;
6806 	return (0);
6807 }
6808 
6809 int
6810 ctl_log_sense(struct ctl_scsiio *ctsio)
6811 {
6812 	struct ctl_lun *lun = CTL_LUN(ctsio);
6813 	int i, pc, page_code, subpage;
6814 	int alloc_len, total_len;
6815 	struct ctl_page_index *page_index;
6816 	struct scsi_log_sense *cdb;
6817 	struct scsi_log_header *header;
6818 
6819 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6820 
6821 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6822 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6823 	page_code = cdb->page & SLS_PAGE_CODE;
6824 	subpage = cdb->subpage;
6825 	alloc_len = scsi_2btoul(cdb->length);
6826 
6827 	page_index = NULL;
6828 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6829 		page_index = &lun->log_pages.index[i];
6830 
6831 		/* Look for the right page code */
6832 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6833 			continue;
6834 
6835 		/* Look for the right subpage or the subpage wildcard*/
6836 		if (page_index->subpage != subpage)
6837 			continue;
6838 
6839 		break;
6840 	}
6841 	if (i >= CTL_NUM_LOG_PAGES) {
6842 		ctl_set_invalid_field(ctsio,
6843 				      /*sks_valid*/ 1,
6844 				      /*command*/ 1,
6845 				      /*field*/ 2,
6846 				      /*bit_valid*/ 0,
6847 				      /*bit*/ 0);
6848 		ctl_done((union ctl_io *)ctsio);
6849 		return (CTL_RETVAL_COMPLETE);
6850 	}
6851 
6852 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6853 
6854 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6855 	ctsio->kern_sg_entries = 0;
6856 	ctsio->kern_rel_offset = 0;
6857 	ctsio->kern_data_len = min(total_len, alloc_len);
6858 	ctsio->kern_total_len = ctsio->kern_data_len;
6859 
6860 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6861 	header->page = page_index->page_code;
6862 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6863 		header->page |= SL_DS;
6864 	if (page_index->subpage) {
6865 		header->page |= SL_SPF;
6866 		header->subpage = page_index->subpage;
6867 	}
6868 	scsi_ulto2b(page_index->page_len, header->datalen);
6869 
6870 	/*
6871 	 * Call the handler, if it exists, to update the
6872 	 * page to the latest values.
6873 	 */
6874 	if (page_index->sense_handler != NULL)
6875 		page_index->sense_handler(ctsio, page_index, pc);
6876 
6877 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6878 
6879 	ctl_set_success(ctsio);
6880 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6881 	ctsio->be_move_done = ctl_config_move_done;
6882 	ctl_datamove((union ctl_io *)ctsio);
6883 	return (CTL_RETVAL_COMPLETE);
6884 }
6885 
6886 int
6887 ctl_read_capacity(struct ctl_scsiio *ctsio)
6888 {
6889 	struct ctl_lun *lun = CTL_LUN(ctsio);
6890 	struct scsi_read_capacity *cdb;
6891 	struct scsi_read_capacity_data *data;
6892 	uint32_t lba;
6893 
6894 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6895 
6896 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6897 
6898 	lba = scsi_4btoul(cdb->addr);
6899 	if (((cdb->pmi & SRC_PMI) == 0)
6900 	 && (lba != 0)) {
6901 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6902 				      /*sks_valid*/ 1,
6903 				      /*command*/ 1,
6904 				      /*field*/ 2,
6905 				      /*bit_valid*/ 0,
6906 				      /*bit*/ 0);
6907 		ctl_done((union ctl_io *)ctsio);
6908 		return (CTL_RETVAL_COMPLETE);
6909 	}
6910 
6911 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6912 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6913 	ctsio->kern_data_len = sizeof(*data);
6914 	ctsio->kern_total_len = sizeof(*data);
6915 	ctsio->kern_rel_offset = 0;
6916 	ctsio->kern_sg_entries = 0;
6917 
6918 	/*
6919 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6920 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6921 	 * serivce action set.
6922 	 */
6923 	if (lun->be_lun->maxlba > 0xfffffffe)
6924 		scsi_ulto4b(0xffffffff, data->addr);
6925 	else
6926 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6927 
6928 	/*
6929 	 * XXX KDM this may not be 512 bytes...
6930 	 */
6931 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6932 
6933 	ctl_set_success(ctsio);
6934 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6935 	ctsio->be_move_done = ctl_config_move_done;
6936 	ctl_datamove((union ctl_io *)ctsio);
6937 	return (CTL_RETVAL_COMPLETE);
6938 }
6939 
6940 int
6941 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6942 {
6943 	struct ctl_lun *lun = CTL_LUN(ctsio);
6944 	struct scsi_read_capacity_16 *cdb;
6945 	struct scsi_read_capacity_data_long *data;
6946 	uint64_t lba;
6947 	uint32_t alloc_len;
6948 
6949 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6950 
6951 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6952 
6953 	alloc_len = scsi_4btoul(cdb->alloc_len);
6954 	lba = scsi_8btou64(cdb->addr);
6955 
6956 	if ((cdb->reladr & SRC16_PMI)
6957 	 && (lba != 0)) {
6958 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6959 				      /*sks_valid*/ 1,
6960 				      /*command*/ 1,
6961 				      /*field*/ 2,
6962 				      /*bit_valid*/ 0,
6963 				      /*bit*/ 0);
6964 		ctl_done((union ctl_io *)ctsio);
6965 		return (CTL_RETVAL_COMPLETE);
6966 	}
6967 
6968 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6969 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6970 	ctsio->kern_rel_offset = 0;
6971 	ctsio->kern_sg_entries = 0;
6972 	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
6973 	ctsio->kern_total_len = ctsio->kern_data_len;
6974 
6975 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6976 	/* XXX KDM this may not be 512 bytes... */
6977 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6978 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6979 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6980 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6981 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6982 
6983 	ctl_set_success(ctsio);
6984 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6985 	ctsio->be_move_done = ctl_config_move_done;
6986 	ctl_datamove((union ctl_io *)ctsio);
6987 	return (CTL_RETVAL_COMPLETE);
6988 }
6989 
6990 int
6991 ctl_get_lba_status(struct ctl_scsiio *ctsio)
6992 {
6993 	struct ctl_lun *lun = CTL_LUN(ctsio);
6994 	struct scsi_get_lba_status *cdb;
6995 	struct scsi_get_lba_status_data *data;
6996 	struct ctl_lba_len_flags *lbalen;
6997 	uint64_t lba;
6998 	uint32_t alloc_len, total_len;
6999 	int retval;
7000 
7001 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7002 
7003 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7004 	lba = scsi_8btou64(cdb->addr);
7005 	alloc_len = scsi_4btoul(cdb->alloc_len);
7006 
7007 	if (lba > lun->be_lun->maxlba) {
7008 		ctl_set_lba_out_of_range(ctsio, lba);
7009 		ctl_done((union ctl_io *)ctsio);
7010 		return (CTL_RETVAL_COMPLETE);
7011 	}
7012 
7013 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7014 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7015 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7016 	ctsio->kern_rel_offset = 0;
7017 	ctsio->kern_sg_entries = 0;
7018 	ctsio->kern_data_len = min(total_len, alloc_len);
7019 	ctsio->kern_total_len = ctsio->kern_data_len;
7020 
7021 	/* Fill dummy data in case backend can't tell anything. */
7022 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7023 	scsi_u64to8b(lba, data->descr[0].addr);
7024 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7025 	    data->descr[0].length);
7026 	data->descr[0].status = 0; /* Mapped or unknown. */
7027 
7028 	ctl_set_success(ctsio);
7029 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7030 	ctsio->be_move_done = ctl_config_move_done;
7031 
7032 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7033 	lbalen->lba = lba;
7034 	lbalen->len = total_len;
7035 	lbalen->flags = 0;
7036 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7037 	return (retval);
7038 }
7039 
7040 int
7041 ctl_read_defect(struct ctl_scsiio *ctsio)
7042 {
7043 	struct scsi_read_defect_data_10 *ccb10;
7044 	struct scsi_read_defect_data_12 *ccb12;
7045 	struct scsi_read_defect_data_hdr_10 *data10;
7046 	struct scsi_read_defect_data_hdr_12 *data12;
7047 	uint32_t alloc_len, data_len;
7048 	uint8_t format;
7049 
7050 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7051 
7052 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7053 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7054 		format = ccb10->format;
7055 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7056 		data_len = sizeof(*data10);
7057 	} else {
7058 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7059 		format = ccb12->format;
7060 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7061 		data_len = sizeof(*data12);
7062 	}
7063 	if (alloc_len == 0) {
7064 		ctl_set_success(ctsio);
7065 		ctl_done((union ctl_io *)ctsio);
7066 		return (CTL_RETVAL_COMPLETE);
7067 	}
7068 
7069 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7070 	ctsio->kern_rel_offset = 0;
7071 	ctsio->kern_sg_entries = 0;
7072 	ctsio->kern_data_len = min(data_len, alloc_len);
7073 	ctsio->kern_total_len = ctsio->kern_data_len;
7074 
7075 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7076 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7077 		    ctsio->kern_data_ptr;
7078 		data10->format = format;
7079 		scsi_ulto2b(0, data10->length);
7080 	} else {
7081 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7082 		    ctsio->kern_data_ptr;
7083 		data12->format = format;
7084 		scsi_ulto2b(0, data12->generation);
7085 		scsi_ulto4b(0, data12->length);
7086 	}
7087 
7088 	ctl_set_success(ctsio);
7089 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7090 	ctsio->be_move_done = ctl_config_move_done;
7091 	ctl_datamove((union ctl_io *)ctsio);
7092 	return (CTL_RETVAL_COMPLETE);
7093 }
7094 
7095 int
7096 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7097 {
7098 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7099 	struct ctl_lun *lun = CTL_LUN(ctsio);
7100 	struct scsi_maintenance_in *cdb;
7101 	int retval;
7102 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7103 	int num_ha_groups, num_target_ports, shared_group;
7104 	struct ctl_port *port;
7105 	struct scsi_target_group_data *rtg_ptr;
7106 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7107 	struct scsi_target_port_group_descriptor *tpg_desc;
7108 
7109 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7110 
7111 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7112 	retval = CTL_RETVAL_COMPLETE;
7113 
7114 	switch (cdb->byte2 & STG_PDF_MASK) {
7115 	case STG_PDF_LENGTH:
7116 		ext = 0;
7117 		break;
7118 	case STG_PDF_EXTENDED:
7119 		ext = 1;
7120 		break;
7121 	default:
7122 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7123 				      /*sks_valid*/ 1,
7124 				      /*command*/ 1,
7125 				      /*field*/ 2,
7126 				      /*bit_valid*/ 1,
7127 				      /*bit*/ 5);
7128 		ctl_done((union ctl_io *)ctsio);
7129 		return(retval);
7130 	}
7131 
7132 	num_target_ports = 0;
7133 	shared_group = (softc->is_single != 0);
7134 	mtx_lock(&softc->ctl_lock);
7135 	STAILQ_FOREACH(port, &softc->port_list, links) {
7136 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7137 			continue;
7138 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7139 			continue;
7140 		num_target_ports++;
7141 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7142 			shared_group = 1;
7143 	}
7144 	mtx_unlock(&softc->ctl_lock);
7145 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7146 
7147 	if (ext)
7148 		total_len = sizeof(struct scsi_target_group_data_extended);
7149 	else
7150 		total_len = sizeof(struct scsi_target_group_data);
7151 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7152 		(shared_group + num_ha_groups) +
7153 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7154 
7155 	alloc_len = scsi_4btoul(cdb->length);
7156 
7157 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7158 	ctsio->kern_sg_entries = 0;
7159 	ctsio->kern_rel_offset = 0;
7160 	ctsio->kern_data_len = min(total_len, alloc_len);
7161 	ctsio->kern_total_len = ctsio->kern_data_len;
7162 
7163 	if (ext) {
7164 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7165 		    ctsio->kern_data_ptr;
7166 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7167 		rtg_ext_ptr->format_type = 0x10;
7168 		rtg_ext_ptr->implicit_transition_time = 0;
7169 		tpg_desc = &rtg_ext_ptr->groups[0];
7170 	} else {
7171 		rtg_ptr = (struct scsi_target_group_data *)
7172 		    ctsio->kern_data_ptr;
7173 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7174 		tpg_desc = &rtg_ptr->groups[0];
7175 	}
7176 
7177 	mtx_lock(&softc->ctl_lock);
7178 	pg = softc->port_min / softc->port_cnt;
7179 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7180 		/* Some shelf is known to be primary. */
7181 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7182 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7183 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7184 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7185 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7186 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7187 		else
7188 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7189 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7190 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7191 		} else {
7192 			ts = os;
7193 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7194 		}
7195 	} else {
7196 		/* No known primary shelf. */
7197 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7198 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7199 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7200 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7201 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7202 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7203 		} else {
7204 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7205 		}
7206 	}
7207 	if (shared_group) {
7208 		tpg_desc->pref_state = ts;
7209 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7210 		    TPG_U_SUP | TPG_T_SUP;
7211 		scsi_ulto2b(1, tpg_desc->target_port_group);
7212 		tpg_desc->status = TPG_IMPLICIT;
7213 		pc = 0;
7214 		STAILQ_FOREACH(port, &softc->port_list, links) {
7215 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7216 				continue;
7217 			if (!softc->is_single &&
7218 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7219 				continue;
7220 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7221 				continue;
7222 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7223 			    relative_target_port_identifier);
7224 			pc++;
7225 		}
7226 		tpg_desc->target_port_count = pc;
7227 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7228 		    &tpg_desc->descriptors[pc];
7229 	}
7230 	for (g = 0; g < num_ha_groups; g++) {
7231 		tpg_desc->pref_state = (g == pg) ? ts : os;
7232 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7233 		    TPG_U_SUP | TPG_T_SUP;
7234 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7235 		tpg_desc->status = TPG_IMPLICIT;
7236 		pc = 0;
7237 		STAILQ_FOREACH(port, &softc->port_list, links) {
7238 			if (port->targ_port < g * softc->port_cnt ||
7239 			    port->targ_port >= (g + 1) * softc->port_cnt)
7240 				continue;
7241 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7242 				continue;
7243 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7244 				continue;
7245 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7246 				continue;
7247 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7248 			    relative_target_port_identifier);
7249 			pc++;
7250 		}
7251 		tpg_desc->target_port_count = pc;
7252 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7253 		    &tpg_desc->descriptors[pc];
7254 	}
7255 	mtx_unlock(&softc->ctl_lock);
7256 
7257 	ctl_set_success(ctsio);
7258 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7259 	ctsio->be_move_done = ctl_config_move_done;
7260 	ctl_datamove((union ctl_io *)ctsio);
7261 	return(retval);
7262 }
7263 
7264 int
7265 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7266 {
7267 	struct ctl_lun *lun = CTL_LUN(ctsio);
7268 	struct scsi_report_supported_opcodes *cdb;
7269 	const struct ctl_cmd_entry *entry, *sentry;
7270 	struct scsi_report_supported_opcodes_all *all;
7271 	struct scsi_report_supported_opcodes_descr *descr;
7272 	struct scsi_report_supported_opcodes_one *one;
7273 	int retval;
7274 	int alloc_len, total_len;
7275 	int opcode, service_action, i, j, num;
7276 
7277 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7278 
7279 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7280 	retval = CTL_RETVAL_COMPLETE;
7281 
7282 	opcode = cdb->requested_opcode;
7283 	service_action = scsi_2btoul(cdb->requested_service_action);
7284 	switch (cdb->options & RSO_OPTIONS_MASK) {
7285 	case RSO_OPTIONS_ALL:
7286 		num = 0;
7287 		for (i = 0; i < 256; i++) {
7288 			entry = &ctl_cmd_table[i];
7289 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7290 				for (j = 0; j < 32; j++) {
7291 					sentry = &((const struct ctl_cmd_entry *)
7292 					    entry->execute)[j];
7293 					if (ctl_cmd_applicable(
7294 					    lun->be_lun->lun_type, sentry))
7295 						num++;
7296 				}
7297 			} else {
7298 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7299 				    entry))
7300 					num++;
7301 			}
7302 		}
7303 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7304 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7305 		break;
7306 	case RSO_OPTIONS_OC:
7307 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7308 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7309 					      /*sks_valid*/ 1,
7310 					      /*command*/ 1,
7311 					      /*field*/ 2,
7312 					      /*bit_valid*/ 1,
7313 					      /*bit*/ 2);
7314 			ctl_done((union ctl_io *)ctsio);
7315 			return (CTL_RETVAL_COMPLETE);
7316 		}
7317 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7318 		break;
7319 	case RSO_OPTIONS_OC_SA:
7320 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7321 		    service_action >= 32) {
7322 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7323 					      /*sks_valid*/ 1,
7324 					      /*command*/ 1,
7325 					      /*field*/ 2,
7326 					      /*bit_valid*/ 1,
7327 					      /*bit*/ 2);
7328 			ctl_done((union ctl_io *)ctsio);
7329 			return (CTL_RETVAL_COMPLETE);
7330 		}
7331 		/* FALLTHROUGH */
7332 	case RSO_OPTIONS_OC_ASA:
7333 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7334 		break;
7335 	default:
7336 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7337 				      /*sks_valid*/ 1,
7338 				      /*command*/ 1,
7339 				      /*field*/ 2,
7340 				      /*bit_valid*/ 1,
7341 				      /*bit*/ 2);
7342 		ctl_done((union ctl_io *)ctsio);
7343 		return (CTL_RETVAL_COMPLETE);
7344 	}
7345 
7346 	alloc_len = scsi_4btoul(cdb->length);
7347 
7348 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7349 	ctsio->kern_sg_entries = 0;
7350 	ctsio->kern_rel_offset = 0;
7351 	ctsio->kern_data_len = min(total_len, alloc_len);
7352 	ctsio->kern_total_len = ctsio->kern_data_len;
7353 
7354 	switch (cdb->options & RSO_OPTIONS_MASK) {
7355 	case RSO_OPTIONS_ALL:
7356 		all = (struct scsi_report_supported_opcodes_all *)
7357 		    ctsio->kern_data_ptr;
7358 		num = 0;
7359 		for (i = 0; i < 256; i++) {
7360 			entry = &ctl_cmd_table[i];
7361 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7362 				for (j = 0; j < 32; j++) {
7363 					sentry = &((const struct ctl_cmd_entry *)
7364 					    entry->execute)[j];
7365 					if (!ctl_cmd_applicable(
7366 					    lun->be_lun->lun_type, sentry))
7367 						continue;
7368 					descr = &all->descr[num++];
7369 					descr->opcode = i;
7370 					scsi_ulto2b(j, descr->service_action);
7371 					descr->flags = RSO_SERVACTV;
7372 					scsi_ulto2b(sentry->length,
7373 					    descr->cdb_length);
7374 				}
7375 			} else {
7376 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7377 				    entry))
7378 					continue;
7379 				descr = &all->descr[num++];
7380 				descr->opcode = i;
7381 				scsi_ulto2b(0, descr->service_action);
7382 				descr->flags = 0;
7383 				scsi_ulto2b(entry->length, descr->cdb_length);
7384 			}
7385 		}
7386 		scsi_ulto4b(
7387 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7388 		    all->length);
7389 		break;
7390 	case RSO_OPTIONS_OC:
7391 		one = (struct scsi_report_supported_opcodes_one *)
7392 		    ctsio->kern_data_ptr;
7393 		entry = &ctl_cmd_table[opcode];
7394 		goto fill_one;
7395 	case RSO_OPTIONS_OC_SA:
7396 		one = (struct scsi_report_supported_opcodes_one *)
7397 		    ctsio->kern_data_ptr;
7398 		entry = &ctl_cmd_table[opcode];
7399 		entry = &((const struct ctl_cmd_entry *)
7400 		    entry->execute)[service_action];
7401 fill_one:
7402 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7403 			one->support = 3;
7404 			scsi_ulto2b(entry->length, one->cdb_length);
7405 			one->cdb_usage[0] = opcode;
7406 			memcpy(&one->cdb_usage[1], entry->usage,
7407 			    entry->length - 1);
7408 		} else
7409 			one->support = 1;
7410 		break;
7411 	case RSO_OPTIONS_OC_ASA:
7412 		one = (struct scsi_report_supported_opcodes_one *)
7413 		    ctsio->kern_data_ptr;
7414 		entry = &ctl_cmd_table[opcode];
7415 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7416 			entry = &((const struct ctl_cmd_entry *)
7417 			    entry->execute)[service_action];
7418 		} else if (service_action != 0) {
7419 			one->support = 1;
7420 			break;
7421 		}
7422 		goto fill_one;
7423 	}
7424 
7425 	ctl_set_success(ctsio);
7426 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7427 	ctsio->be_move_done = ctl_config_move_done;
7428 	ctl_datamove((union ctl_io *)ctsio);
7429 	return(retval);
7430 }
7431 
7432 int
7433 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7434 {
7435 	struct scsi_report_supported_tmf *cdb;
7436 	struct scsi_report_supported_tmf_ext_data *data;
7437 	int retval;
7438 	int alloc_len, total_len;
7439 
7440 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7441 
7442 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7443 
7444 	retval = CTL_RETVAL_COMPLETE;
7445 
7446 	if (cdb->options & RST_REPD)
7447 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7448 	else
7449 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7450 	alloc_len = scsi_4btoul(cdb->length);
7451 
7452 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7453 	ctsio->kern_sg_entries = 0;
7454 	ctsio->kern_rel_offset = 0;
7455 	ctsio->kern_data_len = min(total_len, alloc_len);
7456 	ctsio->kern_total_len = ctsio->kern_data_len;
7457 
7458 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7459 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7460 	    RST_TRS;
7461 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7462 	data->length = total_len - 4;
7463 
7464 	ctl_set_success(ctsio);
7465 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7466 	ctsio->be_move_done = ctl_config_move_done;
7467 	ctl_datamove((union ctl_io *)ctsio);
7468 	return (retval);
7469 }
7470 
7471 int
7472 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7473 {
7474 	struct scsi_report_timestamp *cdb;
7475 	struct scsi_report_timestamp_data *data;
7476 	struct timeval tv;
7477 	int64_t timestamp;
7478 	int retval;
7479 	int alloc_len, total_len;
7480 
7481 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7482 
7483 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7484 
7485 	retval = CTL_RETVAL_COMPLETE;
7486 
7487 	total_len = sizeof(struct scsi_report_timestamp_data);
7488 	alloc_len = scsi_4btoul(cdb->length);
7489 
7490 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7491 	ctsio->kern_sg_entries = 0;
7492 	ctsio->kern_rel_offset = 0;
7493 	ctsio->kern_data_len = min(total_len, alloc_len);
7494 	ctsio->kern_total_len = ctsio->kern_data_len;
7495 
7496 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7497 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7498 	data->origin = RTS_ORIG_OUTSIDE;
7499 	getmicrotime(&tv);
7500 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7501 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7502 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7503 
7504 	ctl_set_success(ctsio);
7505 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7506 	ctsio->be_move_done = ctl_config_move_done;
7507 	ctl_datamove((union ctl_io *)ctsio);
7508 	return (retval);
7509 }
7510 
7511 int
7512 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7513 {
7514 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7515 	struct ctl_lun *lun = CTL_LUN(ctsio);
7516 	struct scsi_per_res_in *cdb;
7517 	int alloc_len, total_len = 0;
7518 	/* struct scsi_per_res_in_rsrv in_data; */
7519 	uint64_t key;
7520 
7521 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7522 
7523 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7524 
7525 	alloc_len = scsi_2btoul(cdb->length);
7526 
7527 retry:
7528 	mtx_lock(&lun->lun_lock);
7529 	switch (cdb->action) {
7530 	case SPRI_RK: /* read keys */
7531 		total_len = sizeof(struct scsi_per_res_in_keys) +
7532 			lun->pr_key_count *
7533 			sizeof(struct scsi_per_res_key);
7534 		break;
7535 	case SPRI_RR: /* read reservation */
7536 		if (lun->flags & CTL_LUN_PR_RESERVED)
7537 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7538 		else
7539 			total_len = sizeof(struct scsi_per_res_in_header);
7540 		break;
7541 	case SPRI_RC: /* report capabilities */
7542 		total_len = sizeof(struct scsi_per_res_cap);
7543 		break;
7544 	case SPRI_RS: /* read full status */
7545 		total_len = sizeof(struct scsi_per_res_in_header) +
7546 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7547 		    lun->pr_key_count;
7548 		break;
7549 	default:
7550 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7551 	}
7552 	mtx_unlock(&lun->lun_lock);
7553 
7554 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7555 	ctsio->kern_rel_offset = 0;
7556 	ctsio->kern_sg_entries = 0;
7557 	ctsio->kern_data_len = min(total_len, alloc_len);
7558 	ctsio->kern_total_len = ctsio->kern_data_len;
7559 
7560 	mtx_lock(&lun->lun_lock);
7561 	switch (cdb->action) {
7562 	case SPRI_RK: { // read keys
7563         struct scsi_per_res_in_keys *res_keys;
7564 		int i, key_count;
7565 
7566 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7567 
7568 		/*
7569 		 * We had to drop the lock to allocate our buffer, which
7570 		 * leaves time for someone to come in with another
7571 		 * persistent reservation.  (That is unlikely, though,
7572 		 * since this should be the only persistent reservation
7573 		 * command active right now.)
7574 		 */
7575 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7576 		    (lun->pr_key_count *
7577 		     sizeof(struct scsi_per_res_key)))){
7578 			mtx_unlock(&lun->lun_lock);
7579 			free(ctsio->kern_data_ptr, M_CTL);
7580 			printf("%s: reservation length changed, retrying\n",
7581 			       __func__);
7582 			goto retry;
7583 		}
7584 
7585 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7586 
7587 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7588 			     lun->pr_key_count, res_keys->header.length);
7589 
7590 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7591 			if ((key = ctl_get_prkey(lun, i)) == 0)
7592 				continue;
7593 
7594 			/*
7595 			 * We used lun->pr_key_count to calculate the
7596 			 * size to allocate.  If it turns out the number of
7597 			 * initiators with the registered flag set is
7598 			 * larger than that (i.e. they haven't been kept in
7599 			 * sync), we've got a problem.
7600 			 */
7601 			if (key_count >= lun->pr_key_count) {
7602 				key_count++;
7603 				continue;
7604 			}
7605 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7606 			key_count++;
7607 		}
7608 		break;
7609 	}
7610 	case SPRI_RR: { // read reservation
7611 		struct scsi_per_res_in_rsrv *res;
7612 		int tmp_len, header_only;
7613 
7614 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7615 
7616 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7617 
7618 		if (lun->flags & CTL_LUN_PR_RESERVED)
7619 		{
7620 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7621 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7622 				    res->header.length);
7623 			header_only = 0;
7624 		} else {
7625 			tmp_len = sizeof(struct scsi_per_res_in_header);
7626 			scsi_ulto4b(0, res->header.length);
7627 			header_only = 1;
7628 		}
7629 
7630 		/*
7631 		 * We had to drop the lock to allocate our buffer, which
7632 		 * leaves time for someone to come in with another
7633 		 * persistent reservation.  (That is unlikely, though,
7634 		 * since this should be the only persistent reservation
7635 		 * command active right now.)
7636 		 */
7637 		if (tmp_len != total_len) {
7638 			mtx_unlock(&lun->lun_lock);
7639 			free(ctsio->kern_data_ptr, M_CTL);
7640 			printf("%s: reservation status changed, retrying\n",
7641 			       __func__);
7642 			goto retry;
7643 		}
7644 
7645 		/*
7646 		 * No reservation held, so we're done.
7647 		 */
7648 		if (header_only != 0)
7649 			break;
7650 
7651 		/*
7652 		 * If the registration is an All Registrants type, the key
7653 		 * is 0, since it doesn't really matter.
7654 		 */
7655 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7656 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7657 			    res->data.reservation);
7658 		}
7659 		res->data.scopetype = lun->pr_res_type;
7660 		break;
7661 	}
7662 	case SPRI_RC:     //report capabilities
7663 	{
7664 		struct scsi_per_res_cap *res_cap;
7665 		uint16_t type_mask;
7666 
7667 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7668 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7669 		res_cap->flags1 = SPRI_CRH;
7670 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7671 		type_mask = SPRI_TM_WR_EX_AR |
7672 			    SPRI_TM_EX_AC_RO |
7673 			    SPRI_TM_WR_EX_RO |
7674 			    SPRI_TM_EX_AC |
7675 			    SPRI_TM_WR_EX |
7676 			    SPRI_TM_EX_AC_AR;
7677 		scsi_ulto2b(type_mask, res_cap->type_mask);
7678 		break;
7679 	}
7680 	case SPRI_RS: { // read full status
7681 		struct scsi_per_res_in_full *res_status;
7682 		struct scsi_per_res_in_full_desc *res_desc;
7683 		struct ctl_port *port;
7684 		int i, len;
7685 
7686 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7687 
7688 		/*
7689 		 * We had to drop the lock to allocate our buffer, which
7690 		 * leaves time for someone to come in with another
7691 		 * persistent reservation.  (That is unlikely, though,
7692 		 * since this should be the only persistent reservation
7693 		 * command active right now.)
7694 		 */
7695 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7696 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7697 		     lun->pr_key_count)){
7698 			mtx_unlock(&lun->lun_lock);
7699 			free(ctsio->kern_data_ptr, M_CTL);
7700 			printf("%s: reservation length changed, retrying\n",
7701 			       __func__);
7702 			goto retry;
7703 		}
7704 
7705 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7706 
7707 		res_desc = &res_status->desc[0];
7708 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7709 			if ((key = ctl_get_prkey(lun, i)) == 0)
7710 				continue;
7711 
7712 			scsi_u64to8b(key, res_desc->res_key.key);
7713 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7714 			    (lun->pr_res_idx == i ||
7715 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7716 				res_desc->flags = SPRI_FULL_R_HOLDER;
7717 				res_desc->scopetype = lun->pr_res_type;
7718 			}
7719 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7720 			    res_desc->rel_trgt_port_id);
7721 			len = 0;
7722 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7723 			if (port != NULL)
7724 				len = ctl_create_iid(port,
7725 				    i % CTL_MAX_INIT_PER_PORT,
7726 				    res_desc->transport_id);
7727 			scsi_ulto4b(len, res_desc->additional_length);
7728 			res_desc = (struct scsi_per_res_in_full_desc *)
7729 			    &res_desc->transport_id[len];
7730 		}
7731 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7732 		    res_status->header.length);
7733 		break;
7734 	}
7735 	default:
7736 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7737 	}
7738 	mtx_unlock(&lun->lun_lock);
7739 
7740 	ctl_set_success(ctsio);
7741 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7742 	ctsio->be_move_done = ctl_config_move_done;
7743 	ctl_datamove((union ctl_io *)ctsio);
7744 	return (CTL_RETVAL_COMPLETE);
7745 }
7746 
7747 /*
7748  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7749  * it should return.
7750  */
7751 static int
7752 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7753 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7754 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7755 		struct scsi_per_res_out_parms* param)
7756 {
7757 	union ctl_ha_msg persis_io;
7758 	int i;
7759 
7760 	mtx_lock(&lun->lun_lock);
7761 	if (sa_res_key == 0) {
7762 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7763 			/* validate scope and type */
7764 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7765 			     SPR_LU_SCOPE) {
7766 				mtx_unlock(&lun->lun_lock);
7767 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7768 						      /*sks_valid*/ 1,
7769 						      /*command*/ 1,
7770 						      /*field*/ 2,
7771 						      /*bit_valid*/ 1,
7772 						      /*bit*/ 4);
7773 				ctl_done((union ctl_io *)ctsio);
7774 				return (1);
7775 			}
7776 
7777 		        if (type>8 || type==2 || type==4 || type==0) {
7778 				mtx_unlock(&lun->lun_lock);
7779 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7780        	           				      /*sks_valid*/ 1,
7781 						      /*command*/ 1,
7782 						      /*field*/ 2,
7783 						      /*bit_valid*/ 1,
7784 						      /*bit*/ 0);
7785 				ctl_done((union ctl_io *)ctsio);
7786 				return (1);
7787 		        }
7788 
7789 			/*
7790 			 * Unregister everybody else and build UA for
7791 			 * them
7792 			 */
7793 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7794 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7795 					continue;
7796 
7797 				ctl_clr_prkey(lun, i);
7798 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7799 			}
7800 			lun->pr_key_count = 1;
7801 			lun->pr_res_type = type;
7802 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7803 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7804 				lun->pr_res_idx = residx;
7805 			lun->pr_generation++;
7806 			mtx_unlock(&lun->lun_lock);
7807 
7808 			/* send msg to other side */
7809 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7810 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7811 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7812 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7813 			persis_io.pr.pr_info.res_type = type;
7814 			memcpy(persis_io.pr.pr_info.sa_res_key,
7815 			       param->serv_act_res_key,
7816 			       sizeof(param->serv_act_res_key));
7817 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7818 			    sizeof(persis_io.pr), M_WAITOK);
7819 		} else {
7820 			/* not all registrants */
7821 			mtx_unlock(&lun->lun_lock);
7822 			free(ctsio->kern_data_ptr, M_CTL);
7823 			ctl_set_invalid_field(ctsio,
7824 					      /*sks_valid*/ 1,
7825 					      /*command*/ 0,
7826 					      /*field*/ 8,
7827 					      /*bit_valid*/ 0,
7828 					      /*bit*/ 0);
7829 			ctl_done((union ctl_io *)ctsio);
7830 			return (1);
7831 		}
7832 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7833 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7834 		int found = 0;
7835 
7836 		if (res_key == sa_res_key) {
7837 			/* special case */
7838 			/*
7839 			 * The spec implies this is not good but doesn't
7840 			 * say what to do. There are two choices either
7841 			 * generate a res conflict or check condition
7842 			 * with illegal field in parameter data. Since
7843 			 * that is what is done when the sa_res_key is
7844 			 * zero I'll take that approach since this has
7845 			 * to do with the sa_res_key.
7846 			 */
7847 			mtx_unlock(&lun->lun_lock);
7848 			free(ctsio->kern_data_ptr, M_CTL);
7849 			ctl_set_invalid_field(ctsio,
7850 					      /*sks_valid*/ 1,
7851 					      /*command*/ 0,
7852 					      /*field*/ 8,
7853 					      /*bit_valid*/ 0,
7854 					      /*bit*/ 0);
7855 			ctl_done((union ctl_io *)ctsio);
7856 			return (1);
7857 		}
7858 
7859 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7860 			if (ctl_get_prkey(lun, i) != sa_res_key)
7861 				continue;
7862 
7863 			found = 1;
7864 			ctl_clr_prkey(lun, i);
7865 			lun->pr_key_count--;
7866 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7867 		}
7868 		if (!found) {
7869 			mtx_unlock(&lun->lun_lock);
7870 			free(ctsio->kern_data_ptr, M_CTL);
7871 			ctl_set_reservation_conflict(ctsio);
7872 			ctl_done((union ctl_io *)ctsio);
7873 			return (CTL_RETVAL_COMPLETE);
7874 		}
7875 		lun->pr_generation++;
7876 		mtx_unlock(&lun->lun_lock);
7877 
7878 		/* send msg to other side */
7879 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7880 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7881 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7882 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7883 		persis_io.pr.pr_info.res_type = type;
7884 		memcpy(persis_io.pr.pr_info.sa_res_key,
7885 		       param->serv_act_res_key,
7886 		       sizeof(param->serv_act_res_key));
7887 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7888 		    sizeof(persis_io.pr), M_WAITOK);
7889 	} else {
7890 		/* Reserved but not all registrants */
7891 		/* sa_res_key is res holder */
7892 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7893 			/* validate scope and type */
7894 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7895 			     SPR_LU_SCOPE) {
7896 				mtx_unlock(&lun->lun_lock);
7897 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7898 						      /*sks_valid*/ 1,
7899 						      /*command*/ 1,
7900 						      /*field*/ 2,
7901 						      /*bit_valid*/ 1,
7902 						      /*bit*/ 4);
7903 				ctl_done((union ctl_io *)ctsio);
7904 				return (1);
7905 			}
7906 
7907 			if (type>8 || type==2 || type==4 || type==0) {
7908 				mtx_unlock(&lun->lun_lock);
7909 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7910 						      /*sks_valid*/ 1,
7911 						      /*command*/ 1,
7912 						      /*field*/ 2,
7913 						      /*bit_valid*/ 1,
7914 						      /*bit*/ 0);
7915 				ctl_done((union ctl_io *)ctsio);
7916 				return (1);
7917 			}
7918 
7919 			/*
7920 			 * Do the following:
7921 			 * if sa_res_key != res_key remove all
7922 			 * registrants w/sa_res_key and generate UA
7923 			 * for these registrants(Registrations
7924 			 * Preempted) if it wasn't an exclusive
7925 			 * reservation generate UA(Reservations
7926 			 * Preempted) for all other registered nexuses
7927 			 * if the type has changed. Establish the new
7928 			 * reservation and holder. If res_key and
7929 			 * sa_res_key are the same do the above
7930 			 * except don't unregister the res holder.
7931 			 */
7932 
7933 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7934 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7935 					continue;
7936 
7937 				if (sa_res_key == ctl_get_prkey(lun, i)) {
7938 					ctl_clr_prkey(lun, i);
7939 					lun->pr_key_count--;
7940 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7941 				} else if (type != lun->pr_res_type &&
7942 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7943 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7944 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7945 				}
7946 			}
7947 			lun->pr_res_type = type;
7948 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7949 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7950 				lun->pr_res_idx = residx;
7951 			else
7952 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7953 			lun->pr_generation++;
7954 			mtx_unlock(&lun->lun_lock);
7955 
7956 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7957 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7958 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7959 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7960 			persis_io.pr.pr_info.res_type = type;
7961 			memcpy(persis_io.pr.pr_info.sa_res_key,
7962 			       param->serv_act_res_key,
7963 			       sizeof(param->serv_act_res_key));
7964 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7965 			    sizeof(persis_io.pr), M_WAITOK);
7966 		} else {
7967 			/*
7968 			 * sa_res_key is not the res holder just
7969 			 * remove registrants
7970 			 */
7971 			int found=0;
7972 
7973 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7974 				if (sa_res_key != ctl_get_prkey(lun, i))
7975 					continue;
7976 
7977 				found = 1;
7978 				ctl_clr_prkey(lun, i);
7979 				lun->pr_key_count--;
7980 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7981 			}
7982 
7983 			if (!found) {
7984 				mtx_unlock(&lun->lun_lock);
7985 				free(ctsio->kern_data_ptr, M_CTL);
7986 				ctl_set_reservation_conflict(ctsio);
7987 				ctl_done((union ctl_io *)ctsio);
7988 		        	return (1);
7989 			}
7990 			lun->pr_generation++;
7991 			mtx_unlock(&lun->lun_lock);
7992 
7993 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7994 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7995 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7996 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7997 			persis_io.pr.pr_info.res_type = type;
7998 			memcpy(persis_io.pr.pr_info.sa_res_key,
7999 			       param->serv_act_res_key,
8000 			       sizeof(param->serv_act_res_key));
8001 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8002 			    sizeof(persis_io.pr), M_WAITOK);
8003 		}
8004 	}
8005 	return (0);
8006 }
8007 
8008 static void
8009 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8010 {
8011 	uint64_t sa_res_key;
8012 	int i;
8013 
8014 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8015 
8016 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8017 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8018 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8019 		if (sa_res_key == 0) {
8020 			/*
8021 			 * Unregister everybody else and build UA for
8022 			 * them
8023 			 */
8024 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8025 				if (i == msg->pr.pr_info.residx ||
8026 				    ctl_get_prkey(lun, i) == 0)
8027 					continue;
8028 
8029 				ctl_clr_prkey(lun, i);
8030 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8031 			}
8032 
8033 			lun->pr_key_count = 1;
8034 			lun->pr_res_type = msg->pr.pr_info.res_type;
8035 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8036 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8037 				lun->pr_res_idx = msg->pr.pr_info.residx;
8038 		} else {
8039 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8040 				if (sa_res_key == ctl_get_prkey(lun, i))
8041 					continue;
8042 
8043 				ctl_clr_prkey(lun, i);
8044 				lun->pr_key_count--;
8045 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8046 			}
8047 		}
8048 	} else {
8049 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8050 			if (i == msg->pr.pr_info.residx ||
8051 			    ctl_get_prkey(lun, i) == 0)
8052 				continue;
8053 
8054 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8055 				ctl_clr_prkey(lun, i);
8056 				lun->pr_key_count--;
8057 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8058 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8059 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8060 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8061 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8062 			}
8063 		}
8064 		lun->pr_res_type = msg->pr.pr_info.res_type;
8065 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8066 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8067 			lun->pr_res_idx = msg->pr.pr_info.residx;
8068 		else
8069 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8070 	}
8071 	lun->pr_generation++;
8072 
8073 }
8074 
8075 
8076 int
8077 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8078 {
8079 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8080 	struct ctl_lun *lun = CTL_LUN(ctsio);
8081 	int retval;
8082 	u_int32_t param_len;
8083 	struct scsi_per_res_out *cdb;
8084 	struct scsi_per_res_out_parms* param;
8085 	uint32_t residx;
8086 	uint64_t res_key, sa_res_key, key;
8087 	uint8_t type;
8088 	union ctl_ha_msg persis_io;
8089 	int    i;
8090 
8091 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8092 
8093 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8094 	retval = CTL_RETVAL_COMPLETE;
8095 
8096 	/*
8097 	 * We only support whole-LUN scope.  The scope & type are ignored for
8098 	 * register, register and ignore existing key and clear.
8099 	 * We sometimes ignore scope and type on preempts too!!
8100 	 * Verify reservation type here as well.
8101 	 */
8102 	type = cdb->scope_type & SPR_TYPE_MASK;
8103 	if ((cdb->action == SPRO_RESERVE)
8104 	 || (cdb->action == SPRO_RELEASE)) {
8105 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8106 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8107 					      /*sks_valid*/ 1,
8108 					      /*command*/ 1,
8109 					      /*field*/ 2,
8110 					      /*bit_valid*/ 1,
8111 					      /*bit*/ 4);
8112 			ctl_done((union ctl_io *)ctsio);
8113 			return (CTL_RETVAL_COMPLETE);
8114 		}
8115 
8116 		if (type>8 || type==2 || type==4 || type==0) {
8117 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8118 					      /*sks_valid*/ 1,
8119 					      /*command*/ 1,
8120 					      /*field*/ 2,
8121 					      /*bit_valid*/ 1,
8122 					      /*bit*/ 0);
8123 			ctl_done((union ctl_io *)ctsio);
8124 			return (CTL_RETVAL_COMPLETE);
8125 		}
8126 	}
8127 
8128 	param_len = scsi_4btoul(cdb->length);
8129 
8130 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8131 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8132 		ctsio->kern_data_len = param_len;
8133 		ctsio->kern_total_len = param_len;
8134 		ctsio->kern_rel_offset = 0;
8135 		ctsio->kern_sg_entries = 0;
8136 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8137 		ctsio->be_move_done = ctl_config_move_done;
8138 		ctl_datamove((union ctl_io *)ctsio);
8139 
8140 		return (CTL_RETVAL_COMPLETE);
8141 	}
8142 
8143 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8144 
8145 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8146 	res_key = scsi_8btou64(param->res_key.key);
8147 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8148 
8149 	/*
8150 	 * Validate the reservation key here except for SPRO_REG_IGNO
8151 	 * This must be done for all other service actions
8152 	 */
8153 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8154 		mtx_lock(&lun->lun_lock);
8155 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8156 			if (res_key != key) {
8157 				/*
8158 				 * The current key passed in doesn't match
8159 				 * the one the initiator previously
8160 				 * registered.
8161 				 */
8162 				mtx_unlock(&lun->lun_lock);
8163 				free(ctsio->kern_data_ptr, M_CTL);
8164 				ctl_set_reservation_conflict(ctsio);
8165 				ctl_done((union ctl_io *)ctsio);
8166 				return (CTL_RETVAL_COMPLETE);
8167 			}
8168 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8169 			/*
8170 			 * We are not registered
8171 			 */
8172 			mtx_unlock(&lun->lun_lock);
8173 			free(ctsio->kern_data_ptr, M_CTL);
8174 			ctl_set_reservation_conflict(ctsio);
8175 			ctl_done((union ctl_io *)ctsio);
8176 			return (CTL_RETVAL_COMPLETE);
8177 		} else if (res_key != 0) {
8178 			/*
8179 			 * We are not registered and trying to register but
8180 			 * the register key isn't zero.
8181 			 */
8182 			mtx_unlock(&lun->lun_lock);
8183 			free(ctsio->kern_data_ptr, M_CTL);
8184 			ctl_set_reservation_conflict(ctsio);
8185 			ctl_done((union ctl_io *)ctsio);
8186 			return (CTL_RETVAL_COMPLETE);
8187 		}
8188 		mtx_unlock(&lun->lun_lock);
8189 	}
8190 
8191 	switch (cdb->action & SPRO_ACTION_MASK) {
8192 	case SPRO_REGISTER:
8193 	case SPRO_REG_IGNO: {
8194 
8195 		/*
8196 		 * We don't support any of these options, as we report in
8197 		 * the read capabilities request (see
8198 		 * ctl_persistent_reserve_in(), above).
8199 		 */
8200 		if ((param->flags & SPR_SPEC_I_PT)
8201 		 || (param->flags & SPR_ALL_TG_PT)
8202 		 || (param->flags & SPR_APTPL)) {
8203 			int bit_ptr;
8204 
8205 			if (param->flags & SPR_APTPL)
8206 				bit_ptr = 0;
8207 			else if (param->flags & SPR_ALL_TG_PT)
8208 				bit_ptr = 2;
8209 			else /* SPR_SPEC_I_PT */
8210 				bit_ptr = 3;
8211 
8212 			free(ctsio->kern_data_ptr, M_CTL);
8213 			ctl_set_invalid_field(ctsio,
8214 					      /*sks_valid*/ 1,
8215 					      /*command*/ 0,
8216 					      /*field*/ 20,
8217 					      /*bit_valid*/ 1,
8218 					      /*bit*/ bit_ptr);
8219 			ctl_done((union ctl_io *)ctsio);
8220 			return (CTL_RETVAL_COMPLETE);
8221 		}
8222 
8223 		mtx_lock(&lun->lun_lock);
8224 
8225 		/*
8226 		 * The initiator wants to clear the
8227 		 * key/unregister.
8228 		 */
8229 		if (sa_res_key == 0) {
8230 			if ((res_key == 0
8231 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8232 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8233 			  && ctl_get_prkey(lun, residx) == 0)) {
8234 				mtx_unlock(&lun->lun_lock);
8235 				goto done;
8236 			}
8237 
8238 			ctl_clr_prkey(lun, residx);
8239 			lun->pr_key_count--;
8240 
8241 			if (residx == lun->pr_res_idx) {
8242 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8243 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8244 
8245 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8246 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8247 				    lun->pr_key_count) {
8248 					/*
8249 					 * If the reservation is a registrants
8250 					 * only type we need to generate a UA
8251 					 * for other registered inits.  The
8252 					 * sense code should be RESERVATIONS
8253 					 * RELEASED
8254 					 */
8255 
8256 					for (i = softc->init_min; i < softc->init_max; i++){
8257 						if (ctl_get_prkey(lun, i) == 0)
8258 							continue;
8259 						ctl_est_ua(lun, i,
8260 						    CTL_UA_RES_RELEASE);
8261 					}
8262 				}
8263 				lun->pr_res_type = 0;
8264 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8265 				if (lun->pr_key_count==0) {
8266 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8267 					lun->pr_res_type = 0;
8268 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8269 				}
8270 			}
8271 			lun->pr_generation++;
8272 			mtx_unlock(&lun->lun_lock);
8273 
8274 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8275 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8276 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8277 			persis_io.pr.pr_info.residx = residx;
8278 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8279 			    sizeof(persis_io.pr), M_WAITOK);
8280 		} else /* sa_res_key != 0 */ {
8281 
8282 			/*
8283 			 * If we aren't registered currently then increment
8284 			 * the key count and set the registered flag.
8285 			 */
8286 			ctl_alloc_prkey(lun, residx);
8287 			if (ctl_get_prkey(lun, residx) == 0)
8288 				lun->pr_key_count++;
8289 			ctl_set_prkey(lun, residx, sa_res_key);
8290 			lun->pr_generation++;
8291 			mtx_unlock(&lun->lun_lock);
8292 
8293 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8294 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8295 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8296 			persis_io.pr.pr_info.residx = residx;
8297 			memcpy(persis_io.pr.pr_info.sa_res_key,
8298 			       param->serv_act_res_key,
8299 			       sizeof(param->serv_act_res_key));
8300 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8301 			    sizeof(persis_io.pr), M_WAITOK);
8302 		}
8303 
8304 		break;
8305 	}
8306 	case SPRO_RESERVE:
8307 		mtx_lock(&lun->lun_lock);
8308 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8309 			/*
8310 			 * if this isn't the reservation holder and it's
8311 			 * not a "all registrants" type or if the type is
8312 			 * different then we have a conflict
8313 			 */
8314 			if ((lun->pr_res_idx != residx
8315 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8316 			 || lun->pr_res_type != type) {
8317 				mtx_unlock(&lun->lun_lock);
8318 				free(ctsio->kern_data_ptr, M_CTL);
8319 				ctl_set_reservation_conflict(ctsio);
8320 				ctl_done((union ctl_io *)ctsio);
8321 				return (CTL_RETVAL_COMPLETE);
8322 			}
8323 			mtx_unlock(&lun->lun_lock);
8324 		} else /* create a reservation */ {
8325 			/*
8326 			 * If it's not an "all registrants" type record
8327 			 * reservation holder
8328 			 */
8329 			if (type != SPR_TYPE_WR_EX_AR
8330 			 && type != SPR_TYPE_EX_AC_AR)
8331 				lun->pr_res_idx = residx; /* Res holder */
8332 			else
8333 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8334 
8335 			lun->flags |= CTL_LUN_PR_RESERVED;
8336 			lun->pr_res_type = type;
8337 
8338 			mtx_unlock(&lun->lun_lock);
8339 
8340 			/* send msg to other side */
8341 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8342 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8343 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8344 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8345 			persis_io.pr.pr_info.res_type = type;
8346 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8347 			    sizeof(persis_io.pr), M_WAITOK);
8348 		}
8349 		break;
8350 
8351 	case SPRO_RELEASE:
8352 		mtx_lock(&lun->lun_lock);
8353 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8354 			/* No reservation exists return good status */
8355 			mtx_unlock(&lun->lun_lock);
8356 			goto done;
8357 		}
8358 		/*
8359 		 * Is this nexus a reservation holder?
8360 		 */
8361 		if (lun->pr_res_idx != residx
8362 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8363 			/*
8364 			 * not a res holder return good status but
8365 			 * do nothing
8366 			 */
8367 			mtx_unlock(&lun->lun_lock);
8368 			goto done;
8369 		}
8370 
8371 		if (lun->pr_res_type != type) {
8372 			mtx_unlock(&lun->lun_lock);
8373 			free(ctsio->kern_data_ptr, M_CTL);
8374 			ctl_set_illegal_pr_release(ctsio);
8375 			ctl_done((union ctl_io *)ctsio);
8376 			return (CTL_RETVAL_COMPLETE);
8377 		}
8378 
8379 		/* okay to release */
8380 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8381 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8382 		lun->pr_res_type = 0;
8383 
8384 		/*
8385 		 * If this isn't an exclusive access reservation and NUAR
8386 		 * is not set, generate UA for all other registrants.
8387 		 */
8388 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8389 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8390 			for (i = softc->init_min; i < softc->init_max; i++) {
8391 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8392 					continue;
8393 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8394 			}
8395 		}
8396 		mtx_unlock(&lun->lun_lock);
8397 
8398 		/* Send msg to other side */
8399 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8400 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8401 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8402 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8403 		     sizeof(persis_io.pr), M_WAITOK);
8404 		break;
8405 
8406 	case SPRO_CLEAR:
8407 		/* send msg to other side */
8408 
8409 		mtx_lock(&lun->lun_lock);
8410 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8411 		lun->pr_res_type = 0;
8412 		lun->pr_key_count = 0;
8413 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8414 
8415 		ctl_clr_prkey(lun, residx);
8416 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8417 			if (ctl_get_prkey(lun, i) != 0) {
8418 				ctl_clr_prkey(lun, i);
8419 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8420 			}
8421 		lun->pr_generation++;
8422 		mtx_unlock(&lun->lun_lock);
8423 
8424 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8425 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8426 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8427 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8428 		     sizeof(persis_io.pr), M_WAITOK);
8429 		break;
8430 
8431 	case SPRO_PREEMPT:
8432 	case SPRO_PRE_ABO: {
8433 		int nretval;
8434 
8435 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8436 					  residx, ctsio, cdb, param);
8437 		if (nretval != 0)
8438 			return (CTL_RETVAL_COMPLETE);
8439 		break;
8440 	}
8441 	default:
8442 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8443 	}
8444 
8445 done:
8446 	free(ctsio->kern_data_ptr, M_CTL);
8447 	ctl_set_success(ctsio);
8448 	ctl_done((union ctl_io *)ctsio);
8449 
8450 	return (retval);
8451 }
8452 
8453 /*
8454  * This routine is for handling a message from the other SC pertaining to
8455  * persistent reserve out. All the error checking will have been done
8456  * so only perorming the action need be done here to keep the two
8457  * in sync.
8458  */
8459 static void
8460 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8461 {
8462 	struct ctl_softc *softc = CTL_SOFTC(io);
8463 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8464 	struct ctl_lun *lun;
8465 	int i;
8466 	uint32_t residx, targ_lun;
8467 
8468 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8469 	mtx_lock(&softc->ctl_lock);
8470 	if (targ_lun >= ctl_max_luns ||
8471 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8472 		mtx_unlock(&softc->ctl_lock);
8473 		return;
8474 	}
8475 	mtx_lock(&lun->lun_lock);
8476 	mtx_unlock(&softc->ctl_lock);
8477 	if (lun->flags & CTL_LUN_DISABLED) {
8478 		mtx_unlock(&lun->lun_lock);
8479 		return;
8480 	}
8481 	residx = ctl_get_initindex(&msg->hdr.nexus);
8482 	switch(msg->pr.pr_info.action) {
8483 	case CTL_PR_REG_KEY:
8484 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8485 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8486 			lun->pr_key_count++;
8487 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8488 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8489 		lun->pr_generation++;
8490 		break;
8491 
8492 	case CTL_PR_UNREG_KEY:
8493 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8494 		lun->pr_key_count--;
8495 
8496 		/* XXX Need to see if the reservation has been released */
8497 		/* if so do we need to generate UA? */
8498 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8499 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8500 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8501 
8502 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8503 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8504 			    lun->pr_key_count) {
8505 				/*
8506 				 * If the reservation is a registrants
8507 				 * only type we need to generate a UA
8508 				 * for other registered inits.  The
8509 				 * sense code should be RESERVATIONS
8510 				 * RELEASED
8511 				 */
8512 
8513 				for (i = softc->init_min; i < softc->init_max; i++) {
8514 					if (ctl_get_prkey(lun, i) == 0)
8515 						continue;
8516 
8517 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8518 				}
8519 			}
8520 			lun->pr_res_type = 0;
8521 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8522 			if (lun->pr_key_count==0) {
8523 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8524 				lun->pr_res_type = 0;
8525 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8526 			}
8527 		}
8528 		lun->pr_generation++;
8529 		break;
8530 
8531 	case CTL_PR_RESERVE:
8532 		lun->flags |= CTL_LUN_PR_RESERVED;
8533 		lun->pr_res_type = msg->pr.pr_info.res_type;
8534 		lun->pr_res_idx = msg->pr.pr_info.residx;
8535 
8536 		break;
8537 
8538 	case CTL_PR_RELEASE:
8539 		/*
8540 		 * If this isn't an exclusive access reservation and NUAR
8541 		 * is not set, generate UA for all other registrants.
8542 		 */
8543 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8544 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8545 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8546 			for (i = softc->init_min; i < softc->init_max; i++) {
8547 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8548 					continue;
8549 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8550 			}
8551 		}
8552 
8553 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8554 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8555 		lun->pr_res_type = 0;
8556 		break;
8557 
8558 	case CTL_PR_PREEMPT:
8559 		ctl_pro_preempt_other(lun, msg);
8560 		break;
8561 	case CTL_PR_CLEAR:
8562 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8563 		lun->pr_res_type = 0;
8564 		lun->pr_key_count = 0;
8565 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8566 
8567 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8568 			if (ctl_get_prkey(lun, i) == 0)
8569 				continue;
8570 			ctl_clr_prkey(lun, i);
8571 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8572 		}
8573 		lun->pr_generation++;
8574 		break;
8575 	}
8576 
8577 	mtx_unlock(&lun->lun_lock);
8578 }
8579 
8580 int
8581 ctl_read_write(struct ctl_scsiio *ctsio)
8582 {
8583 	struct ctl_lun *lun = CTL_LUN(ctsio);
8584 	struct ctl_lba_len_flags *lbalen;
8585 	uint64_t lba;
8586 	uint32_t num_blocks;
8587 	int flags, retval;
8588 	int isread;
8589 
8590 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8591 
8592 	flags = 0;
8593 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8594 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8595 	switch (ctsio->cdb[0]) {
8596 	case READ_6:
8597 	case WRITE_6: {
8598 		struct scsi_rw_6 *cdb;
8599 
8600 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8601 
8602 		lba = scsi_3btoul(cdb->addr);
8603 		/* only 5 bits are valid in the most significant address byte */
8604 		lba &= 0x1fffff;
8605 		num_blocks = cdb->length;
8606 		/*
8607 		 * This is correct according to SBC-2.
8608 		 */
8609 		if (num_blocks == 0)
8610 			num_blocks = 256;
8611 		break;
8612 	}
8613 	case READ_10:
8614 	case WRITE_10: {
8615 		struct scsi_rw_10 *cdb;
8616 
8617 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8618 		if (cdb->byte2 & SRW10_FUA)
8619 			flags |= CTL_LLF_FUA;
8620 		if (cdb->byte2 & SRW10_DPO)
8621 			flags |= CTL_LLF_DPO;
8622 		lba = scsi_4btoul(cdb->addr);
8623 		num_blocks = scsi_2btoul(cdb->length);
8624 		break;
8625 	}
8626 	case WRITE_VERIFY_10: {
8627 		struct scsi_write_verify_10 *cdb;
8628 
8629 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8630 		flags |= CTL_LLF_FUA;
8631 		if (cdb->byte2 & SWV_DPO)
8632 			flags |= CTL_LLF_DPO;
8633 		lba = scsi_4btoul(cdb->addr);
8634 		num_blocks = scsi_2btoul(cdb->length);
8635 		break;
8636 	}
8637 	case READ_12:
8638 	case WRITE_12: {
8639 		struct scsi_rw_12 *cdb;
8640 
8641 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8642 		if (cdb->byte2 & SRW12_FUA)
8643 			flags |= CTL_LLF_FUA;
8644 		if (cdb->byte2 & SRW12_DPO)
8645 			flags |= CTL_LLF_DPO;
8646 		lba = scsi_4btoul(cdb->addr);
8647 		num_blocks = scsi_4btoul(cdb->length);
8648 		break;
8649 	}
8650 	case WRITE_VERIFY_12: {
8651 		struct scsi_write_verify_12 *cdb;
8652 
8653 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8654 		flags |= CTL_LLF_FUA;
8655 		if (cdb->byte2 & SWV_DPO)
8656 			flags |= CTL_LLF_DPO;
8657 		lba = scsi_4btoul(cdb->addr);
8658 		num_blocks = scsi_4btoul(cdb->length);
8659 		break;
8660 	}
8661 	case READ_16:
8662 	case WRITE_16: {
8663 		struct scsi_rw_16 *cdb;
8664 
8665 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8666 		if (cdb->byte2 & SRW12_FUA)
8667 			flags |= CTL_LLF_FUA;
8668 		if (cdb->byte2 & SRW12_DPO)
8669 			flags |= CTL_LLF_DPO;
8670 		lba = scsi_8btou64(cdb->addr);
8671 		num_blocks = scsi_4btoul(cdb->length);
8672 		break;
8673 	}
8674 	case WRITE_ATOMIC_16: {
8675 		struct scsi_write_atomic_16 *cdb;
8676 
8677 		if (lun->be_lun->atomicblock == 0) {
8678 			ctl_set_invalid_opcode(ctsio);
8679 			ctl_done((union ctl_io *)ctsio);
8680 			return (CTL_RETVAL_COMPLETE);
8681 		}
8682 
8683 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8684 		if (cdb->byte2 & SRW12_FUA)
8685 			flags |= CTL_LLF_FUA;
8686 		if (cdb->byte2 & SRW12_DPO)
8687 			flags |= CTL_LLF_DPO;
8688 		lba = scsi_8btou64(cdb->addr);
8689 		num_blocks = scsi_2btoul(cdb->length);
8690 		if (num_blocks > lun->be_lun->atomicblock) {
8691 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8692 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8693 			    /*bit*/ 0);
8694 			ctl_done((union ctl_io *)ctsio);
8695 			return (CTL_RETVAL_COMPLETE);
8696 		}
8697 		break;
8698 	}
8699 	case WRITE_VERIFY_16: {
8700 		struct scsi_write_verify_16 *cdb;
8701 
8702 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8703 		flags |= CTL_LLF_FUA;
8704 		if (cdb->byte2 & SWV_DPO)
8705 			flags |= CTL_LLF_DPO;
8706 		lba = scsi_8btou64(cdb->addr);
8707 		num_blocks = scsi_4btoul(cdb->length);
8708 		break;
8709 	}
8710 	default:
8711 		/*
8712 		 * We got a command we don't support.  This shouldn't
8713 		 * happen, commands should be filtered out above us.
8714 		 */
8715 		ctl_set_invalid_opcode(ctsio);
8716 		ctl_done((union ctl_io *)ctsio);
8717 
8718 		return (CTL_RETVAL_COMPLETE);
8719 		break; /* NOTREACHED */
8720 	}
8721 
8722 	/*
8723 	 * The first check is to make sure we're in bounds, the second
8724 	 * check is to catch wrap-around problems.  If the lba + num blocks
8725 	 * is less than the lba, then we've wrapped around and the block
8726 	 * range is invalid anyway.
8727 	 */
8728 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8729 	 || ((lba + num_blocks) < lba)) {
8730 		ctl_set_lba_out_of_range(ctsio,
8731 		    MAX(lba, lun->be_lun->maxlba + 1));
8732 		ctl_done((union ctl_io *)ctsio);
8733 		return (CTL_RETVAL_COMPLETE);
8734 	}
8735 
8736 	/*
8737 	 * According to SBC-3, a transfer length of 0 is not an error.
8738 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8739 	 * translates to 256 blocks for those commands.
8740 	 */
8741 	if (num_blocks == 0) {
8742 		ctl_set_success(ctsio);
8743 		ctl_done((union ctl_io *)ctsio);
8744 		return (CTL_RETVAL_COMPLETE);
8745 	}
8746 
8747 	/* Set FUA and/or DPO if caches are disabled. */
8748 	if (isread) {
8749 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8750 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8751 	} else {
8752 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8753 			flags |= CTL_LLF_FUA;
8754 	}
8755 
8756 	lbalen = (struct ctl_lba_len_flags *)
8757 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8758 	lbalen->lba = lba;
8759 	lbalen->len = num_blocks;
8760 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8761 
8762 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8763 	ctsio->kern_rel_offset = 0;
8764 
8765 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8766 
8767 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8768 	return (retval);
8769 }
8770 
8771 static int
8772 ctl_cnw_cont(union ctl_io *io)
8773 {
8774 	struct ctl_lun *lun = CTL_LUN(io);
8775 	struct ctl_scsiio *ctsio;
8776 	struct ctl_lba_len_flags *lbalen;
8777 	int retval;
8778 
8779 	ctsio = &io->scsiio;
8780 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8781 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8782 	lbalen = (struct ctl_lba_len_flags *)
8783 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8784 	lbalen->flags &= ~CTL_LLF_COMPARE;
8785 	lbalen->flags |= CTL_LLF_WRITE;
8786 
8787 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8788 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8789 	return (retval);
8790 }
8791 
8792 int
8793 ctl_cnw(struct ctl_scsiio *ctsio)
8794 {
8795 	struct ctl_lun *lun = CTL_LUN(ctsio);
8796 	struct ctl_lba_len_flags *lbalen;
8797 	uint64_t lba;
8798 	uint32_t num_blocks;
8799 	int flags, retval;
8800 
8801 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8802 
8803 	flags = 0;
8804 	switch (ctsio->cdb[0]) {
8805 	case COMPARE_AND_WRITE: {
8806 		struct scsi_compare_and_write *cdb;
8807 
8808 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8809 		if (cdb->byte2 & SRW10_FUA)
8810 			flags |= CTL_LLF_FUA;
8811 		if (cdb->byte2 & SRW10_DPO)
8812 			flags |= CTL_LLF_DPO;
8813 		lba = scsi_8btou64(cdb->addr);
8814 		num_blocks = cdb->length;
8815 		break;
8816 	}
8817 	default:
8818 		/*
8819 		 * We got a command we don't support.  This shouldn't
8820 		 * happen, commands should be filtered out above us.
8821 		 */
8822 		ctl_set_invalid_opcode(ctsio);
8823 		ctl_done((union ctl_io *)ctsio);
8824 
8825 		return (CTL_RETVAL_COMPLETE);
8826 		break; /* NOTREACHED */
8827 	}
8828 
8829 	/*
8830 	 * The first check is to make sure we're in bounds, the second
8831 	 * check is to catch wrap-around problems.  If the lba + num blocks
8832 	 * is less than the lba, then we've wrapped around and the block
8833 	 * range is invalid anyway.
8834 	 */
8835 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8836 	 || ((lba + num_blocks) < lba)) {
8837 		ctl_set_lba_out_of_range(ctsio,
8838 		    MAX(lba, lun->be_lun->maxlba + 1));
8839 		ctl_done((union ctl_io *)ctsio);
8840 		return (CTL_RETVAL_COMPLETE);
8841 	}
8842 
8843 	/*
8844 	 * According to SBC-3, a transfer length of 0 is not an error.
8845 	 */
8846 	if (num_blocks == 0) {
8847 		ctl_set_success(ctsio);
8848 		ctl_done((union ctl_io *)ctsio);
8849 		return (CTL_RETVAL_COMPLETE);
8850 	}
8851 
8852 	/* Set FUA if write cache is disabled. */
8853 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8854 		flags |= CTL_LLF_FUA;
8855 
8856 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8857 	ctsio->kern_rel_offset = 0;
8858 
8859 	/*
8860 	 * Set the IO_CONT flag, so that if this I/O gets passed to
8861 	 * ctl_data_submit_done(), it'll get passed back to
8862 	 * ctl_ctl_cnw_cont() for further processing.
8863 	 */
8864 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8865 	ctsio->io_cont = ctl_cnw_cont;
8866 
8867 	lbalen = (struct ctl_lba_len_flags *)
8868 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8869 	lbalen->lba = lba;
8870 	lbalen->len = num_blocks;
8871 	lbalen->flags = CTL_LLF_COMPARE | flags;
8872 
8873 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8874 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8875 	return (retval);
8876 }
8877 
8878 int
8879 ctl_verify(struct ctl_scsiio *ctsio)
8880 {
8881 	struct ctl_lun *lun = CTL_LUN(ctsio);
8882 	struct ctl_lba_len_flags *lbalen;
8883 	uint64_t lba;
8884 	uint32_t num_blocks;
8885 	int bytchk, flags;
8886 	int retval;
8887 
8888 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8889 
8890 	bytchk = 0;
8891 	flags = CTL_LLF_FUA;
8892 	switch (ctsio->cdb[0]) {
8893 	case VERIFY_10: {
8894 		struct scsi_verify_10 *cdb;
8895 
8896 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8897 		if (cdb->byte2 & SVFY_BYTCHK)
8898 			bytchk = 1;
8899 		if (cdb->byte2 & SVFY_DPO)
8900 			flags |= CTL_LLF_DPO;
8901 		lba = scsi_4btoul(cdb->addr);
8902 		num_blocks = scsi_2btoul(cdb->length);
8903 		break;
8904 	}
8905 	case VERIFY_12: {
8906 		struct scsi_verify_12 *cdb;
8907 
8908 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8909 		if (cdb->byte2 & SVFY_BYTCHK)
8910 			bytchk = 1;
8911 		if (cdb->byte2 & SVFY_DPO)
8912 			flags |= CTL_LLF_DPO;
8913 		lba = scsi_4btoul(cdb->addr);
8914 		num_blocks = scsi_4btoul(cdb->length);
8915 		break;
8916 	}
8917 	case VERIFY_16: {
8918 		struct scsi_rw_16 *cdb;
8919 
8920 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8921 		if (cdb->byte2 & SVFY_BYTCHK)
8922 			bytchk = 1;
8923 		if (cdb->byte2 & SVFY_DPO)
8924 			flags |= CTL_LLF_DPO;
8925 		lba = scsi_8btou64(cdb->addr);
8926 		num_blocks = scsi_4btoul(cdb->length);
8927 		break;
8928 	}
8929 	default:
8930 		/*
8931 		 * We got a command we don't support.  This shouldn't
8932 		 * happen, commands should be filtered out above us.
8933 		 */
8934 		ctl_set_invalid_opcode(ctsio);
8935 		ctl_done((union ctl_io *)ctsio);
8936 		return (CTL_RETVAL_COMPLETE);
8937 	}
8938 
8939 	/*
8940 	 * The first check is to make sure we're in bounds, the second
8941 	 * check is to catch wrap-around problems.  If the lba + num blocks
8942 	 * is less than the lba, then we've wrapped around and the block
8943 	 * range is invalid anyway.
8944 	 */
8945 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8946 	 || ((lba + num_blocks) < lba)) {
8947 		ctl_set_lba_out_of_range(ctsio,
8948 		    MAX(lba, lun->be_lun->maxlba + 1));
8949 		ctl_done((union ctl_io *)ctsio);
8950 		return (CTL_RETVAL_COMPLETE);
8951 	}
8952 
8953 	/*
8954 	 * According to SBC-3, a transfer length of 0 is not an error.
8955 	 */
8956 	if (num_blocks == 0) {
8957 		ctl_set_success(ctsio);
8958 		ctl_done((union ctl_io *)ctsio);
8959 		return (CTL_RETVAL_COMPLETE);
8960 	}
8961 
8962 	lbalen = (struct ctl_lba_len_flags *)
8963 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8964 	lbalen->lba = lba;
8965 	lbalen->len = num_blocks;
8966 	if (bytchk) {
8967 		lbalen->flags = CTL_LLF_COMPARE | flags;
8968 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8969 	} else {
8970 		lbalen->flags = CTL_LLF_VERIFY | flags;
8971 		ctsio->kern_total_len = 0;
8972 	}
8973 	ctsio->kern_rel_offset = 0;
8974 
8975 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8976 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8977 	return (retval);
8978 }
8979 
8980 int
8981 ctl_report_luns(struct ctl_scsiio *ctsio)
8982 {
8983 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8984 	struct ctl_port *port = CTL_PORT(ctsio);
8985 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
8986 	struct scsi_report_luns *cdb;
8987 	struct scsi_report_luns_data *lun_data;
8988 	int num_filled, num_luns, num_port_luns, retval;
8989 	uint32_t alloc_len, lun_datalen;
8990 	uint32_t initidx, targ_lun_id, lun_id;
8991 
8992 	retval = CTL_RETVAL_COMPLETE;
8993 	cdb = (struct scsi_report_luns *)ctsio->cdb;
8994 
8995 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8996 
8997 	num_luns = 0;
8998 	num_port_luns = port->lun_map ? port->lun_map_size : ctl_max_luns;
8999 	mtx_lock(&softc->ctl_lock);
9000 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9001 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9002 			num_luns++;
9003 	}
9004 	mtx_unlock(&softc->ctl_lock);
9005 
9006 	switch (cdb->select_report) {
9007 	case RPL_REPORT_DEFAULT:
9008 	case RPL_REPORT_ALL:
9009 	case RPL_REPORT_NONSUBSID:
9010 		break;
9011 	case RPL_REPORT_WELLKNOWN:
9012 	case RPL_REPORT_ADMIN:
9013 	case RPL_REPORT_CONGLOM:
9014 		num_luns = 0;
9015 		break;
9016 	default:
9017 		ctl_set_invalid_field(ctsio,
9018 				      /*sks_valid*/ 1,
9019 				      /*command*/ 1,
9020 				      /*field*/ 2,
9021 				      /*bit_valid*/ 0,
9022 				      /*bit*/ 0);
9023 		ctl_done((union ctl_io *)ctsio);
9024 		return (retval);
9025 		break; /* NOTREACHED */
9026 	}
9027 
9028 	alloc_len = scsi_4btoul(cdb->length);
9029 	/*
9030 	 * The initiator has to allocate at least 16 bytes for this request,
9031 	 * so he can at least get the header and the first LUN.  Otherwise
9032 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9033 	 */
9034 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9035 	    sizeof(struct scsi_report_luns_lundata))) {
9036 		ctl_set_invalid_field(ctsio,
9037 				      /*sks_valid*/ 1,
9038 				      /*command*/ 1,
9039 				      /*field*/ 6,
9040 				      /*bit_valid*/ 0,
9041 				      /*bit*/ 0);
9042 		ctl_done((union ctl_io *)ctsio);
9043 		return (retval);
9044 	}
9045 
9046 	lun_datalen = sizeof(*lun_data) +
9047 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9048 
9049 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9050 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9051 	ctsio->kern_sg_entries = 0;
9052 
9053 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9054 
9055 	mtx_lock(&softc->ctl_lock);
9056 	for (targ_lun_id = 0, num_filled = 0;
9057 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9058 	    targ_lun_id++) {
9059 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9060 		if (lun_id == UINT32_MAX)
9061 			continue;
9062 		lun = softc->ctl_luns[lun_id];
9063 		if (lun == NULL)
9064 			continue;
9065 
9066 		be64enc(lun_data->luns[num_filled++].lundata,
9067 		    ctl_encode_lun(targ_lun_id));
9068 
9069 		/*
9070 		 * According to SPC-3, rev 14 section 6.21:
9071 		 *
9072 		 * "The execution of a REPORT LUNS command to any valid and
9073 		 * installed logical unit shall clear the REPORTED LUNS DATA
9074 		 * HAS CHANGED unit attention condition for all logical
9075 		 * units of that target with respect to the requesting
9076 		 * initiator. A valid and installed logical unit is one
9077 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9078 		 * INQUIRY data (see 6.4.2)."
9079 		 *
9080 		 * If request_lun is NULL, the LUN this report luns command
9081 		 * was issued to is either disabled or doesn't exist. In that
9082 		 * case, we shouldn't clear any pending lun change unit
9083 		 * attention.
9084 		 */
9085 		if (request_lun != NULL) {
9086 			mtx_lock(&lun->lun_lock);
9087 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9088 			mtx_unlock(&lun->lun_lock);
9089 		}
9090 	}
9091 	mtx_unlock(&softc->ctl_lock);
9092 
9093 	/*
9094 	 * It's quite possible that we've returned fewer LUNs than we allocated
9095 	 * space for.  Trim it.
9096 	 */
9097 	lun_datalen = sizeof(*lun_data) +
9098 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9099 	ctsio->kern_rel_offset = 0;
9100 	ctsio->kern_sg_entries = 0;
9101 	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9102 	ctsio->kern_total_len = ctsio->kern_data_len;
9103 
9104 	/*
9105 	 * We set this to the actual data length, regardless of how much
9106 	 * space we actually have to return results.  If the user looks at
9107 	 * this value, he'll know whether or not he allocated enough space
9108 	 * and reissue the command if necessary.  We don't support well
9109 	 * known logical units, so if the user asks for that, return none.
9110 	 */
9111 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9112 
9113 	/*
9114 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9115 	 * this request.
9116 	 */
9117 	ctl_set_success(ctsio);
9118 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9119 	ctsio->be_move_done = ctl_config_move_done;
9120 	ctl_datamove((union ctl_io *)ctsio);
9121 	return (retval);
9122 }
9123 
9124 int
9125 ctl_request_sense(struct ctl_scsiio *ctsio)
9126 {
9127 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9128 	struct ctl_lun *lun = CTL_LUN(ctsio);
9129 	struct scsi_request_sense *cdb;
9130 	struct scsi_sense_data *sense_ptr, *ps;
9131 	uint32_t initidx;
9132 	int have_error;
9133 	u_int sense_len = SSD_FULL_SIZE;
9134 	scsi_sense_data_type sense_format;
9135 	ctl_ua_type ua_type;
9136 	uint8_t asc = 0, ascq = 0;
9137 
9138 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9139 
9140 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9141 
9142 	/*
9143 	 * Determine which sense format the user wants.
9144 	 */
9145 	if (cdb->byte2 & SRS_DESC)
9146 		sense_format = SSD_TYPE_DESC;
9147 	else
9148 		sense_format = SSD_TYPE_FIXED;
9149 
9150 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9151 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9152 	ctsio->kern_sg_entries = 0;
9153 	ctsio->kern_rel_offset = 0;
9154 
9155 	/*
9156 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9157 	 * larger than the largest allowed value for the length field in the
9158 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9159 	 */
9160 	ctsio->kern_data_len = cdb->length;
9161 	ctsio->kern_total_len = cdb->length;
9162 
9163 	/*
9164 	 * If we don't have a LUN, we don't have any pending sense.
9165 	 */
9166 	if (lun == NULL ||
9167 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9168 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9169 		/* "Logical unit not supported" */
9170 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9171 		    /*current_error*/ 1,
9172 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9173 		    /*asc*/ 0x25,
9174 		    /*ascq*/ 0x00,
9175 		    SSD_ELEM_NONE);
9176 		goto send;
9177 	}
9178 
9179 	have_error = 0;
9180 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9181 	/*
9182 	 * Check for pending sense, and then for pending unit attentions.
9183 	 * Pending sense gets returned first, then pending unit attentions.
9184 	 */
9185 	mtx_lock(&lun->lun_lock);
9186 	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9187 	if (ps != NULL)
9188 		ps += initidx % CTL_MAX_INIT_PER_PORT;
9189 	if (ps != NULL && ps->error_code != 0) {
9190 		scsi_sense_data_type stored_format;
9191 
9192 		/*
9193 		 * Check to see which sense format was used for the stored
9194 		 * sense data.
9195 		 */
9196 		stored_format = scsi_sense_type(ps);
9197 
9198 		/*
9199 		 * If the user requested a different sense format than the
9200 		 * one we stored, then we need to convert it to the other
9201 		 * format.  If we're going from descriptor to fixed format
9202 		 * sense data, we may lose things in translation, depending
9203 		 * on what options were used.
9204 		 *
9205 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9206 		 * for some reason we'll just copy it out as-is.
9207 		 */
9208 		if ((stored_format == SSD_TYPE_FIXED)
9209 		 && (sense_format == SSD_TYPE_DESC))
9210 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9211 			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9212 		else if ((stored_format == SSD_TYPE_DESC)
9213 		      && (sense_format == SSD_TYPE_FIXED))
9214 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9215 			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9216 		else
9217 			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9218 
9219 		ps->error_code = 0;
9220 		have_error = 1;
9221 	} else {
9222 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9223 		    sense_format);
9224 		if (ua_type != CTL_UA_NONE)
9225 			have_error = 1;
9226 	}
9227 	if (have_error == 0) {
9228 		/*
9229 		 * Report informational exception if have one and allowed.
9230 		 */
9231 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9232 			asc = lun->ie_asc;
9233 			ascq = lun->ie_ascq;
9234 		}
9235 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9236 		    /*current_error*/ 1,
9237 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9238 		    /*asc*/ asc,
9239 		    /*ascq*/ ascq,
9240 		    SSD_ELEM_NONE);
9241 	}
9242 	mtx_unlock(&lun->lun_lock);
9243 
9244 send:
9245 	/*
9246 	 * We report the SCSI status as OK, since the status of the command
9247 	 * itself is OK.  We're reporting sense as parameter data.
9248 	 */
9249 	ctl_set_success(ctsio);
9250 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9251 	ctsio->be_move_done = ctl_config_move_done;
9252 	ctl_datamove((union ctl_io *)ctsio);
9253 	return (CTL_RETVAL_COMPLETE);
9254 }
9255 
9256 int
9257 ctl_tur(struct ctl_scsiio *ctsio)
9258 {
9259 
9260 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9261 
9262 	ctl_set_success(ctsio);
9263 	ctl_done((union ctl_io *)ctsio);
9264 
9265 	return (CTL_RETVAL_COMPLETE);
9266 }
9267 
9268 /*
9269  * SCSI VPD page 0x00, the Supported VPD Pages page.
9270  */
9271 static int
9272 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9273 {
9274 	struct ctl_lun *lun = CTL_LUN(ctsio);
9275 	struct scsi_vpd_supported_pages *pages;
9276 	int sup_page_size;
9277 	int p;
9278 
9279 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9280 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9281 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9282 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9283 	ctsio->kern_rel_offset = 0;
9284 	ctsio->kern_sg_entries = 0;
9285 	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9286 	ctsio->kern_total_len = ctsio->kern_data_len;
9287 
9288 	/*
9289 	 * The control device is always connected.  The disk device, on the
9290 	 * other hand, may not be online all the time.  Need to change this
9291 	 * to figure out whether the disk device is actually online or not.
9292 	 */
9293 	if (lun != NULL)
9294 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9295 				lun->be_lun->lun_type;
9296 	else
9297 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9298 
9299 	p = 0;
9300 	/* Supported VPD pages */
9301 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9302 	/* Serial Number */
9303 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9304 	/* Device Identification */
9305 	pages->page_list[p++] = SVPD_DEVICE_ID;
9306 	/* Extended INQUIRY Data */
9307 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9308 	/* Mode Page Policy */
9309 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9310 	/* SCSI Ports */
9311 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9312 	/* Third-party Copy */
9313 	pages->page_list[p++] = SVPD_SCSI_TPC;
9314 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9315 		/* Block limits */
9316 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9317 		/* Block Device Characteristics */
9318 		pages->page_list[p++] = SVPD_BDC;
9319 		/* Logical Block Provisioning */
9320 		pages->page_list[p++] = SVPD_LBP;
9321 	}
9322 	pages->length = p;
9323 
9324 	ctl_set_success(ctsio);
9325 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9326 	ctsio->be_move_done = ctl_config_move_done;
9327 	ctl_datamove((union ctl_io *)ctsio);
9328 	return (CTL_RETVAL_COMPLETE);
9329 }
9330 
9331 /*
9332  * SCSI VPD page 0x80, the Unit Serial Number page.
9333  */
9334 static int
9335 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9336 {
9337 	struct ctl_lun *lun = CTL_LUN(ctsio);
9338 	struct scsi_vpd_unit_serial_number *sn_ptr;
9339 	int data_len;
9340 
9341 	data_len = 4 + CTL_SN_LEN;
9342 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9343 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9344 	ctsio->kern_rel_offset = 0;
9345 	ctsio->kern_sg_entries = 0;
9346 	ctsio->kern_data_len = min(data_len, alloc_len);
9347 	ctsio->kern_total_len = ctsio->kern_data_len;
9348 
9349 	/*
9350 	 * The control device is always connected.  The disk device, on the
9351 	 * other hand, may not be online all the time.  Need to change this
9352 	 * to figure out whether the disk device is actually online or not.
9353 	 */
9354 	if (lun != NULL)
9355 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9356 				  lun->be_lun->lun_type;
9357 	else
9358 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9359 
9360 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9361 	sn_ptr->length = CTL_SN_LEN;
9362 	/*
9363 	 * If we don't have a LUN, we just leave the serial number as
9364 	 * all spaces.
9365 	 */
9366 	if (lun != NULL) {
9367 		strncpy((char *)sn_ptr->serial_num,
9368 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9369 	} else
9370 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9371 
9372 	ctl_set_success(ctsio);
9373 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9374 	ctsio->be_move_done = ctl_config_move_done;
9375 	ctl_datamove((union ctl_io *)ctsio);
9376 	return (CTL_RETVAL_COMPLETE);
9377 }
9378 
9379 
9380 /*
9381  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9382  */
9383 static int
9384 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9385 {
9386 	struct ctl_lun *lun = CTL_LUN(ctsio);
9387 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9388 	int data_len;
9389 
9390 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9391 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9392 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9393 	ctsio->kern_sg_entries = 0;
9394 	ctsio->kern_rel_offset = 0;
9395 	ctsio->kern_data_len = min(data_len, alloc_len);
9396 	ctsio->kern_total_len = ctsio->kern_data_len;
9397 
9398 	/*
9399 	 * The control device is always connected.  The disk device, on the
9400 	 * other hand, may not be online all the time.
9401 	 */
9402 	if (lun != NULL)
9403 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9404 				     lun->be_lun->lun_type;
9405 	else
9406 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9407 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9408 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9409 	/*
9410 	 * We support head of queue, ordered and simple tags.
9411 	 */
9412 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9413 	/*
9414 	 * Volatile cache supported.
9415 	 */
9416 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9417 
9418 	/*
9419 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9420 	 * attention for a particular IT nexus on all LUNs once we report
9421 	 * it to that nexus once.  This bit is required as of SPC-4.
9422 	 */
9423 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9424 
9425 	/*
9426 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9427 	 */
9428 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9429 
9430 	/*
9431 	 * XXX KDM in order to correctly answer this, we would need
9432 	 * information from the SIM to determine how much sense data it
9433 	 * can send.  So this would really be a path inquiry field, most
9434 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9435 	 * but the hardware may or may not be able to support that much.
9436 	 * 0 just means that the maximum sense data length is not reported.
9437 	 */
9438 	eid_ptr->max_sense_length = 0;
9439 
9440 	ctl_set_success(ctsio);
9441 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9442 	ctsio->be_move_done = ctl_config_move_done;
9443 	ctl_datamove((union ctl_io *)ctsio);
9444 	return (CTL_RETVAL_COMPLETE);
9445 }
9446 
9447 static int
9448 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9449 {
9450 	struct ctl_lun *lun = CTL_LUN(ctsio);
9451 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9452 	int data_len;
9453 
9454 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9455 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9456 
9457 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9458 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9459 	ctsio->kern_rel_offset = 0;
9460 	ctsio->kern_sg_entries = 0;
9461 	ctsio->kern_data_len = min(data_len, alloc_len);
9462 	ctsio->kern_total_len = ctsio->kern_data_len;
9463 
9464 	/*
9465 	 * The control device is always connected.  The disk device, on the
9466 	 * other hand, may not be online all the time.
9467 	 */
9468 	if (lun != NULL)
9469 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9470 				     lun->be_lun->lun_type;
9471 	else
9472 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9473 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9474 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9475 	mpp_ptr->descr[0].page_code = 0x3f;
9476 	mpp_ptr->descr[0].subpage_code = 0xff;
9477 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9478 
9479 	ctl_set_success(ctsio);
9480 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9481 	ctsio->be_move_done = ctl_config_move_done;
9482 	ctl_datamove((union ctl_io *)ctsio);
9483 	return (CTL_RETVAL_COMPLETE);
9484 }
9485 
9486 /*
9487  * SCSI VPD page 0x83, the Device Identification page.
9488  */
9489 static int
9490 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9491 {
9492 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9493 	struct ctl_port *port = CTL_PORT(ctsio);
9494 	struct ctl_lun *lun = CTL_LUN(ctsio);
9495 	struct scsi_vpd_device_id *devid_ptr;
9496 	struct scsi_vpd_id_descriptor *desc;
9497 	int data_len, g;
9498 	uint8_t proto;
9499 
9500 	data_len = sizeof(struct scsi_vpd_device_id) +
9501 	    sizeof(struct scsi_vpd_id_descriptor) +
9502 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9503 	    sizeof(struct scsi_vpd_id_descriptor) +
9504 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9505 	if (lun && lun->lun_devid)
9506 		data_len += lun->lun_devid->len;
9507 	if (port && port->port_devid)
9508 		data_len += port->port_devid->len;
9509 	if (port && port->target_devid)
9510 		data_len += port->target_devid->len;
9511 
9512 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9513 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9514 	ctsio->kern_sg_entries = 0;
9515 	ctsio->kern_rel_offset = 0;
9516 	ctsio->kern_sg_entries = 0;
9517 	ctsio->kern_data_len = min(data_len, alloc_len);
9518 	ctsio->kern_total_len = ctsio->kern_data_len;
9519 
9520 	/*
9521 	 * The control device is always connected.  The disk device, on the
9522 	 * other hand, may not be online all the time.
9523 	 */
9524 	if (lun != NULL)
9525 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9526 				     lun->be_lun->lun_type;
9527 	else
9528 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9529 	devid_ptr->page_code = SVPD_DEVICE_ID;
9530 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9531 
9532 	if (port && port->port_type == CTL_PORT_FC)
9533 		proto = SCSI_PROTO_FC << 4;
9534 	else if (port && port->port_type == CTL_PORT_SAS)
9535 		proto = SCSI_PROTO_SAS << 4;
9536 	else if (port && port->port_type == CTL_PORT_ISCSI)
9537 		proto = SCSI_PROTO_ISCSI << 4;
9538 	else
9539 		proto = SCSI_PROTO_SPI << 4;
9540 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9541 
9542 	/*
9543 	 * We're using a LUN association here.  i.e., this device ID is a
9544 	 * per-LUN identifier.
9545 	 */
9546 	if (lun && lun->lun_devid) {
9547 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9548 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9549 		    lun->lun_devid->len);
9550 	}
9551 
9552 	/*
9553 	 * This is for the WWPN which is a port association.
9554 	 */
9555 	if (port && port->port_devid) {
9556 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9557 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9558 		    port->port_devid->len);
9559 	}
9560 
9561 	/*
9562 	 * This is for the Relative Target Port(type 4h) identifier
9563 	 */
9564 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9565 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9566 	    SVPD_ID_TYPE_RELTARG;
9567 	desc->length = 4;
9568 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9569 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9570 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9571 
9572 	/*
9573 	 * This is for the Target Port Group(type 5h) identifier
9574 	 */
9575 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9576 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9577 	    SVPD_ID_TYPE_TPORTGRP;
9578 	desc->length = 4;
9579 	if (softc->is_single ||
9580 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9581 		g = 1;
9582 	else
9583 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9584 	scsi_ulto2b(g, &desc->identifier[2]);
9585 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9586 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9587 
9588 	/*
9589 	 * This is for the Target identifier
9590 	 */
9591 	if (port && port->target_devid) {
9592 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9593 	}
9594 
9595 	ctl_set_success(ctsio);
9596 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9597 	ctsio->be_move_done = ctl_config_move_done;
9598 	ctl_datamove((union ctl_io *)ctsio);
9599 	return (CTL_RETVAL_COMPLETE);
9600 }
9601 
9602 static int
9603 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9604 {
9605 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9606 	struct ctl_lun *lun = CTL_LUN(ctsio);
9607 	struct scsi_vpd_scsi_ports *sp;
9608 	struct scsi_vpd_port_designation *pd;
9609 	struct scsi_vpd_port_designation_cont *pdc;
9610 	struct ctl_port *port;
9611 	int data_len, num_target_ports, iid_len, id_len;
9612 
9613 	num_target_ports = 0;
9614 	iid_len = 0;
9615 	id_len = 0;
9616 	mtx_lock(&softc->ctl_lock);
9617 	STAILQ_FOREACH(port, &softc->port_list, links) {
9618 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9619 			continue;
9620 		if (lun != NULL &&
9621 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9622 			continue;
9623 		num_target_ports++;
9624 		if (port->init_devid)
9625 			iid_len += port->init_devid->len;
9626 		if (port->port_devid)
9627 			id_len += port->port_devid->len;
9628 	}
9629 	mtx_unlock(&softc->ctl_lock);
9630 
9631 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9632 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9633 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9634 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9635 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9636 	ctsio->kern_sg_entries = 0;
9637 	ctsio->kern_rel_offset = 0;
9638 	ctsio->kern_sg_entries = 0;
9639 	ctsio->kern_data_len = min(data_len, alloc_len);
9640 	ctsio->kern_total_len = ctsio->kern_data_len;
9641 
9642 	/*
9643 	 * The control device is always connected.  The disk device, on the
9644 	 * other hand, may not be online all the time.  Need to change this
9645 	 * to figure out whether the disk device is actually online or not.
9646 	 */
9647 	if (lun != NULL)
9648 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9649 				  lun->be_lun->lun_type;
9650 	else
9651 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9652 
9653 	sp->page_code = SVPD_SCSI_PORTS;
9654 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9655 	    sp->page_length);
9656 	pd = &sp->design[0];
9657 
9658 	mtx_lock(&softc->ctl_lock);
9659 	STAILQ_FOREACH(port, &softc->port_list, links) {
9660 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9661 			continue;
9662 		if (lun != NULL &&
9663 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9664 			continue;
9665 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9666 		if (port->init_devid) {
9667 			iid_len = port->init_devid->len;
9668 			memcpy(pd->initiator_transportid,
9669 			    port->init_devid->data, port->init_devid->len);
9670 		} else
9671 			iid_len = 0;
9672 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9673 		pdc = (struct scsi_vpd_port_designation_cont *)
9674 		    (&pd->initiator_transportid[iid_len]);
9675 		if (port->port_devid) {
9676 			id_len = port->port_devid->len;
9677 			memcpy(pdc->target_port_descriptors,
9678 			    port->port_devid->data, port->port_devid->len);
9679 		} else
9680 			id_len = 0;
9681 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9682 		pd = (struct scsi_vpd_port_designation *)
9683 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9684 	}
9685 	mtx_unlock(&softc->ctl_lock);
9686 
9687 	ctl_set_success(ctsio);
9688 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9689 	ctsio->be_move_done = ctl_config_move_done;
9690 	ctl_datamove((union ctl_io *)ctsio);
9691 	return (CTL_RETVAL_COMPLETE);
9692 }
9693 
9694 static int
9695 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9696 {
9697 	struct ctl_lun *lun = CTL_LUN(ctsio);
9698 	struct scsi_vpd_block_limits *bl_ptr;
9699 	const char *val;
9700 	uint64_t ival;
9701 
9702 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9703 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9704 	ctsio->kern_sg_entries = 0;
9705 	ctsio->kern_rel_offset = 0;
9706 	ctsio->kern_sg_entries = 0;
9707 	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9708 	ctsio->kern_total_len = ctsio->kern_data_len;
9709 
9710 	/*
9711 	 * The control device is always connected.  The disk device, on the
9712 	 * other hand, may not be online all the time.  Need to change this
9713 	 * to figure out whether the disk device is actually online or not.
9714 	 */
9715 	if (lun != NULL)
9716 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9717 				  lun->be_lun->lun_type;
9718 	else
9719 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9720 
9721 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9722 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9723 	bl_ptr->max_cmp_write_len = 0xff;
9724 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9725 	if (lun != NULL) {
9726 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9727 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9728 			ival = 0xffffffff;
9729 			val = dnvlist_get_string(lun->be_lun->options,
9730 			    "unmap_max_lba", NULL);
9731 			if (val != NULL)
9732 				ctl_expand_number(val, &ival);
9733 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9734 			ival = 0xffffffff;
9735 			val = dnvlist_get_string(lun->be_lun->options,
9736 			    "unmap_max_descr", NULL);
9737 			if (val != NULL)
9738 				ctl_expand_number(val, &ival);
9739 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9740 			if (lun->be_lun->ublockexp != 0) {
9741 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9742 				    bl_ptr->opt_unmap_grain);
9743 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9744 				    bl_ptr->unmap_grain_align);
9745 			}
9746 		}
9747 		scsi_ulto4b(lun->be_lun->atomicblock,
9748 		    bl_ptr->max_atomic_transfer_length);
9749 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9750 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9751 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9752 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9753 		ival = UINT64_MAX;
9754 		val = dnvlist_get_string(lun->be_lun->options,
9755 		    "write_same_max_lba", NULL);
9756 		if (val != NULL)
9757 			ctl_expand_number(val, &ival);
9758 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9759 	}
9760 
9761 	ctl_set_success(ctsio);
9762 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9763 	ctsio->be_move_done = ctl_config_move_done;
9764 	ctl_datamove((union ctl_io *)ctsio);
9765 	return (CTL_RETVAL_COMPLETE);
9766 }
9767 
9768 static int
9769 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9770 {
9771 	struct ctl_lun *lun = CTL_LUN(ctsio);
9772 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9773 	const char *value;
9774 	u_int i;
9775 
9776 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9777 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9778 	ctsio->kern_sg_entries = 0;
9779 	ctsio->kern_rel_offset = 0;
9780 	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
9781 	ctsio->kern_total_len = ctsio->kern_data_len;
9782 
9783 	/*
9784 	 * The control device is always connected.  The disk device, on the
9785 	 * other hand, may not be online all the time.  Need to change this
9786 	 * to figure out whether the disk device is actually online or not.
9787 	 */
9788 	if (lun != NULL)
9789 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9790 				  lun->be_lun->lun_type;
9791 	else
9792 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9793 	bdc_ptr->page_code = SVPD_BDC;
9794 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9795 	if (lun != NULL &&
9796 	    (value = dnvlist_get_string(lun->be_lun->options, "rpm", NULL)) != NULL)
9797 		i = strtol(value, NULL, 0);
9798 	else
9799 		i = CTL_DEFAULT_ROTATION_RATE;
9800 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9801 	if (lun != NULL &&
9802 	    (value = dnvlist_get_string(lun->be_lun->options, "formfactor", NULL)) != NULL)
9803 		i = strtol(value, NULL, 0);
9804 	else
9805 		i = 0;
9806 	bdc_ptr->wab_wac_ff = (i & 0x0f);
9807 	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9808 
9809 	ctl_set_success(ctsio);
9810 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9811 	ctsio->be_move_done = ctl_config_move_done;
9812 	ctl_datamove((union ctl_io *)ctsio);
9813 	return (CTL_RETVAL_COMPLETE);
9814 }
9815 
9816 static int
9817 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9818 {
9819 	struct ctl_lun *lun = CTL_LUN(ctsio);
9820 	struct scsi_vpd_logical_block_prov *lbp_ptr;
9821 	const char *value;
9822 
9823 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9824 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9825 	ctsio->kern_sg_entries = 0;
9826 	ctsio->kern_rel_offset = 0;
9827 	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
9828 	ctsio->kern_total_len = ctsio->kern_data_len;
9829 
9830 	/*
9831 	 * The control device is always connected.  The disk device, on the
9832 	 * other hand, may not be online all the time.  Need to change this
9833 	 * to figure out whether the disk device is actually online or not.
9834 	 */
9835 	if (lun != NULL)
9836 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9837 				  lun->be_lun->lun_type;
9838 	else
9839 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9840 
9841 	lbp_ptr->page_code = SVPD_LBP;
9842 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9843 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9844 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9845 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9846 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9847 		value = dnvlist_get_string(lun->be_lun->options,
9848 		    "provisioning_type", NULL);
9849 		if (value != NULL) {
9850 			if (strcmp(value, "resource") == 0)
9851 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
9852 			else if (strcmp(value, "thin") == 0)
9853 				lbp_ptr->prov_type = SVPD_LBP_THIN;
9854 		} else
9855 			lbp_ptr->prov_type = SVPD_LBP_THIN;
9856 	}
9857 
9858 	ctl_set_success(ctsio);
9859 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9860 	ctsio->be_move_done = ctl_config_move_done;
9861 	ctl_datamove((union ctl_io *)ctsio);
9862 	return (CTL_RETVAL_COMPLETE);
9863 }
9864 
9865 /*
9866  * INQUIRY with the EVPD bit set.
9867  */
9868 static int
9869 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9870 {
9871 	struct ctl_lun *lun = CTL_LUN(ctsio);
9872 	struct scsi_inquiry *cdb;
9873 	int alloc_len, retval;
9874 
9875 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9876 	alloc_len = scsi_2btoul(cdb->length);
9877 
9878 	switch (cdb->page_code) {
9879 	case SVPD_SUPPORTED_PAGES:
9880 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9881 		break;
9882 	case SVPD_UNIT_SERIAL_NUMBER:
9883 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9884 		break;
9885 	case SVPD_DEVICE_ID:
9886 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9887 		break;
9888 	case SVPD_EXTENDED_INQUIRY_DATA:
9889 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9890 		break;
9891 	case SVPD_MODE_PAGE_POLICY:
9892 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9893 		break;
9894 	case SVPD_SCSI_PORTS:
9895 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9896 		break;
9897 	case SVPD_SCSI_TPC:
9898 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
9899 		break;
9900 	case SVPD_BLOCK_LIMITS:
9901 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9902 			goto err;
9903 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9904 		break;
9905 	case SVPD_BDC:
9906 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9907 			goto err;
9908 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
9909 		break;
9910 	case SVPD_LBP:
9911 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9912 			goto err;
9913 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
9914 		break;
9915 	default:
9916 err:
9917 		ctl_set_invalid_field(ctsio,
9918 				      /*sks_valid*/ 1,
9919 				      /*command*/ 1,
9920 				      /*field*/ 2,
9921 				      /*bit_valid*/ 0,
9922 				      /*bit*/ 0);
9923 		ctl_done((union ctl_io *)ctsio);
9924 		retval = CTL_RETVAL_COMPLETE;
9925 		break;
9926 	}
9927 
9928 	return (retval);
9929 }
9930 
9931 /*
9932  * Standard INQUIRY data.
9933  */
9934 static int
9935 ctl_inquiry_std(struct ctl_scsiio *ctsio)
9936 {
9937 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9938 	struct ctl_port *port = CTL_PORT(ctsio);
9939 	struct ctl_lun *lun = CTL_LUN(ctsio);
9940 	struct scsi_inquiry_data *inq_ptr;
9941 	struct scsi_inquiry *cdb;
9942 	const char *val;
9943 	uint32_t alloc_len, data_len;
9944 	ctl_port_type port_type;
9945 
9946 	port_type = port->port_type;
9947 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
9948 		port_type = CTL_PORT_SCSI;
9949 
9950 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9951 	alloc_len = scsi_2btoul(cdb->length);
9952 
9953 	/*
9954 	 * We malloc the full inquiry data size here and fill it
9955 	 * in.  If the user only asks for less, we'll give him
9956 	 * that much.
9957 	 */
9958 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
9959 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9960 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
9961 	ctsio->kern_sg_entries = 0;
9962 	ctsio->kern_rel_offset = 0;
9963 	ctsio->kern_data_len = min(data_len, alloc_len);
9964 	ctsio->kern_total_len = ctsio->kern_data_len;
9965 
9966 	if (lun != NULL) {
9967 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
9968 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
9969 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9970 			    lun->be_lun->lun_type;
9971 		} else {
9972 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
9973 			    lun->be_lun->lun_type;
9974 		}
9975 		if (lun->flags & CTL_LUN_REMOVABLE)
9976 			inq_ptr->dev_qual2 |= SID_RMB;
9977 	} else
9978 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
9979 
9980 	/* RMB in byte 2 is 0 */
9981 	inq_ptr->version = SCSI_REV_SPC5;
9982 
9983 	/*
9984 	 * According to SAM-3, even if a device only supports a single
9985 	 * level of LUN addressing, it should still set the HISUP bit:
9986 	 *
9987 	 * 4.9.1 Logical unit numbers overview
9988 	 *
9989 	 * All logical unit number formats described in this standard are
9990 	 * hierarchical in structure even when only a single level in that
9991 	 * hierarchy is used. The HISUP bit shall be set to one in the
9992 	 * standard INQUIRY data (see SPC-2) when any logical unit number
9993 	 * format described in this standard is used.  Non-hierarchical
9994 	 * formats are outside the scope of this standard.
9995 	 *
9996 	 * Therefore we set the HiSup bit here.
9997 	 *
9998 	 * The response format is 2, per SPC-3.
9999 	 */
10000 	inq_ptr->response_format = SID_HiSup | 2;
10001 
10002 	inq_ptr->additional_length = data_len -
10003 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10004 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10005 			 inq_ptr->additional_length));
10006 
10007 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10008 	if (port_type == CTL_PORT_SCSI)
10009 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10010 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10011 	inq_ptr->flags = SID_CmdQue;
10012 	if (port_type == CTL_PORT_SCSI)
10013 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10014 
10015 	/*
10016 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10017 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10018 	 * name and 4 bytes for the revision.
10019 	 */
10020 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10021 	    "vendor", NULL)) == NULL) {
10022 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10023 	} else {
10024 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10025 		strncpy(inq_ptr->vendor, val,
10026 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10027 	}
10028 	if (lun == NULL) {
10029 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10030 		    sizeof(inq_ptr->product));
10031 	} else if ((val = dnvlist_get_string(lun->be_lun->options, "product",
10032 	    NULL)) == NULL) {
10033 		switch (lun->be_lun->lun_type) {
10034 		case T_DIRECT:
10035 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10036 			    sizeof(inq_ptr->product));
10037 			break;
10038 		case T_PROCESSOR:
10039 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10040 			    sizeof(inq_ptr->product));
10041 			break;
10042 		case T_CDROM:
10043 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10044 			    sizeof(inq_ptr->product));
10045 			break;
10046 		default:
10047 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10048 			    sizeof(inq_ptr->product));
10049 			break;
10050 		}
10051 	} else {
10052 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10053 		strncpy(inq_ptr->product, val,
10054 		    min(sizeof(inq_ptr->product), strlen(val)));
10055 	}
10056 
10057 	/*
10058 	 * XXX make this a macro somewhere so it automatically gets
10059 	 * incremented when we make changes.
10060 	 */
10061 	if (lun == NULL || (val = dnvlist_get_string(lun->be_lun->options,
10062 	    "revision", NULL)) == NULL) {
10063 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10064 	} else {
10065 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10066 		strncpy(inq_ptr->revision, val,
10067 		    min(sizeof(inq_ptr->revision), strlen(val)));
10068 	}
10069 
10070 	/*
10071 	 * For parallel SCSI, we support double transition and single
10072 	 * transition clocking.  We also support QAS (Quick Arbitration
10073 	 * and Selection) and Information Unit transfers on both the
10074 	 * control and array devices.
10075 	 */
10076 	if (port_type == CTL_PORT_SCSI)
10077 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10078 				    SID_SPI_IUS;
10079 
10080 	/* SAM-6 (no version claimed) */
10081 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10082 	/* SPC-5 (no version claimed) */
10083 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10084 	if (port_type == CTL_PORT_FC) {
10085 		/* FCP-2 ANSI INCITS.350:2003 */
10086 		scsi_ulto2b(0x0917, inq_ptr->version3);
10087 	} else if (port_type == CTL_PORT_SCSI) {
10088 		/* SPI-4 ANSI INCITS.362:200x */
10089 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10090 	} else if (port_type == CTL_PORT_ISCSI) {
10091 		/* iSCSI (no version claimed) */
10092 		scsi_ulto2b(0x0960, inq_ptr->version3);
10093 	} else if (port_type == CTL_PORT_SAS) {
10094 		/* SAS (no version claimed) */
10095 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10096 	} else if (port_type == CTL_PORT_UMASS) {
10097 		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10098 		scsi_ulto2b(0x1730, inq_ptr->version3);
10099 	}
10100 
10101 	if (lun == NULL) {
10102 		/* SBC-4 (no version claimed) */
10103 		scsi_ulto2b(0x0600, inq_ptr->version4);
10104 	} else {
10105 		switch (lun->be_lun->lun_type) {
10106 		case T_DIRECT:
10107 			/* SBC-4 (no version claimed) */
10108 			scsi_ulto2b(0x0600, inq_ptr->version4);
10109 			break;
10110 		case T_PROCESSOR:
10111 			break;
10112 		case T_CDROM:
10113 			/* MMC-6 (no version claimed) */
10114 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10115 			break;
10116 		default:
10117 			break;
10118 		}
10119 	}
10120 
10121 	ctl_set_success(ctsio);
10122 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10123 	ctsio->be_move_done = ctl_config_move_done;
10124 	ctl_datamove((union ctl_io *)ctsio);
10125 	return (CTL_RETVAL_COMPLETE);
10126 }
10127 
10128 int
10129 ctl_inquiry(struct ctl_scsiio *ctsio)
10130 {
10131 	struct scsi_inquiry *cdb;
10132 	int retval;
10133 
10134 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10135 
10136 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10137 	if (cdb->byte2 & SI_EVPD)
10138 		retval = ctl_inquiry_evpd(ctsio);
10139 	else if (cdb->page_code == 0)
10140 		retval = ctl_inquiry_std(ctsio);
10141 	else {
10142 		ctl_set_invalid_field(ctsio,
10143 				      /*sks_valid*/ 1,
10144 				      /*command*/ 1,
10145 				      /*field*/ 2,
10146 				      /*bit_valid*/ 0,
10147 				      /*bit*/ 0);
10148 		ctl_done((union ctl_io *)ctsio);
10149 		return (CTL_RETVAL_COMPLETE);
10150 	}
10151 
10152 	return (retval);
10153 }
10154 
10155 int
10156 ctl_get_config(struct ctl_scsiio *ctsio)
10157 {
10158 	struct ctl_lun *lun = CTL_LUN(ctsio);
10159 	struct scsi_get_config_header *hdr;
10160 	struct scsi_get_config_feature *feature;
10161 	struct scsi_get_config *cdb;
10162 	uint32_t alloc_len, data_len;
10163 	int rt, starting;
10164 
10165 	cdb = (struct scsi_get_config *)ctsio->cdb;
10166 	rt = (cdb->rt & SGC_RT_MASK);
10167 	starting = scsi_2btoul(cdb->starting_feature);
10168 	alloc_len = scsi_2btoul(cdb->length);
10169 
10170 	data_len = sizeof(struct scsi_get_config_header) +
10171 	    sizeof(struct scsi_get_config_feature) + 8 +
10172 	    sizeof(struct scsi_get_config_feature) + 8 +
10173 	    sizeof(struct scsi_get_config_feature) + 4 +
10174 	    sizeof(struct scsi_get_config_feature) + 4 +
10175 	    sizeof(struct scsi_get_config_feature) + 8 +
10176 	    sizeof(struct scsi_get_config_feature) +
10177 	    sizeof(struct scsi_get_config_feature) + 4 +
10178 	    sizeof(struct scsi_get_config_feature) + 4 +
10179 	    sizeof(struct scsi_get_config_feature) + 4 +
10180 	    sizeof(struct scsi_get_config_feature) + 4 +
10181 	    sizeof(struct scsi_get_config_feature) + 4 +
10182 	    sizeof(struct scsi_get_config_feature) + 4;
10183 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10184 	ctsio->kern_sg_entries = 0;
10185 	ctsio->kern_rel_offset = 0;
10186 
10187 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10188 	if (lun->flags & CTL_LUN_NO_MEDIA)
10189 		scsi_ulto2b(0x0000, hdr->current_profile);
10190 	else
10191 		scsi_ulto2b(0x0010, hdr->current_profile);
10192 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10193 
10194 	if (starting > 0x003b)
10195 		goto done;
10196 	if (starting > 0x003a)
10197 		goto f3b;
10198 	if (starting > 0x002b)
10199 		goto f3a;
10200 	if (starting > 0x002a)
10201 		goto f2b;
10202 	if (starting > 0x001f)
10203 		goto f2a;
10204 	if (starting > 0x001e)
10205 		goto f1f;
10206 	if (starting > 0x001d)
10207 		goto f1e;
10208 	if (starting > 0x0010)
10209 		goto f1d;
10210 	if (starting > 0x0003)
10211 		goto f10;
10212 	if (starting > 0x0002)
10213 		goto f3;
10214 	if (starting > 0x0001)
10215 		goto f2;
10216 	if (starting > 0x0000)
10217 		goto f1;
10218 
10219 	/* Profile List */
10220 	scsi_ulto2b(0x0000, feature->feature_code);
10221 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10222 	feature->add_length = 8;
10223 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10224 	feature->feature_data[2] = 0x00;
10225 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10226 	feature->feature_data[6] = 0x01;
10227 	feature = (struct scsi_get_config_feature *)
10228 	    &feature->feature_data[feature->add_length];
10229 
10230 f1:	/* Core */
10231 	scsi_ulto2b(0x0001, feature->feature_code);
10232 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10233 	feature->add_length = 8;
10234 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10235 	feature->feature_data[4] = 0x03;
10236 	feature = (struct scsi_get_config_feature *)
10237 	    &feature->feature_data[feature->add_length];
10238 
10239 f2:	/* Morphing */
10240 	scsi_ulto2b(0x0002, feature->feature_code);
10241 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10242 	feature->add_length = 4;
10243 	feature->feature_data[0] = 0x02;
10244 	feature = (struct scsi_get_config_feature *)
10245 	    &feature->feature_data[feature->add_length];
10246 
10247 f3:	/* Removable Medium */
10248 	scsi_ulto2b(0x0003, feature->feature_code);
10249 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10250 	feature->add_length = 4;
10251 	feature->feature_data[0] = 0x39;
10252 	feature = (struct scsi_get_config_feature *)
10253 	    &feature->feature_data[feature->add_length];
10254 
10255 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10256 		goto done;
10257 
10258 f10:	/* Random Read */
10259 	scsi_ulto2b(0x0010, feature->feature_code);
10260 	feature->flags = 0x00;
10261 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10262 		feature->flags |= SGC_F_CURRENT;
10263 	feature->add_length = 8;
10264 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10265 	scsi_ulto2b(1, &feature->feature_data[4]);
10266 	feature->feature_data[6] = 0x00;
10267 	feature = (struct scsi_get_config_feature *)
10268 	    &feature->feature_data[feature->add_length];
10269 
10270 f1d:	/* Multi-Read */
10271 	scsi_ulto2b(0x001D, feature->feature_code);
10272 	feature->flags = 0x00;
10273 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10274 		feature->flags |= SGC_F_CURRENT;
10275 	feature->add_length = 0;
10276 	feature = (struct scsi_get_config_feature *)
10277 	    &feature->feature_data[feature->add_length];
10278 
10279 f1e:	/* CD Read */
10280 	scsi_ulto2b(0x001E, feature->feature_code);
10281 	feature->flags = 0x00;
10282 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10283 		feature->flags |= SGC_F_CURRENT;
10284 	feature->add_length = 4;
10285 	feature->feature_data[0] = 0x00;
10286 	feature = (struct scsi_get_config_feature *)
10287 	    &feature->feature_data[feature->add_length];
10288 
10289 f1f:	/* DVD Read */
10290 	scsi_ulto2b(0x001F, feature->feature_code);
10291 	feature->flags = 0x08;
10292 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10293 		feature->flags |= SGC_F_CURRENT;
10294 	feature->add_length = 4;
10295 	feature->feature_data[0] = 0x01;
10296 	feature->feature_data[2] = 0x03;
10297 	feature = (struct scsi_get_config_feature *)
10298 	    &feature->feature_data[feature->add_length];
10299 
10300 f2a:	/* DVD+RW */
10301 	scsi_ulto2b(0x002A, feature->feature_code);
10302 	feature->flags = 0x04;
10303 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10304 		feature->flags |= SGC_F_CURRENT;
10305 	feature->add_length = 4;
10306 	feature->feature_data[0] = 0x00;
10307 	feature->feature_data[1] = 0x00;
10308 	feature = (struct scsi_get_config_feature *)
10309 	    &feature->feature_data[feature->add_length];
10310 
10311 f2b:	/* DVD+R */
10312 	scsi_ulto2b(0x002B, feature->feature_code);
10313 	feature->flags = 0x00;
10314 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10315 		feature->flags |= SGC_F_CURRENT;
10316 	feature->add_length = 4;
10317 	feature->feature_data[0] = 0x00;
10318 	feature = (struct scsi_get_config_feature *)
10319 	    &feature->feature_data[feature->add_length];
10320 
10321 f3a:	/* DVD+RW Dual Layer */
10322 	scsi_ulto2b(0x003A, feature->feature_code);
10323 	feature->flags = 0x00;
10324 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10325 		feature->flags |= SGC_F_CURRENT;
10326 	feature->add_length = 4;
10327 	feature->feature_data[0] = 0x00;
10328 	feature->feature_data[1] = 0x00;
10329 	feature = (struct scsi_get_config_feature *)
10330 	    &feature->feature_data[feature->add_length];
10331 
10332 f3b:	/* DVD+R Dual Layer */
10333 	scsi_ulto2b(0x003B, feature->feature_code);
10334 	feature->flags = 0x00;
10335 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10336 		feature->flags |= SGC_F_CURRENT;
10337 	feature->add_length = 4;
10338 	feature->feature_data[0] = 0x00;
10339 	feature = (struct scsi_get_config_feature *)
10340 	    &feature->feature_data[feature->add_length];
10341 
10342 done:
10343 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10344 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10345 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10346 		if (scsi_2btoul(feature->feature_code) == starting)
10347 			feature = (struct scsi_get_config_feature *)
10348 			    &feature->feature_data[feature->add_length];
10349 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10350 	}
10351 	scsi_ulto4b(data_len - 4, hdr->data_length);
10352 	ctsio->kern_data_len = min(data_len, alloc_len);
10353 	ctsio->kern_total_len = ctsio->kern_data_len;
10354 
10355 	ctl_set_success(ctsio);
10356 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10357 	ctsio->be_move_done = ctl_config_move_done;
10358 	ctl_datamove((union ctl_io *)ctsio);
10359 	return (CTL_RETVAL_COMPLETE);
10360 }
10361 
10362 int
10363 ctl_get_event_status(struct ctl_scsiio *ctsio)
10364 {
10365 	struct scsi_get_event_status_header *hdr;
10366 	struct scsi_get_event_status *cdb;
10367 	uint32_t alloc_len, data_len;
10368 
10369 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10370 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10371 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10372 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10373 		ctl_done((union ctl_io *)ctsio);
10374 		return (CTL_RETVAL_COMPLETE);
10375 	}
10376 	alloc_len = scsi_2btoul(cdb->length);
10377 
10378 	data_len = sizeof(struct scsi_get_event_status_header);
10379 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10380 	ctsio->kern_sg_entries = 0;
10381 	ctsio->kern_rel_offset = 0;
10382 	ctsio->kern_data_len = min(data_len, alloc_len);
10383 	ctsio->kern_total_len = ctsio->kern_data_len;
10384 
10385 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10386 	scsi_ulto2b(0, hdr->descr_length);
10387 	hdr->nea_class = SGESN_NEA;
10388 	hdr->supported_class = 0;
10389 
10390 	ctl_set_success(ctsio);
10391 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10392 	ctsio->be_move_done = ctl_config_move_done;
10393 	ctl_datamove((union ctl_io *)ctsio);
10394 	return (CTL_RETVAL_COMPLETE);
10395 }
10396 
10397 int
10398 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10399 {
10400 	struct scsi_mechanism_status_header *hdr;
10401 	struct scsi_mechanism_status *cdb;
10402 	uint32_t alloc_len, data_len;
10403 
10404 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10405 	alloc_len = scsi_2btoul(cdb->length);
10406 
10407 	data_len = sizeof(struct scsi_mechanism_status_header);
10408 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10409 	ctsio->kern_sg_entries = 0;
10410 	ctsio->kern_rel_offset = 0;
10411 	ctsio->kern_data_len = min(data_len, alloc_len);
10412 	ctsio->kern_total_len = ctsio->kern_data_len;
10413 
10414 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10415 	hdr->state1 = 0x00;
10416 	hdr->state2 = 0xe0;
10417 	scsi_ulto3b(0, hdr->lba);
10418 	hdr->slots_num = 0;
10419 	scsi_ulto2b(0, hdr->slots_length);
10420 
10421 	ctl_set_success(ctsio);
10422 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10423 	ctsio->be_move_done = ctl_config_move_done;
10424 	ctl_datamove((union ctl_io *)ctsio);
10425 	return (CTL_RETVAL_COMPLETE);
10426 }
10427 
10428 static void
10429 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10430 {
10431 
10432 	lba += 150;
10433 	buf[0] = 0;
10434 	buf[1] = bin2bcd((lba / 75) / 60);
10435 	buf[2] = bin2bcd((lba / 75) % 60);
10436 	buf[3] = bin2bcd(lba % 75);
10437 }
10438 
10439 int
10440 ctl_read_toc(struct ctl_scsiio *ctsio)
10441 {
10442 	struct ctl_lun *lun = CTL_LUN(ctsio);
10443 	struct scsi_read_toc_hdr *hdr;
10444 	struct scsi_read_toc_type01_descr *descr;
10445 	struct scsi_read_toc *cdb;
10446 	uint32_t alloc_len, data_len;
10447 	int format, msf;
10448 
10449 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10450 	msf = (cdb->byte2 & CD_MSF) != 0;
10451 	format = cdb->format;
10452 	alloc_len = scsi_2btoul(cdb->data_len);
10453 
10454 	data_len = sizeof(struct scsi_read_toc_hdr);
10455 	if (format == 0)
10456 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10457 	else
10458 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10459 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10460 	ctsio->kern_sg_entries = 0;
10461 	ctsio->kern_rel_offset = 0;
10462 	ctsio->kern_data_len = min(data_len, alloc_len);
10463 	ctsio->kern_total_len = ctsio->kern_data_len;
10464 
10465 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10466 	if (format == 0) {
10467 		scsi_ulto2b(0x12, hdr->data_length);
10468 		hdr->first = 1;
10469 		hdr->last = 1;
10470 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10471 		descr->addr_ctl = 0x14;
10472 		descr->track_number = 1;
10473 		if (msf)
10474 			ctl_ultomsf(0, descr->track_start);
10475 		else
10476 			scsi_ulto4b(0, descr->track_start);
10477 		descr++;
10478 		descr->addr_ctl = 0x14;
10479 		descr->track_number = 0xaa;
10480 		if (msf)
10481 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10482 		else
10483 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10484 	} else {
10485 		scsi_ulto2b(0x0a, hdr->data_length);
10486 		hdr->first = 1;
10487 		hdr->last = 1;
10488 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10489 		descr->addr_ctl = 0x14;
10490 		descr->track_number = 1;
10491 		if (msf)
10492 			ctl_ultomsf(0, descr->track_start);
10493 		else
10494 			scsi_ulto4b(0, descr->track_start);
10495 	}
10496 
10497 	ctl_set_success(ctsio);
10498 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10499 	ctsio->be_move_done = ctl_config_move_done;
10500 	ctl_datamove((union ctl_io *)ctsio);
10501 	return (CTL_RETVAL_COMPLETE);
10502 }
10503 
10504 /*
10505  * For known CDB types, parse the LBA and length.
10506  */
10507 static int
10508 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10509 {
10510 	if (io->io_hdr.io_type != CTL_IO_SCSI)
10511 		return (1);
10512 
10513 	switch (io->scsiio.cdb[0]) {
10514 	case COMPARE_AND_WRITE: {
10515 		struct scsi_compare_and_write *cdb;
10516 
10517 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10518 
10519 		*lba = scsi_8btou64(cdb->addr);
10520 		*len = cdb->length;
10521 		break;
10522 	}
10523 	case READ_6:
10524 	case WRITE_6: {
10525 		struct scsi_rw_6 *cdb;
10526 
10527 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10528 
10529 		*lba = scsi_3btoul(cdb->addr);
10530 		/* only 5 bits are valid in the most significant address byte */
10531 		*lba &= 0x1fffff;
10532 		*len = cdb->length;
10533 		break;
10534 	}
10535 	case READ_10:
10536 	case WRITE_10: {
10537 		struct scsi_rw_10 *cdb;
10538 
10539 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10540 
10541 		*lba = scsi_4btoul(cdb->addr);
10542 		*len = scsi_2btoul(cdb->length);
10543 		break;
10544 	}
10545 	case WRITE_VERIFY_10: {
10546 		struct scsi_write_verify_10 *cdb;
10547 
10548 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10549 
10550 		*lba = scsi_4btoul(cdb->addr);
10551 		*len = scsi_2btoul(cdb->length);
10552 		break;
10553 	}
10554 	case READ_12:
10555 	case WRITE_12: {
10556 		struct scsi_rw_12 *cdb;
10557 
10558 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10559 
10560 		*lba = scsi_4btoul(cdb->addr);
10561 		*len = scsi_4btoul(cdb->length);
10562 		break;
10563 	}
10564 	case WRITE_VERIFY_12: {
10565 		struct scsi_write_verify_12 *cdb;
10566 
10567 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10568 
10569 		*lba = scsi_4btoul(cdb->addr);
10570 		*len = scsi_4btoul(cdb->length);
10571 		break;
10572 	}
10573 	case READ_16:
10574 	case WRITE_16: {
10575 		struct scsi_rw_16 *cdb;
10576 
10577 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10578 
10579 		*lba = scsi_8btou64(cdb->addr);
10580 		*len = scsi_4btoul(cdb->length);
10581 		break;
10582 	}
10583 	case WRITE_ATOMIC_16: {
10584 		struct scsi_write_atomic_16 *cdb;
10585 
10586 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10587 
10588 		*lba = scsi_8btou64(cdb->addr);
10589 		*len = scsi_2btoul(cdb->length);
10590 		break;
10591 	}
10592 	case WRITE_VERIFY_16: {
10593 		struct scsi_write_verify_16 *cdb;
10594 
10595 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10596 
10597 		*lba = scsi_8btou64(cdb->addr);
10598 		*len = scsi_4btoul(cdb->length);
10599 		break;
10600 	}
10601 	case WRITE_SAME_10: {
10602 		struct scsi_write_same_10 *cdb;
10603 
10604 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10605 
10606 		*lba = scsi_4btoul(cdb->addr);
10607 		*len = scsi_2btoul(cdb->length);
10608 		break;
10609 	}
10610 	case WRITE_SAME_16: {
10611 		struct scsi_write_same_16 *cdb;
10612 
10613 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10614 
10615 		*lba = scsi_8btou64(cdb->addr);
10616 		*len = scsi_4btoul(cdb->length);
10617 		break;
10618 	}
10619 	case VERIFY_10: {
10620 		struct scsi_verify_10 *cdb;
10621 
10622 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10623 
10624 		*lba = scsi_4btoul(cdb->addr);
10625 		*len = scsi_2btoul(cdb->length);
10626 		break;
10627 	}
10628 	case VERIFY_12: {
10629 		struct scsi_verify_12 *cdb;
10630 
10631 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10632 
10633 		*lba = scsi_4btoul(cdb->addr);
10634 		*len = scsi_4btoul(cdb->length);
10635 		break;
10636 	}
10637 	case VERIFY_16: {
10638 		struct scsi_verify_16 *cdb;
10639 
10640 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10641 
10642 		*lba = scsi_8btou64(cdb->addr);
10643 		*len = scsi_4btoul(cdb->length);
10644 		break;
10645 	}
10646 	case UNMAP: {
10647 		*lba = 0;
10648 		*len = UINT64_MAX;
10649 		break;
10650 	}
10651 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10652 		struct scsi_get_lba_status *cdb;
10653 
10654 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10655 		*lba = scsi_8btou64(cdb->addr);
10656 		*len = UINT32_MAX;
10657 		break;
10658 	}
10659 	default:
10660 		return (1);
10661 		break; /* NOTREACHED */
10662 	}
10663 
10664 	return (0);
10665 }
10666 
10667 static ctl_action
10668 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10669     bool seq)
10670 {
10671 	uint64_t endlba1, endlba2;
10672 
10673 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10674 	endlba2 = lba2 + len2 - 1;
10675 
10676 	if ((endlba1 < lba2) || (endlba2 < lba1))
10677 		return (CTL_ACTION_PASS);
10678 	else
10679 		return (CTL_ACTION_BLOCK);
10680 }
10681 
10682 static int
10683 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10684 {
10685 	struct ctl_ptr_len_flags *ptrlen;
10686 	struct scsi_unmap_desc *buf, *end, *range;
10687 	uint64_t lba;
10688 	uint32_t len;
10689 
10690 	/* If not UNMAP -- go other way. */
10691 	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10692 	    io->scsiio.cdb[0] != UNMAP)
10693 		return (CTL_ACTION_ERROR);
10694 
10695 	/* If UNMAP without data -- block and wait for data. */
10696 	ptrlen = (struct ctl_ptr_len_flags *)
10697 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10698 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10699 	    ptrlen->ptr == NULL)
10700 		return (CTL_ACTION_BLOCK);
10701 
10702 	/* UNMAP with data -- check for collision. */
10703 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10704 	end = buf + ptrlen->len / sizeof(*buf);
10705 	for (range = buf; range < end; range++) {
10706 		lba = scsi_8btou64(range->lba);
10707 		len = scsi_4btoul(range->length);
10708 		if ((lba < lba2 + len2) && (lba + len > lba2))
10709 			return (CTL_ACTION_BLOCK);
10710 	}
10711 	return (CTL_ACTION_PASS);
10712 }
10713 
10714 static ctl_action
10715 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10716 {
10717 	uint64_t lba1, lba2;
10718 	uint64_t len1, len2;
10719 	int retval;
10720 
10721 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10722 		return (CTL_ACTION_ERROR);
10723 
10724 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10725 	if (retval != CTL_ACTION_ERROR)
10726 		return (retval);
10727 
10728 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10729 		return (CTL_ACTION_ERROR);
10730 
10731 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10732 		seq = FALSE;
10733 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10734 }
10735 
10736 static ctl_action
10737 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10738 {
10739 	uint64_t lba1, lba2;
10740 	uint64_t len1, len2;
10741 
10742 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10743 		return (CTL_ACTION_PASS);
10744 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10745 		return (CTL_ACTION_ERROR);
10746 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10747 		return (CTL_ACTION_ERROR);
10748 
10749 	if (lba1 + len1 == lba2)
10750 		return (CTL_ACTION_BLOCK);
10751 	return (CTL_ACTION_PASS);
10752 }
10753 
10754 static ctl_action
10755 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10756     union ctl_io *ooa_io)
10757 {
10758 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10759 	const ctl_serialize_action *serialize_row;
10760 
10761 	/*
10762 	 * The initiator attempted multiple untagged commands at the same
10763 	 * time.  Can't do that.
10764 	 */
10765 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10766 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10767 	 && ((pending_io->io_hdr.nexus.targ_port ==
10768 	      ooa_io->io_hdr.nexus.targ_port)
10769 	  && (pending_io->io_hdr.nexus.initid ==
10770 	      ooa_io->io_hdr.nexus.initid))
10771 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10772 	      CTL_FLAG_STATUS_SENT)) == 0))
10773 		return (CTL_ACTION_OVERLAP);
10774 
10775 	/*
10776 	 * The initiator attempted to send multiple tagged commands with
10777 	 * the same ID.  (It's fine if different initiators have the same
10778 	 * tag ID.)
10779 	 *
10780 	 * Even if all of those conditions are true, we don't kill the I/O
10781 	 * if the command ahead of us has been aborted.  We won't end up
10782 	 * sending it to the FETD, and it's perfectly legal to resend a
10783 	 * command with the same tag number as long as the previous
10784 	 * instance of this tag number has been aborted somehow.
10785 	 */
10786 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10787 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10788 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10789 	 && ((pending_io->io_hdr.nexus.targ_port ==
10790 	      ooa_io->io_hdr.nexus.targ_port)
10791 	  && (pending_io->io_hdr.nexus.initid ==
10792 	      ooa_io->io_hdr.nexus.initid))
10793 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10794 	      CTL_FLAG_STATUS_SENT)) == 0))
10795 		return (CTL_ACTION_OVERLAP_TAG);
10796 
10797 	/*
10798 	 * If we get a head of queue tag, SAM-3 says that we should
10799 	 * immediately execute it.
10800 	 *
10801 	 * What happens if this command would normally block for some other
10802 	 * reason?  e.g. a request sense with a head of queue tag
10803 	 * immediately after a write.  Normally that would block, but this
10804 	 * will result in its getting executed immediately...
10805 	 *
10806 	 * We currently return "pass" instead of "skip", so we'll end up
10807 	 * going through the rest of the queue to check for overlapped tags.
10808 	 *
10809 	 * XXX KDM check for other types of blockage first??
10810 	 */
10811 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10812 		return (CTL_ACTION_PASS);
10813 
10814 	/*
10815 	 * Ordered tags have to block until all items ahead of them
10816 	 * have completed.  If we get called with an ordered tag, we always
10817 	 * block, if something else is ahead of us in the queue.
10818 	 */
10819 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10820 		return (CTL_ACTION_BLOCK);
10821 
10822 	/*
10823 	 * Simple tags get blocked until all head of queue and ordered tags
10824 	 * ahead of them have completed.  I'm lumping untagged commands in
10825 	 * with simple tags here.  XXX KDM is that the right thing to do?
10826 	 */
10827 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10828 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10829 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10830 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10831 		return (CTL_ACTION_BLOCK);
10832 
10833 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10834 	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
10835 	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
10836 	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
10837 	     pending_io->scsiio.cdb[1], pending_io));
10838 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10839 	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
10840 		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
10841 	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
10842 	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
10843 	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
10844 	     ooa_io->scsiio.cdb[1], ooa_io));
10845 
10846 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10847 
10848 	switch (serialize_row[pending_entry->seridx]) {
10849 	case CTL_SER_BLOCK:
10850 		return (CTL_ACTION_BLOCK);
10851 	case CTL_SER_EXTENT:
10852 		return (ctl_extent_check(ooa_io, pending_io,
10853 		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10854 	case CTL_SER_EXTENTOPT:
10855 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
10856 		    SCP_QUEUE_ALG_UNRESTRICTED)
10857 			return (ctl_extent_check(ooa_io, pending_io,
10858 			    (lun->be_lun &&
10859 			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10860 		return (CTL_ACTION_PASS);
10861 	case CTL_SER_EXTENTSEQ:
10862 		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10863 			return (ctl_extent_check_seq(ooa_io, pending_io));
10864 		return (CTL_ACTION_PASS);
10865 	case CTL_SER_PASS:
10866 		return (CTL_ACTION_PASS);
10867 	case CTL_SER_BLOCKOPT:
10868 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
10869 		    SCP_QUEUE_ALG_UNRESTRICTED)
10870 			return (CTL_ACTION_BLOCK);
10871 		return (CTL_ACTION_PASS);
10872 	case CTL_SER_SKIP:
10873 		return (CTL_ACTION_SKIP);
10874 	default:
10875 		panic("%s: Invalid serialization value %d for %d => %d",
10876 		    __func__, serialize_row[pending_entry->seridx],
10877 		    pending_entry->seridx, ooa_entry->seridx);
10878 	}
10879 
10880 	return (CTL_ACTION_ERROR);
10881 }
10882 
10883 /*
10884  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10885  * Assumptions:
10886  * - pending_io is generally either incoming, or on the blocked queue
10887  * - starting I/O is the I/O we want to start the check with.
10888  */
10889 static ctl_action
10890 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10891 	      union ctl_io *starting_io)
10892 {
10893 	union ctl_io *ooa_io;
10894 	ctl_action action;
10895 
10896 	mtx_assert(&lun->lun_lock, MA_OWNED);
10897 
10898 	/*
10899 	 * Run back along the OOA queue, starting with the current
10900 	 * blocked I/O and going through every I/O before it on the
10901 	 * queue.  If starting_io is NULL, we'll just end up returning
10902 	 * CTL_ACTION_PASS.
10903 	 */
10904 	for (ooa_io = starting_io; ooa_io != NULL;
10905 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10906 	     ooa_links)){
10907 
10908 		/*
10909 		 * This routine just checks to see whether
10910 		 * cur_blocked is blocked by ooa_io, which is ahead
10911 		 * of it in the queue.  It doesn't queue/dequeue
10912 		 * cur_blocked.
10913 		 */
10914 		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10915 		switch (action) {
10916 		case CTL_ACTION_BLOCK:
10917 		case CTL_ACTION_OVERLAP:
10918 		case CTL_ACTION_OVERLAP_TAG:
10919 		case CTL_ACTION_SKIP:
10920 		case CTL_ACTION_ERROR:
10921 			return (action);
10922 			break; /* NOTREACHED */
10923 		case CTL_ACTION_PASS:
10924 			break;
10925 		default:
10926 			panic("%s: Invalid action %d\n", __func__, action);
10927 		}
10928 	}
10929 
10930 	return (CTL_ACTION_PASS);
10931 }
10932 
10933 /*
10934  * Assumptions:
10935  * - An I/O has just completed, and has been removed from the per-LUN OOA
10936  *   queue, so some items on the blocked queue may now be unblocked.
10937  */
10938 static int
10939 ctl_check_blocked(struct ctl_lun *lun)
10940 {
10941 	struct ctl_softc *softc = lun->ctl_softc;
10942 	union ctl_io *cur_blocked, *next_blocked;
10943 
10944 	mtx_assert(&lun->lun_lock, MA_OWNED);
10945 
10946 	/*
10947 	 * Run forward from the head of the blocked queue, checking each
10948 	 * entry against the I/Os prior to it on the OOA queue to see if
10949 	 * there is still any blockage.
10950 	 *
10951 	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10952 	 * with our removing a variable on it while it is traversing the
10953 	 * list.
10954 	 */
10955 	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10956 	     cur_blocked != NULL; cur_blocked = next_blocked) {
10957 		union ctl_io *prev_ooa;
10958 		ctl_action action;
10959 
10960 		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10961 							  blocked_links);
10962 
10963 		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10964 						      ctl_ooaq, ooa_links);
10965 
10966 		/*
10967 		 * If cur_blocked happens to be the first item in the OOA
10968 		 * queue now, prev_ooa will be NULL, and the action
10969 		 * returned will just be CTL_ACTION_PASS.
10970 		 */
10971 		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10972 
10973 		switch (action) {
10974 		case CTL_ACTION_BLOCK:
10975 			/* Nothing to do here, still blocked */
10976 			break;
10977 		case CTL_ACTION_OVERLAP:
10978 		case CTL_ACTION_OVERLAP_TAG:
10979 			/*
10980 			 * This shouldn't happen!  In theory we've already
10981 			 * checked this command for overlap...
10982 			 */
10983 			break;
10984 		case CTL_ACTION_PASS:
10985 		case CTL_ACTION_SKIP: {
10986 			const struct ctl_cmd_entry *entry;
10987 
10988 			/*
10989 			 * The skip case shouldn't happen, this transaction
10990 			 * should have never made it onto the blocked queue.
10991 			 */
10992 			/*
10993 			 * This I/O is no longer blocked, we can remove it
10994 			 * from the blocked queue.  Since this is a TAILQ
10995 			 * (doubly linked list), we can do O(1) removals
10996 			 * from any place on the list.
10997 			 */
10998 			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
10999 				     blocked_links);
11000 			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11001 
11002 			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11003 			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11004 				/*
11005 				 * Need to send IO back to original side to
11006 				 * run
11007 				 */
11008 				union ctl_ha_msg msg_info;
11009 
11010 				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11011 				msg_info.hdr.original_sc =
11012 					cur_blocked->io_hdr.remote_io;
11013 				msg_info.hdr.serializing_sc = cur_blocked;
11014 				msg_info.hdr.msg_type = CTL_MSG_R2R;
11015 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11016 				    sizeof(msg_info.hdr), M_NOWAIT);
11017 				break;
11018 			}
11019 			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11020 
11021 			/*
11022 			 * Check this I/O for LUN state changes that may
11023 			 * have happened while this command was blocked.
11024 			 * The LUN state may have been changed by a command
11025 			 * ahead of us in the queue, so we need to re-check
11026 			 * for any states that can be caused by SCSI
11027 			 * commands.
11028 			 */
11029 			if (ctl_scsiio_lun_check(lun, entry,
11030 						 &cur_blocked->scsiio) == 0) {
11031 				cur_blocked->io_hdr.flags |=
11032 				                      CTL_FLAG_IS_WAS_ON_RTR;
11033 				ctl_enqueue_rtr(cur_blocked);
11034 			} else
11035 				ctl_done(cur_blocked);
11036 			break;
11037 		}
11038 		default:
11039 			/*
11040 			 * This probably shouldn't happen -- we shouldn't
11041 			 * get CTL_ACTION_ERROR, or anything else.
11042 			 */
11043 			break;
11044 		}
11045 	}
11046 
11047 	return (CTL_RETVAL_COMPLETE);
11048 }
11049 
11050 /*
11051  * This routine (with one exception) checks LUN flags that can be set by
11052  * commands ahead of us in the OOA queue.  These flags have to be checked
11053  * when a command initially comes in, and when we pull a command off the
11054  * blocked queue and are preparing to execute it.  The reason we have to
11055  * check these flags for commands on the blocked queue is that the LUN
11056  * state may have been changed by a command ahead of us while we're on the
11057  * blocked queue.
11058  *
11059  * Ordering is somewhat important with these checks, so please pay
11060  * careful attention to the placement of any new checks.
11061  */
11062 static int
11063 ctl_scsiio_lun_check(struct ctl_lun *lun,
11064     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11065 {
11066 	struct ctl_softc *softc = lun->ctl_softc;
11067 	int retval;
11068 	uint32_t residx;
11069 
11070 	retval = 0;
11071 
11072 	mtx_assert(&lun->lun_lock, MA_OWNED);
11073 
11074 	/*
11075 	 * If this shelf is a secondary shelf controller, we may have to
11076 	 * reject some commands disallowed by HA mode and link state.
11077 	 */
11078 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11079 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11080 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11081 			ctl_set_lun_unavail(ctsio);
11082 			retval = 1;
11083 			goto bailout;
11084 		}
11085 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11086 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11087 			ctl_set_lun_transit(ctsio);
11088 			retval = 1;
11089 			goto bailout;
11090 		}
11091 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11092 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11093 			ctl_set_lun_standby(ctsio);
11094 			retval = 1;
11095 			goto bailout;
11096 		}
11097 
11098 		/* The rest of checks are only done on executing side */
11099 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11100 			goto bailout;
11101 	}
11102 
11103 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11104 		if (lun->be_lun &&
11105 		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11106 			ctl_set_hw_write_protected(ctsio);
11107 			retval = 1;
11108 			goto bailout;
11109 		}
11110 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11111 			ctl_set_sense(ctsio, /*current_error*/ 1,
11112 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11113 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11114 			retval = 1;
11115 			goto bailout;
11116 		}
11117 	}
11118 
11119 	/*
11120 	 * Check for a reservation conflict.  If this command isn't allowed
11121 	 * even on reserved LUNs, and if this initiator isn't the one who
11122 	 * reserved us, reject the command with a reservation conflict.
11123 	 */
11124 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11125 	if ((lun->flags & CTL_LUN_RESERVED)
11126 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11127 		if (lun->res_idx != residx) {
11128 			ctl_set_reservation_conflict(ctsio);
11129 			retval = 1;
11130 			goto bailout;
11131 		}
11132 	}
11133 
11134 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11135 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11136 		/* No reservation or command is allowed. */;
11137 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11138 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11139 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11140 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11141 		/* The command is allowed for Write Exclusive resv. */;
11142 	} else {
11143 		/*
11144 		 * if we aren't registered or it's a res holder type
11145 		 * reservation and this isn't the res holder then set a
11146 		 * conflict.
11147 		 */
11148 		if (ctl_get_prkey(lun, residx) == 0 ||
11149 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11150 			ctl_set_reservation_conflict(ctsio);
11151 			retval = 1;
11152 			goto bailout;
11153 		}
11154 	}
11155 
11156 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11157 		if (lun->flags & CTL_LUN_EJECTED)
11158 			ctl_set_lun_ejected(ctsio);
11159 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11160 			if (lun->flags & CTL_LUN_REMOVABLE)
11161 				ctl_set_lun_no_media(ctsio);
11162 			else
11163 				ctl_set_lun_int_reqd(ctsio);
11164 		} else if (lun->flags & CTL_LUN_STOPPED)
11165 			ctl_set_lun_stopped(ctsio);
11166 		else
11167 			goto bailout;
11168 		retval = 1;
11169 		goto bailout;
11170 	}
11171 
11172 bailout:
11173 	return (retval);
11174 }
11175 
11176 static void
11177 ctl_failover_io(union ctl_io *io, int have_lock)
11178 {
11179 	ctl_set_busy(&io->scsiio);
11180 	ctl_done(io);
11181 }
11182 
11183 static void
11184 ctl_failover_lun(union ctl_io *rio)
11185 {
11186 	struct ctl_softc *softc = CTL_SOFTC(rio);
11187 	struct ctl_lun *lun;
11188 	struct ctl_io_hdr *io, *next_io;
11189 	uint32_t targ_lun;
11190 
11191 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11192 	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11193 
11194 	/* Find and lock the LUN. */
11195 	mtx_lock(&softc->ctl_lock);
11196 	if (targ_lun > ctl_max_luns ||
11197 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11198 		mtx_unlock(&softc->ctl_lock);
11199 		return;
11200 	}
11201 	mtx_lock(&lun->lun_lock);
11202 	mtx_unlock(&softc->ctl_lock);
11203 	if (lun->flags & CTL_LUN_DISABLED) {
11204 		mtx_unlock(&lun->lun_lock);
11205 		return;
11206 	}
11207 
11208 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11209 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11210 			/* We are master */
11211 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11212 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11213 					io->flags |= CTL_FLAG_ABORT;
11214 					io->flags |= CTL_FLAG_FAILOVER;
11215 				} else { /* This can be only due to DATAMOVE */
11216 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11217 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11218 					io->flags |= CTL_FLAG_IO_ACTIVE;
11219 					io->port_status = 31340;
11220 					ctl_enqueue_isc((union ctl_io *)io);
11221 				}
11222 			}
11223 			/* We are slave */
11224 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11225 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11226 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11227 					io->flags |= CTL_FLAG_FAILOVER;
11228 				} else {
11229 					ctl_set_busy(&((union ctl_io *)io)->
11230 					    scsiio);
11231 					ctl_done((union ctl_io *)io);
11232 				}
11233 			}
11234 		}
11235 	} else { /* SERIALIZE modes */
11236 		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11237 		    next_io) {
11238 			/* We are master */
11239 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11240 				TAILQ_REMOVE(&lun->blocked_queue, io,
11241 				    blocked_links);
11242 				io->flags &= ~CTL_FLAG_BLOCKED;
11243 				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11244 				ctl_free_io((union ctl_io *)io);
11245 			}
11246 		}
11247 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11248 			/* We are master */
11249 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11250 				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11251 				ctl_free_io((union ctl_io *)io);
11252 			}
11253 			/* We are slave */
11254 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11255 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11256 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11257 					ctl_set_busy(&((union ctl_io *)io)->
11258 					    scsiio);
11259 					ctl_done((union ctl_io *)io);
11260 				}
11261 			}
11262 		}
11263 		ctl_check_blocked(lun);
11264 	}
11265 	mtx_unlock(&lun->lun_lock);
11266 }
11267 
11268 static int
11269 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11270 {
11271 	struct ctl_lun *lun;
11272 	const struct ctl_cmd_entry *entry;
11273 	uint32_t initidx, targ_lun;
11274 	int retval = 0;
11275 
11276 	lun = NULL;
11277 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11278 	if (targ_lun < ctl_max_luns)
11279 		lun = softc->ctl_luns[targ_lun];
11280 	if (lun) {
11281 		/*
11282 		 * If the LUN is invalid, pretend that it doesn't exist.
11283 		 * It will go away as soon as all pending I/O has been
11284 		 * completed.
11285 		 */
11286 		mtx_lock(&lun->lun_lock);
11287 		if (lun->flags & CTL_LUN_DISABLED) {
11288 			mtx_unlock(&lun->lun_lock);
11289 			lun = NULL;
11290 		}
11291 	}
11292 	CTL_LUN(ctsio) = lun;
11293 	if (lun) {
11294 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11295 
11296 		/*
11297 		 * Every I/O goes into the OOA queue for a particular LUN,
11298 		 * and stays there until completion.
11299 		 */
11300 #ifdef CTL_TIME_IO
11301 		if (TAILQ_EMPTY(&lun->ooa_queue))
11302 			lun->idle_time += getsbinuptime() - lun->last_busy;
11303 #endif
11304 		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11305 	}
11306 
11307 	/* Get command entry and return error if it is unsuppotyed. */
11308 	entry = ctl_validate_command(ctsio);
11309 	if (entry == NULL) {
11310 		if (lun)
11311 			mtx_unlock(&lun->lun_lock);
11312 		return (retval);
11313 	}
11314 
11315 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11316 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11317 
11318 	/*
11319 	 * Check to see whether we can send this command to LUNs that don't
11320 	 * exist.  This should pretty much only be the case for inquiry
11321 	 * and request sense.  Further checks, below, really require having
11322 	 * a LUN, so we can't really check the command anymore.  Just put
11323 	 * it on the rtr queue.
11324 	 */
11325 	if (lun == NULL) {
11326 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11327 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11328 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11329 			return (retval);
11330 		}
11331 
11332 		ctl_set_unsupported_lun(ctsio);
11333 		ctl_done((union ctl_io *)ctsio);
11334 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11335 		return (retval);
11336 	} else {
11337 		/*
11338 		 * Make sure we support this particular command on this LUN.
11339 		 * e.g., we don't support writes to the control LUN.
11340 		 */
11341 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11342 			mtx_unlock(&lun->lun_lock);
11343 			ctl_set_invalid_opcode(ctsio);
11344 			ctl_done((union ctl_io *)ctsio);
11345 			return (retval);
11346 		}
11347 	}
11348 
11349 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11350 
11351 	/*
11352 	 * If we've got a request sense, it'll clear the contingent
11353 	 * allegiance condition.  Otherwise, if we have a CA condition for
11354 	 * this initiator, clear it, because it sent down a command other
11355 	 * than request sense.
11356 	 */
11357 	if (ctsio->cdb[0] != REQUEST_SENSE) {
11358 		struct scsi_sense_data *ps;
11359 
11360 		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11361 		if (ps != NULL)
11362 			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11363 	}
11364 
11365 	/*
11366 	 * If the command has this flag set, it handles its own unit
11367 	 * attention reporting, we shouldn't do anything.  Otherwise we
11368 	 * check for any pending unit attentions, and send them back to the
11369 	 * initiator.  We only do this when a command initially comes in,
11370 	 * not when we pull it off the blocked queue.
11371 	 *
11372 	 * According to SAM-3, section 5.3.2, the order that things get
11373 	 * presented back to the host is basically unit attentions caused
11374 	 * by some sort of reset event, busy status, reservation conflicts
11375 	 * or task set full, and finally any other status.
11376 	 *
11377 	 * One issue here is that some of the unit attentions we report
11378 	 * don't fall into the "reset" category (e.g. "reported luns data
11379 	 * has changed").  So reporting it here, before the reservation
11380 	 * check, may be technically wrong.  I guess the only thing to do
11381 	 * would be to check for and report the reset events here, and then
11382 	 * check for the other unit attention types after we check for a
11383 	 * reservation conflict.
11384 	 *
11385 	 * XXX KDM need to fix this
11386 	 */
11387 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11388 		ctl_ua_type ua_type;
11389 		u_int sense_len = 0;
11390 
11391 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11392 		    &sense_len, SSD_TYPE_NONE);
11393 		if (ua_type != CTL_UA_NONE) {
11394 			mtx_unlock(&lun->lun_lock);
11395 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11396 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11397 			ctsio->sense_len = sense_len;
11398 			ctl_done((union ctl_io *)ctsio);
11399 			return (retval);
11400 		}
11401 	}
11402 
11403 
11404 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11405 		mtx_unlock(&lun->lun_lock);
11406 		ctl_done((union ctl_io *)ctsio);
11407 		return (retval);
11408 	}
11409 
11410 	/*
11411 	 * XXX CHD this is where we want to send IO to other side if
11412 	 * this LUN is secondary on this SC. We will need to make a copy
11413 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11414 	 * the copy we send as FROM_OTHER.
11415 	 * We also need to stuff the address of the original IO so we can
11416 	 * find it easily. Something similar will need be done on the other
11417 	 * side so when we are done we can find the copy.
11418 	 */
11419 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11420 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11421 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11422 		union ctl_ha_msg msg_info;
11423 		int isc_retval;
11424 
11425 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11426 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11427 		mtx_unlock(&lun->lun_lock);
11428 
11429 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11430 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11431 		msg_info.hdr.serializing_sc = NULL;
11432 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11433 		msg_info.scsi.tag_num = ctsio->tag_num;
11434 		msg_info.scsi.tag_type = ctsio->tag_type;
11435 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11436 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11437 
11438 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11439 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11440 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11441 			ctl_set_busy(ctsio);
11442 			ctl_done((union ctl_io *)ctsio);
11443 			return (retval);
11444 		}
11445 		return (retval);
11446 	}
11447 
11448 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11449 			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11450 			      ctl_ooaq, ooa_links))) {
11451 	case CTL_ACTION_BLOCK:
11452 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11453 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11454 				  blocked_links);
11455 		mtx_unlock(&lun->lun_lock);
11456 		return (retval);
11457 	case CTL_ACTION_PASS:
11458 	case CTL_ACTION_SKIP:
11459 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11460 		mtx_unlock(&lun->lun_lock);
11461 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11462 		break;
11463 	case CTL_ACTION_OVERLAP:
11464 		mtx_unlock(&lun->lun_lock);
11465 		ctl_set_overlapped_cmd(ctsio);
11466 		ctl_done((union ctl_io *)ctsio);
11467 		break;
11468 	case CTL_ACTION_OVERLAP_TAG:
11469 		mtx_unlock(&lun->lun_lock);
11470 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11471 		ctl_done((union ctl_io *)ctsio);
11472 		break;
11473 	case CTL_ACTION_ERROR:
11474 	default:
11475 		mtx_unlock(&lun->lun_lock);
11476 		ctl_set_internal_failure(ctsio,
11477 					 /*sks_valid*/ 0,
11478 					 /*retry_count*/ 0);
11479 		ctl_done((union ctl_io *)ctsio);
11480 		break;
11481 	}
11482 	return (retval);
11483 }
11484 
11485 const struct ctl_cmd_entry *
11486 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11487 {
11488 	const struct ctl_cmd_entry *entry;
11489 	int service_action;
11490 
11491 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11492 	if (sa)
11493 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11494 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11495 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11496 		entry = &((const struct ctl_cmd_entry *)
11497 		    entry->execute)[service_action];
11498 	}
11499 	return (entry);
11500 }
11501 
11502 const struct ctl_cmd_entry *
11503 ctl_validate_command(struct ctl_scsiio *ctsio)
11504 {
11505 	const struct ctl_cmd_entry *entry;
11506 	int i, sa;
11507 	uint8_t diff;
11508 
11509 	entry = ctl_get_cmd_entry(ctsio, &sa);
11510 	if (entry->execute == NULL) {
11511 		if (sa)
11512 			ctl_set_invalid_field(ctsio,
11513 					      /*sks_valid*/ 1,
11514 					      /*command*/ 1,
11515 					      /*field*/ 1,
11516 					      /*bit_valid*/ 1,
11517 					      /*bit*/ 4);
11518 		else
11519 			ctl_set_invalid_opcode(ctsio);
11520 		ctl_done((union ctl_io *)ctsio);
11521 		return (NULL);
11522 	}
11523 	KASSERT(entry->length > 0,
11524 	    ("Not defined length for command 0x%02x/0x%02x",
11525 	     ctsio->cdb[0], ctsio->cdb[1]));
11526 	for (i = 1; i < entry->length; i++) {
11527 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11528 		if (diff == 0)
11529 			continue;
11530 		ctl_set_invalid_field(ctsio,
11531 				      /*sks_valid*/ 1,
11532 				      /*command*/ 1,
11533 				      /*field*/ i,
11534 				      /*bit_valid*/ 1,
11535 				      /*bit*/ fls(diff) - 1);
11536 		ctl_done((union ctl_io *)ctsio);
11537 		return (NULL);
11538 	}
11539 	return (entry);
11540 }
11541 
11542 static int
11543 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11544 {
11545 
11546 	switch (lun_type) {
11547 	case T_DIRECT:
11548 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11549 			return (0);
11550 		break;
11551 	case T_PROCESSOR:
11552 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11553 			return (0);
11554 		break;
11555 	case T_CDROM:
11556 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11557 			return (0);
11558 		break;
11559 	default:
11560 		return (0);
11561 	}
11562 	return (1);
11563 }
11564 
11565 static int
11566 ctl_scsiio(struct ctl_scsiio *ctsio)
11567 {
11568 	int retval;
11569 	const struct ctl_cmd_entry *entry;
11570 
11571 	retval = CTL_RETVAL_COMPLETE;
11572 
11573 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11574 
11575 	entry = ctl_get_cmd_entry(ctsio, NULL);
11576 
11577 	/*
11578 	 * If this I/O has been aborted, just send it straight to
11579 	 * ctl_done() without executing it.
11580 	 */
11581 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11582 		ctl_done((union ctl_io *)ctsio);
11583 		goto bailout;
11584 	}
11585 
11586 	/*
11587 	 * All the checks should have been handled by ctl_scsiio_precheck().
11588 	 * We should be clear now to just execute the I/O.
11589 	 */
11590 	retval = entry->execute(ctsio);
11591 
11592 bailout:
11593 	return (retval);
11594 }
11595 
11596 static int
11597 ctl_target_reset(union ctl_io *io)
11598 {
11599 	struct ctl_softc *softc = CTL_SOFTC(io);
11600 	struct ctl_port *port = CTL_PORT(io);
11601 	struct ctl_lun *lun;
11602 	uint32_t initidx;
11603 	ctl_ua_type ua_type;
11604 
11605 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11606 		union ctl_ha_msg msg_info;
11607 
11608 		msg_info.hdr.nexus = io->io_hdr.nexus;
11609 		msg_info.task.task_action = io->taskio.task_action;
11610 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11611 		msg_info.hdr.original_sc = NULL;
11612 		msg_info.hdr.serializing_sc = NULL;
11613 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11614 		    sizeof(msg_info.task), M_WAITOK);
11615 	}
11616 
11617 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11618 	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11619 		ua_type = CTL_UA_TARG_RESET;
11620 	else
11621 		ua_type = CTL_UA_BUS_RESET;
11622 	mtx_lock(&softc->ctl_lock);
11623 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11624 		if (port != NULL &&
11625 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11626 			continue;
11627 		ctl_do_lun_reset(lun, initidx, ua_type);
11628 	}
11629 	mtx_unlock(&softc->ctl_lock);
11630 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11631 	return (0);
11632 }
11633 
11634 /*
11635  * The LUN should always be set.  The I/O is optional, and is used to
11636  * distinguish between I/Os sent by this initiator, and by other
11637  * initiators.  We set unit attention for initiators other than this one.
11638  * SAM-3 is vague on this point.  It does say that a unit attention should
11639  * be established for other initiators when a LUN is reset (see section
11640  * 5.7.3), but it doesn't specifically say that the unit attention should
11641  * be established for this particular initiator when a LUN is reset.  Here
11642  * is the relevant text, from SAM-3 rev 8:
11643  *
11644  * 5.7.2 When a SCSI initiator port aborts its own tasks
11645  *
11646  * When a SCSI initiator port causes its own task(s) to be aborted, no
11647  * notification that the task(s) have been aborted shall be returned to
11648  * the SCSI initiator port other than the completion response for the
11649  * command or task management function action that caused the task(s) to
11650  * be aborted and notification(s) associated with related effects of the
11651  * action (e.g., a reset unit attention condition).
11652  *
11653  * XXX KDM for now, we're setting unit attention for all initiators.
11654  */
11655 static void
11656 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11657 {
11658 	union ctl_io *xio;
11659 	int i;
11660 
11661 	mtx_lock(&lun->lun_lock);
11662 	/* Abort tasks. */
11663 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11664 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11665 		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11666 	}
11667 	/* Clear CA. */
11668 	for (i = 0; i < ctl_max_ports; i++) {
11669 		free(lun->pending_sense[i], M_CTL);
11670 		lun->pending_sense[i] = NULL;
11671 	}
11672 	/* Clear reservation. */
11673 	lun->flags &= ~CTL_LUN_RESERVED;
11674 	/* Clear prevent media removal. */
11675 	if (lun->prevent) {
11676 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11677 			ctl_clear_mask(lun->prevent, i);
11678 		lun->prevent_count = 0;
11679 	}
11680 	/* Clear TPC status */
11681 	ctl_tpc_lun_clear(lun, -1);
11682 	/* Establish UA. */
11683 #if 0
11684 	ctl_est_ua_all(lun, initidx, ua_type);
11685 #else
11686 	ctl_est_ua_all(lun, -1, ua_type);
11687 #endif
11688 	mtx_unlock(&lun->lun_lock);
11689 }
11690 
11691 static int
11692 ctl_lun_reset(union ctl_io *io)
11693 {
11694 	struct ctl_softc *softc = CTL_SOFTC(io);
11695 	struct ctl_lun *lun;
11696 	uint32_t targ_lun, initidx;
11697 
11698 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11699 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11700 	mtx_lock(&softc->ctl_lock);
11701 	if (targ_lun >= ctl_max_luns ||
11702 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11703 		mtx_unlock(&softc->ctl_lock);
11704 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11705 		return (1);
11706 	}
11707 	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11708 	mtx_unlock(&softc->ctl_lock);
11709 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11710 
11711 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11712 		union ctl_ha_msg msg_info;
11713 
11714 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11715 		msg_info.hdr.nexus = io->io_hdr.nexus;
11716 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11717 		msg_info.hdr.original_sc = NULL;
11718 		msg_info.hdr.serializing_sc = NULL;
11719 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11720 		    sizeof(msg_info.task), M_WAITOK);
11721 	}
11722 	return (0);
11723 }
11724 
11725 static void
11726 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11727     int other_sc)
11728 {
11729 	union ctl_io *xio;
11730 
11731 	mtx_assert(&lun->lun_lock, MA_OWNED);
11732 
11733 	/*
11734 	 * Run through the OOA queue and attempt to find the given I/O.
11735 	 * The target port, initiator ID, tag type and tag number have to
11736 	 * match the values that we got from the initiator.  If we have an
11737 	 * untagged command to abort, simply abort the first untagged command
11738 	 * we come to.  We only allow one untagged command at a time of course.
11739 	 */
11740 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11741 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11742 
11743 		if ((targ_port == UINT32_MAX ||
11744 		     targ_port == xio->io_hdr.nexus.targ_port) &&
11745 		    (init_id == UINT32_MAX ||
11746 		     init_id == xio->io_hdr.nexus.initid)) {
11747 			if (targ_port != xio->io_hdr.nexus.targ_port ||
11748 			    init_id != xio->io_hdr.nexus.initid)
11749 				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11750 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11751 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11752 				union ctl_ha_msg msg_info;
11753 
11754 				msg_info.hdr.nexus = xio->io_hdr.nexus;
11755 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11756 				msg_info.task.tag_num = xio->scsiio.tag_num;
11757 				msg_info.task.tag_type = xio->scsiio.tag_type;
11758 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11759 				msg_info.hdr.original_sc = NULL;
11760 				msg_info.hdr.serializing_sc = NULL;
11761 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11762 				    sizeof(msg_info.task), M_NOWAIT);
11763 			}
11764 		}
11765 	}
11766 }
11767 
11768 static int
11769 ctl_abort_task_set(union ctl_io *io)
11770 {
11771 	struct ctl_softc *softc = CTL_SOFTC(io);
11772 	struct ctl_lun *lun;
11773 	uint32_t targ_lun;
11774 
11775 	/*
11776 	 * Look up the LUN.
11777 	 */
11778 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11779 	mtx_lock(&softc->ctl_lock);
11780 	if (targ_lun >= ctl_max_luns ||
11781 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11782 		mtx_unlock(&softc->ctl_lock);
11783 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11784 		return (1);
11785 	}
11786 
11787 	mtx_lock(&lun->lun_lock);
11788 	mtx_unlock(&softc->ctl_lock);
11789 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11790 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11791 		    io->io_hdr.nexus.initid,
11792 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11793 	} else { /* CTL_TASK_CLEAR_TASK_SET */
11794 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11795 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11796 	}
11797 	mtx_unlock(&lun->lun_lock);
11798 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11799 	return (0);
11800 }
11801 
11802 static void
11803 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
11804     ctl_ua_type ua_type)
11805 {
11806 	struct ctl_lun *lun;
11807 	struct scsi_sense_data *ps;
11808 	uint32_t p, i;
11809 
11810 	p = initidx / CTL_MAX_INIT_PER_PORT;
11811 	i = initidx % CTL_MAX_INIT_PER_PORT;
11812 	mtx_lock(&softc->ctl_lock);
11813 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11814 		mtx_lock(&lun->lun_lock);
11815 		/* Abort tasks. */
11816 		ctl_abort_tasks_lun(lun, p, i, 1);
11817 		/* Clear CA. */
11818 		ps = lun->pending_sense[p];
11819 		if (ps != NULL)
11820 			ps[i].error_code = 0;
11821 		/* Clear reservation. */
11822 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11823 			lun->flags &= ~CTL_LUN_RESERVED;
11824 		/* Clear prevent media removal. */
11825 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
11826 			ctl_clear_mask(lun->prevent, initidx);
11827 			lun->prevent_count--;
11828 		}
11829 		/* Clear TPC status */
11830 		ctl_tpc_lun_clear(lun, initidx);
11831 		/* Establish UA. */
11832 		ctl_est_ua(lun, initidx, ua_type);
11833 		mtx_unlock(&lun->lun_lock);
11834 	}
11835 	mtx_unlock(&softc->ctl_lock);
11836 }
11837 
11838 static int
11839 ctl_i_t_nexus_reset(union ctl_io *io)
11840 {
11841 	struct ctl_softc *softc = CTL_SOFTC(io);
11842 	uint32_t initidx;
11843 
11844 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11845 		union ctl_ha_msg msg_info;
11846 
11847 		msg_info.hdr.nexus = io->io_hdr.nexus;
11848 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11849 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11850 		msg_info.hdr.original_sc = NULL;
11851 		msg_info.hdr.serializing_sc = NULL;
11852 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11853 		    sizeof(msg_info.task), M_WAITOK);
11854 	}
11855 
11856 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11857 	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
11858 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11859 	return (0);
11860 }
11861 
11862 static int
11863 ctl_abort_task(union ctl_io *io)
11864 {
11865 	struct ctl_softc *softc = CTL_SOFTC(io);
11866 	union ctl_io *xio;
11867 	struct ctl_lun *lun;
11868 	uint32_t targ_lun;
11869 
11870 	/*
11871 	 * Look up the LUN.
11872 	 */
11873 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11874 	mtx_lock(&softc->ctl_lock);
11875 	if (targ_lun >= ctl_max_luns ||
11876 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11877 		mtx_unlock(&softc->ctl_lock);
11878 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11879 		return (1);
11880 	}
11881 
11882 	mtx_lock(&lun->lun_lock);
11883 	mtx_unlock(&softc->ctl_lock);
11884 	/*
11885 	 * Run through the OOA queue and attempt to find the given I/O.
11886 	 * The target port, initiator ID, tag type and tag number have to
11887 	 * match the values that we got from the initiator.  If we have an
11888 	 * untagged command to abort, simply abort the first untagged command
11889 	 * we come to.  We only allow one untagged command at a time of course.
11890 	 */
11891 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11892 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11893 
11894 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11895 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11896 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11897 			continue;
11898 
11899 		/*
11900 		 * If the abort says that the task is untagged, the
11901 		 * task in the queue must be untagged.  Otherwise,
11902 		 * we just check to see whether the tag numbers
11903 		 * match.  This is because the QLogic firmware
11904 		 * doesn't pass back the tag type in an abort
11905 		 * request.
11906 		 */
11907 #if 0
11908 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11909 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11910 		 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
11911 #else
11912 		/*
11913 		 * XXX KDM we've got problems with FC, because it
11914 		 * doesn't send down a tag type with aborts.  So we
11915 		 * can only really go by the tag number...
11916 		 * This may cause problems with parallel SCSI.
11917 		 * Need to figure that out!!
11918 		 */
11919 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
11920 #endif
11921 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11922 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11923 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11924 				union ctl_ha_msg msg_info;
11925 
11926 				msg_info.hdr.nexus = io->io_hdr.nexus;
11927 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11928 				msg_info.task.tag_num = io->taskio.tag_num;
11929 				msg_info.task.tag_type = io->taskio.tag_type;
11930 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11931 				msg_info.hdr.original_sc = NULL;
11932 				msg_info.hdr.serializing_sc = NULL;
11933 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11934 				    sizeof(msg_info.task), M_NOWAIT);
11935 			}
11936 		}
11937 	}
11938 	mtx_unlock(&lun->lun_lock);
11939 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11940 	return (0);
11941 }
11942 
11943 static int
11944 ctl_query_task(union ctl_io *io, int task_set)
11945 {
11946 	struct ctl_softc *softc = CTL_SOFTC(io);
11947 	union ctl_io *xio;
11948 	struct ctl_lun *lun;
11949 	int found = 0;
11950 	uint32_t targ_lun;
11951 
11952 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11953 	mtx_lock(&softc->ctl_lock);
11954 	if (targ_lun >= ctl_max_luns ||
11955 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11956 		mtx_unlock(&softc->ctl_lock);
11957 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11958 		return (1);
11959 	}
11960 	mtx_lock(&lun->lun_lock);
11961 	mtx_unlock(&softc->ctl_lock);
11962 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11963 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11964 
11965 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11966 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11967 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11968 			continue;
11969 
11970 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
11971 			found = 1;
11972 			break;
11973 		}
11974 	}
11975 	mtx_unlock(&lun->lun_lock);
11976 	if (found)
11977 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
11978 	else
11979 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11980 	return (0);
11981 }
11982 
11983 static int
11984 ctl_query_async_event(union ctl_io *io)
11985 {
11986 	struct ctl_softc *softc = CTL_SOFTC(io);
11987 	struct ctl_lun *lun;
11988 	ctl_ua_type ua;
11989 	uint32_t targ_lun, initidx;
11990 
11991 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11992 	mtx_lock(&softc->ctl_lock);
11993 	if (targ_lun >= ctl_max_luns ||
11994 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11995 		mtx_unlock(&softc->ctl_lock);
11996 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11997 		return (1);
11998 	}
11999 	mtx_lock(&lun->lun_lock);
12000 	mtx_unlock(&softc->ctl_lock);
12001 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12002 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12003 	mtx_unlock(&lun->lun_lock);
12004 	if (ua != CTL_UA_NONE)
12005 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12006 	else
12007 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12008 	return (0);
12009 }
12010 
12011 static void
12012 ctl_run_task(union ctl_io *io)
12013 {
12014 	int retval = 1;
12015 
12016 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12017 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12018 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12019 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12020 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12021 	switch (io->taskio.task_action) {
12022 	case CTL_TASK_ABORT_TASK:
12023 		retval = ctl_abort_task(io);
12024 		break;
12025 	case CTL_TASK_ABORT_TASK_SET:
12026 	case CTL_TASK_CLEAR_TASK_SET:
12027 		retval = ctl_abort_task_set(io);
12028 		break;
12029 	case CTL_TASK_CLEAR_ACA:
12030 		break;
12031 	case CTL_TASK_I_T_NEXUS_RESET:
12032 		retval = ctl_i_t_nexus_reset(io);
12033 		break;
12034 	case CTL_TASK_LUN_RESET:
12035 		retval = ctl_lun_reset(io);
12036 		break;
12037 	case CTL_TASK_TARGET_RESET:
12038 	case CTL_TASK_BUS_RESET:
12039 		retval = ctl_target_reset(io);
12040 		break;
12041 	case CTL_TASK_PORT_LOGIN:
12042 		break;
12043 	case CTL_TASK_PORT_LOGOUT:
12044 		break;
12045 	case CTL_TASK_QUERY_TASK:
12046 		retval = ctl_query_task(io, 0);
12047 		break;
12048 	case CTL_TASK_QUERY_TASK_SET:
12049 		retval = ctl_query_task(io, 1);
12050 		break;
12051 	case CTL_TASK_QUERY_ASYNC_EVENT:
12052 		retval = ctl_query_async_event(io);
12053 		break;
12054 	default:
12055 		printf("%s: got unknown task management event %d\n",
12056 		       __func__, io->taskio.task_action);
12057 		break;
12058 	}
12059 	if (retval == 0)
12060 		io->io_hdr.status = CTL_SUCCESS;
12061 	else
12062 		io->io_hdr.status = CTL_ERROR;
12063 	ctl_done(io);
12064 }
12065 
12066 /*
12067  * For HA operation.  Handle commands that come in from the other
12068  * controller.
12069  */
12070 static void
12071 ctl_handle_isc(union ctl_io *io)
12072 {
12073 	struct ctl_softc *softc = CTL_SOFTC(io);
12074 	struct ctl_lun *lun;
12075 	const struct ctl_cmd_entry *entry;
12076 	uint32_t targ_lun;
12077 
12078 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12079 	switch (io->io_hdr.msg_type) {
12080 	case CTL_MSG_SERIALIZE:
12081 		ctl_serialize_other_sc_cmd(&io->scsiio);
12082 		break;
12083 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12084 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12085 		if (targ_lun >= ctl_max_luns ||
12086 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12087 			ctl_done(io);
12088 			break;
12089 		}
12090 		mtx_lock(&lun->lun_lock);
12091 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12092 			mtx_unlock(&lun->lun_lock);
12093 			ctl_done(io);
12094 			break;
12095 		}
12096 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12097 		mtx_unlock(&lun->lun_lock);
12098 		ctl_enqueue_rtr(io);
12099 		break;
12100 	case CTL_MSG_FINISH_IO:
12101 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12102 			ctl_done(io);
12103 			break;
12104 		}
12105 		if (targ_lun >= ctl_max_luns ||
12106 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12107 			ctl_free_io(io);
12108 			break;
12109 		}
12110 		mtx_lock(&lun->lun_lock);
12111 		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12112 		ctl_check_blocked(lun);
12113 		mtx_unlock(&lun->lun_lock);
12114 		ctl_free_io(io);
12115 		break;
12116 	case CTL_MSG_PERS_ACTION:
12117 		ctl_hndl_per_res_out_on_other_sc(io);
12118 		ctl_free_io(io);
12119 		break;
12120 	case CTL_MSG_BAD_JUJU:
12121 		ctl_done(io);
12122 		break;
12123 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12124 		ctl_datamove_remote(io);
12125 		break;
12126 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12127 		io->scsiio.be_move_done(io);
12128 		break;
12129 	case CTL_MSG_FAILOVER:
12130 		ctl_failover_lun(io);
12131 		ctl_free_io(io);
12132 		break;
12133 	default:
12134 		printf("%s: Invalid message type %d\n",
12135 		       __func__, io->io_hdr.msg_type);
12136 		ctl_free_io(io);
12137 		break;
12138 	}
12139 
12140 }
12141 
12142 
12143 /*
12144  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12145  * there is no match.
12146  */
12147 static ctl_lun_error_pattern
12148 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12149 {
12150 	const struct ctl_cmd_entry *entry;
12151 	ctl_lun_error_pattern filtered_pattern, pattern;
12152 
12153 	pattern = desc->error_pattern;
12154 
12155 	/*
12156 	 * XXX KDM we need more data passed into this function to match a
12157 	 * custom pattern, and we actually need to implement custom pattern
12158 	 * matching.
12159 	 */
12160 	if (pattern & CTL_LUN_PAT_CMD)
12161 		return (CTL_LUN_PAT_CMD);
12162 
12163 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12164 		return (CTL_LUN_PAT_ANY);
12165 
12166 	entry = ctl_get_cmd_entry(ctsio, NULL);
12167 
12168 	filtered_pattern = entry->pattern & pattern;
12169 
12170 	/*
12171 	 * If the user requested specific flags in the pattern (e.g.
12172 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12173 	 * flags.
12174 	 *
12175 	 * If the user did not specify any flags, it doesn't matter whether
12176 	 * or not the command supports the flags.
12177 	 */
12178 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12179 	     (pattern & ~CTL_LUN_PAT_MASK))
12180 		return (CTL_LUN_PAT_NONE);
12181 
12182 	/*
12183 	 * If the user asked for a range check, see if the requested LBA
12184 	 * range overlaps with this command's LBA range.
12185 	 */
12186 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12187 		uint64_t lba1;
12188 		uint64_t len1;
12189 		ctl_action action;
12190 		int retval;
12191 
12192 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12193 		if (retval != 0)
12194 			return (CTL_LUN_PAT_NONE);
12195 
12196 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12197 					      desc->lba_range.len, FALSE);
12198 		/*
12199 		 * A "pass" means that the LBA ranges don't overlap, so
12200 		 * this doesn't match the user's range criteria.
12201 		 */
12202 		if (action == CTL_ACTION_PASS)
12203 			return (CTL_LUN_PAT_NONE);
12204 	}
12205 
12206 	return (filtered_pattern);
12207 }
12208 
12209 static void
12210 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12211 {
12212 	struct ctl_error_desc *desc, *desc2;
12213 
12214 	mtx_assert(&lun->lun_lock, MA_OWNED);
12215 
12216 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12217 		ctl_lun_error_pattern pattern;
12218 		/*
12219 		 * Check to see whether this particular command matches
12220 		 * the pattern in the descriptor.
12221 		 */
12222 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12223 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12224 			continue;
12225 
12226 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12227 		case CTL_LUN_INJ_ABORTED:
12228 			ctl_set_aborted(&io->scsiio);
12229 			break;
12230 		case CTL_LUN_INJ_MEDIUM_ERR:
12231 			ctl_set_medium_error(&io->scsiio,
12232 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12233 			     CTL_FLAG_DATA_OUT);
12234 			break;
12235 		case CTL_LUN_INJ_UA:
12236 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12237 			 * OCCURRED */
12238 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12239 			break;
12240 		case CTL_LUN_INJ_CUSTOM:
12241 			/*
12242 			 * We're assuming the user knows what he is doing.
12243 			 * Just copy the sense information without doing
12244 			 * checks.
12245 			 */
12246 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12247 			      MIN(sizeof(desc->custom_sense),
12248 				  sizeof(io->scsiio.sense_data)));
12249 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12250 			io->scsiio.sense_len = SSD_FULL_SIZE;
12251 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12252 			break;
12253 		case CTL_LUN_INJ_NONE:
12254 		default:
12255 			/*
12256 			 * If this is an error injection type we don't know
12257 			 * about, clear the continuous flag (if it is set)
12258 			 * so it will get deleted below.
12259 			 */
12260 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12261 			break;
12262 		}
12263 		/*
12264 		 * By default, each error injection action is a one-shot
12265 		 */
12266 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12267 			continue;
12268 
12269 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12270 
12271 		free(desc, M_CTL);
12272 	}
12273 }
12274 
12275 #ifdef CTL_IO_DELAY
12276 static void
12277 ctl_datamove_timer_wakeup(void *arg)
12278 {
12279 	union ctl_io *io;
12280 
12281 	io = (union ctl_io *)arg;
12282 
12283 	ctl_datamove(io);
12284 }
12285 #endif /* CTL_IO_DELAY */
12286 
12287 void
12288 ctl_datamove(union ctl_io *io)
12289 {
12290 	void (*fe_datamove)(union ctl_io *io);
12291 
12292 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12293 
12294 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12295 
12296 	/* No data transferred yet.  Frontend must update this when done. */
12297 	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12298 
12299 #ifdef CTL_TIME_IO
12300 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12301 		char str[256];
12302 		char path_str[64];
12303 		struct sbuf sb;
12304 
12305 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12306 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12307 
12308 		sbuf_cat(&sb, path_str);
12309 		switch (io->io_hdr.io_type) {
12310 		case CTL_IO_SCSI:
12311 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12312 			sbuf_printf(&sb, "\n");
12313 			sbuf_cat(&sb, path_str);
12314 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12315 				    io->scsiio.tag_num, io->scsiio.tag_type);
12316 			break;
12317 		case CTL_IO_TASK:
12318 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12319 				    "Tag Type: %d\n", io->taskio.task_action,
12320 				    io->taskio.tag_num, io->taskio.tag_type);
12321 			break;
12322 		default:
12323 			panic("%s: Invalid CTL I/O type %d\n",
12324 			    __func__, io->io_hdr.io_type);
12325 		}
12326 		sbuf_cat(&sb, path_str);
12327 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12328 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12329 		sbuf_finish(&sb);
12330 		printf("%s", sbuf_data(&sb));
12331 	}
12332 #endif /* CTL_TIME_IO */
12333 
12334 #ifdef CTL_IO_DELAY
12335 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12336 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12337 	} else {
12338 		struct ctl_lun *lun;
12339 
12340 		lun = CTL_LUN(io);
12341 		if ((lun != NULL)
12342 		 && (lun->delay_info.datamove_delay > 0)) {
12343 
12344 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12345 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12346 			callout_reset(&io->io_hdr.delay_callout,
12347 				      lun->delay_info.datamove_delay * hz,
12348 				      ctl_datamove_timer_wakeup, io);
12349 			if (lun->delay_info.datamove_type ==
12350 			    CTL_DELAY_TYPE_ONESHOT)
12351 				lun->delay_info.datamove_delay = 0;
12352 			return;
12353 		}
12354 	}
12355 #endif
12356 
12357 	/*
12358 	 * This command has been aborted.  Set the port status, so we fail
12359 	 * the data move.
12360 	 */
12361 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12362 		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12363 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12364 		       io->io_hdr.nexus.targ_port,
12365 		       io->io_hdr.nexus.targ_lun);
12366 		io->io_hdr.port_status = 31337;
12367 		/*
12368 		 * Note that the backend, in this case, will get the
12369 		 * callback in its context.  In other cases it may get
12370 		 * called in the frontend's interrupt thread context.
12371 		 */
12372 		io->scsiio.be_move_done(io);
12373 		return;
12374 	}
12375 
12376 	/* Don't confuse frontend with zero length data move. */
12377 	if (io->scsiio.kern_data_len == 0) {
12378 		io->scsiio.be_move_done(io);
12379 		return;
12380 	}
12381 
12382 	fe_datamove = CTL_PORT(io)->fe_datamove;
12383 	fe_datamove(io);
12384 }
12385 
12386 static void
12387 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12388 {
12389 	union ctl_ha_msg msg;
12390 #ifdef CTL_TIME_IO
12391 	struct bintime cur_bt;
12392 #endif
12393 
12394 	memset(&msg, 0, sizeof(msg));
12395 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12396 	msg.hdr.original_sc = io;
12397 	msg.hdr.serializing_sc = io->io_hdr.remote_io;
12398 	msg.hdr.nexus = io->io_hdr.nexus;
12399 	msg.hdr.status = io->io_hdr.status;
12400 	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12401 	msg.scsi.tag_num = io->scsiio.tag_num;
12402 	msg.scsi.tag_type = io->scsiio.tag_type;
12403 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12404 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12405 	       io->scsiio.sense_len);
12406 	msg.scsi.sense_len = io->scsiio.sense_len;
12407 	msg.scsi.port_status = io->io_hdr.port_status;
12408 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12409 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12410 		ctl_failover_io(io, /*have_lock*/ have_lock);
12411 		return;
12412 	}
12413 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12414 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12415 	    msg.scsi.sense_len, M_WAITOK);
12416 
12417 #ifdef CTL_TIME_IO
12418 	getbinuptime(&cur_bt);
12419 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12420 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12421 #endif
12422 	io->io_hdr.num_dmas++;
12423 }
12424 
12425 /*
12426  * The DMA to the remote side is done, now we need to tell the other side
12427  * we're done so it can continue with its data movement.
12428  */
12429 static void
12430 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12431 {
12432 	union ctl_io *io;
12433 	uint32_t i;
12434 
12435 	io = rq->context;
12436 
12437 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12438 		printf("%s: ISC DMA write failed with error %d", __func__,
12439 		       rq->ret);
12440 		ctl_set_internal_failure(&io->scsiio,
12441 					 /*sks_valid*/ 1,
12442 					 /*retry_count*/ rq->ret);
12443 	}
12444 
12445 	ctl_dt_req_free(rq);
12446 
12447 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12448 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12449 	free(CTL_RSGL(io), M_CTL);
12450 	CTL_RSGL(io) = NULL;
12451 	CTL_LSGL(io) = NULL;
12452 
12453 	/*
12454 	 * The data is in local and remote memory, so now we need to send
12455 	 * status (good or back) back to the other side.
12456 	 */
12457 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12458 }
12459 
12460 /*
12461  * We've moved the data from the host/controller into local memory.  Now we
12462  * need to push it over to the remote controller's memory.
12463  */
12464 static int
12465 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12466 {
12467 	int retval;
12468 
12469 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12470 					  ctl_datamove_remote_write_cb);
12471 	return (retval);
12472 }
12473 
12474 static void
12475 ctl_datamove_remote_write(union ctl_io *io)
12476 {
12477 	int retval;
12478 	void (*fe_datamove)(union ctl_io *io);
12479 
12480 	/*
12481 	 * - Get the data from the host/HBA into local memory.
12482 	 * - DMA memory from the local controller to the remote controller.
12483 	 * - Send status back to the remote controller.
12484 	 */
12485 
12486 	retval = ctl_datamove_remote_sgl_setup(io);
12487 	if (retval != 0)
12488 		return;
12489 
12490 	/* Switch the pointer over so the FETD knows what to do */
12491 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12492 
12493 	/*
12494 	 * Use a custom move done callback, since we need to send completion
12495 	 * back to the other controller, not to the backend on this side.
12496 	 */
12497 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12498 
12499 	fe_datamove = CTL_PORT(io)->fe_datamove;
12500 	fe_datamove(io);
12501 }
12502 
12503 static int
12504 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12505 {
12506 	uint32_t i;
12507 
12508 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12509 		free(CTL_LSGLT(io)[i].addr, M_CTL);
12510 	free(CTL_RSGL(io), M_CTL);
12511 	CTL_RSGL(io) = NULL;
12512 	CTL_LSGL(io) = NULL;
12513 
12514 	/*
12515 	 * The read is done, now we need to send status (good or bad) back
12516 	 * to the other side.
12517 	 */
12518 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12519 
12520 	return (0);
12521 }
12522 
12523 static void
12524 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12525 {
12526 	union ctl_io *io;
12527 	void (*fe_datamove)(union ctl_io *io);
12528 
12529 	io = rq->context;
12530 
12531 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12532 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12533 		       rq->ret);
12534 		ctl_set_internal_failure(&io->scsiio,
12535 					 /*sks_valid*/ 1,
12536 					 /*retry_count*/ rq->ret);
12537 	}
12538 
12539 	ctl_dt_req_free(rq);
12540 
12541 	/* Switch the pointer over so the FETD knows what to do */
12542 	io->scsiio.kern_data_ptr = (uint8_t *)CTL_LSGL(io);
12543 
12544 	/*
12545 	 * Use a custom move done callback, since we need to send completion
12546 	 * back to the other controller, not to the backend on this side.
12547 	 */
12548 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12549 
12550 	/* XXX KDM add checks like the ones in ctl_datamove? */
12551 
12552 	fe_datamove = CTL_PORT(io)->fe_datamove;
12553 	fe_datamove(io);
12554 }
12555 
12556 static int
12557 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12558 {
12559 	struct ctl_sg_entry *local_sglist;
12560 	uint32_t len_to_go;
12561 	int retval;
12562 	int i;
12563 
12564 	retval = 0;
12565 	local_sglist = CTL_LSGL(io);
12566 	len_to_go = io->scsiio.kern_data_len;
12567 
12568 	/*
12569 	 * The difficult thing here is that the size of the various
12570 	 * S/G segments may be different than the size from the
12571 	 * remote controller.  That'll make it harder when DMAing
12572 	 * the data back to the other side.
12573 	 */
12574 	for (i = 0; len_to_go > 0; i++) {
12575 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12576 		local_sglist[i].addr =
12577 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12578 
12579 		len_to_go -= local_sglist[i].len;
12580 	}
12581 	/*
12582 	 * Reset the number of S/G entries accordingly.  The original
12583 	 * number of S/G entries is available in rem_sg_entries.
12584 	 */
12585 	io->scsiio.kern_sg_entries = i;
12586 
12587 	return (retval);
12588 }
12589 
12590 static int
12591 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12592 			 ctl_ha_dt_cb callback)
12593 {
12594 	struct ctl_ha_dt_req *rq;
12595 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12596 	uint32_t local_used, remote_used, total_used;
12597 	int i, j, isc_ret;
12598 
12599 	rq = ctl_dt_req_alloc();
12600 
12601 	/*
12602 	 * If we failed to allocate the request, and if the DMA didn't fail
12603 	 * anyway, set busy status.  This is just a resource allocation
12604 	 * failure.
12605 	 */
12606 	if ((rq == NULL)
12607 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12608 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12609 		ctl_set_busy(&io->scsiio);
12610 
12611 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12612 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12613 
12614 		if (rq != NULL)
12615 			ctl_dt_req_free(rq);
12616 
12617 		/*
12618 		 * The data move failed.  We need to return status back
12619 		 * to the other controller.  No point in trying to DMA
12620 		 * data to the remote controller.
12621 		 */
12622 
12623 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12624 
12625 		return (1);
12626 	}
12627 
12628 	local_sglist = CTL_LSGL(io);
12629 	remote_sglist = CTL_RSGL(io);
12630 	local_used = 0;
12631 	remote_used = 0;
12632 	total_used = 0;
12633 
12634 	/*
12635 	 * Pull/push the data over the wire from/to the other controller.
12636 	 * This takes into account the possibility that the local and
12637 	 * remote sglists may not be identical in terms of the size of
12638 	 * the elements and the number of elements.
12639 	 *
12640 	 * One fundamental assumption here is that the length allocated for
12641 	 * both the local and remote sglists is identical.  Otherwise, we've
12642 	 * essentially got a coding error of some sort.
12643 	 */
12644 	isc_ret = CTL_HA_STATUS_SUCCESS;
12645 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12646 		uint32_t cur_len;
12647 		uint8_t *tmp_ptr;
12648 
12649 		rq->command = command;
12650 		rq->context = io;
12651 
12652 		/*
12653 		 * Both pointers should be aligned.  But it is possible
12654 		 * that the allocation length is not.  They should both
12655 		 * also have enough slack left over at the end, though,
12656 		 * to round up to the next 8 byte boundary.
12657 		 */
12658 		cur_len = MIN(local_sglist[i].len - local_used,
12659 			      remote_sglist[j].len - remote_used);
12660 		rq->size = cur_len;
12661 
12662 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12663 		tmp_ptr += local_used;
12664 
12665 #if 0
12666 		/* Use physical addresses when talking to ISC hardware */
12667 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12668 			/* XXX KDM use busdma */
12669 			rq->local = vtophys(tmp_ptr);
12670 		} else
12671 			rq->local = tmp_ptr;
12672 #else
12673 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12674 		    ("HA does not support BUS_ADDR"));
12675 		rq->local = tmp_ptr;
12676 #endif
12677 
12678 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12679 		tmp_ptr += remote_used;
12680 		rq->remote = tmp_ptr;
12681 
12682 		rq->callback = NULL;
12683 
12684 		local_used += cur_len;
12685 		if (local_used >= local_sglist[i].len) {
12686 			i++;
12687 			local_used = 0;
12688 		}
12689 
12690 		remote_used += cur_len;
12691 		if (remote_used >= remote_sglist[j].len) {
12692 			j++;
12693 			remote_used = 0;
12694 		}
12695 		total_used += cur_len;
12696 
12697 		if (total_used >= io->scsiio.kern_data_len)
12698 			rq->callback = callback;
12699 
12700 		isc_ret = ctl_dt_single(rq);
12701 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12702 			break;
12703 	}
12704 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12705 		rq->ret = isc_ret;
12706 		callback(rq);
12707 	}
12708 
12709 	return (0);
12710 }
12711 
12712 static void
12713 ctl_datamove_remote_read(union ctl_io *io)
12714 {
12715 	int retval;
12716 	uint32_t i;
12717 
12718 	/*
12719 	 * This will send an error to the other controller in the case of a
12720 	 * failure.
12721 	 */
12722 	retval = ctl_datamove_remote_sgl_setup(io);
12723 	if (retval != 0)
12724 		return;
12725 
12726 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12727 					  ctl_datamove_remote_read_cb);
12728 	if (retval != 0) {
12729 		/*
12730 		 * Make sure we free memory if there was an error..  The
12731 		 * ctl_datamove_remote_xfer() function will send the
12732 		 * datamove done message, or call the callback with an
12733 		 * error if there is a problem.
12734 		 */
12735 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12736 			free(CTL_LSGLT(io)[i].addr, M_CTL);
12737 		free(CTL_RSGL(io), M_CTL);
12738 		CTL_RSGL(io) = NULL;
12739 		CTL_LSGL(io) = NULL;
12740 	}
12741 }
12742 
12743 /*
12744  * Process a datamove request from the other controller.  This is used for
12745  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12746  * first.  Once that is complete, the data gets DMAed into the remote
12747  * controller's memory.  For reads, we DMA from the remote controller's
12748  * memory into our memory first, and then move it out to the FETD.
12749  */
12750 static void
12751 ctl_datamove_remote(union ctl_io *io)
12752 {
12753 
12754 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12755 
12756 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12757 		ctl_failover_io(io, /*have_lock*/ 0);
12758 		return;
12759 	}
12760 
12761 	/*
12762 	 * Note that we look for an aborted I/O here, but don't do some of
12763 	 * the other checks that ctl_datamove() normally does.
12764 	 * We don't need to run the datamove delay code, since that should
12765 	 * have been done if need be on the other controller.
12766 	 */
12767 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12768 		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12769 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12770 		       io->io_hdr.nexus.targ_port,
12771 		       io->io_hdr.nexus.targ_lun);
12772 		io->io_hdr.port_status = 31338;
12773 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12774 		return;
12775 	}
12776 
12777 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12778 		ctl_datamove_remote_write(io);
12779 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12780 		ctl_datamove_remote_read(io);
12781 	else {
12782 		io->io_hdr.port_status = 31339;
12783 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12784 	}
12785 }
12786 
12787 static void
12788 ctl_process_done(union ctl_io *io)
12789 {
12790 	struct ctl_softc *softc = CTL_SOFTC(io);
12791 	struct ctl_port *port = CTL_PORT(io);
12792 	struct ctl_lun *lun = CTL_LUN(io);
12793 	void (*fe_done)(union ctl_io *io);
12794 	union ctl_ha_msg msg;
12795 
12796 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12797 	fe_done = port->fe_done;
12798 
12799 #ifdef CTL_TIME_IO
12800 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12801 		char str[256];
12802 		char path_str[64];
12803 		struct sbuf sb;
12804 
12805 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12806 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12807 
12808 		sbuf_cat(&sb, path_str);
12809 		switch (io->io_hdr.io_type) {
12810 		case CTL_IO_SCSI:
12811 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12812 			sbuf_printf(&sb, "\n");
12813 			sbuf_cat(&sb, path_str);
12814 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12815 				    io->scsiio.tag_num, io->scsiio.tag_type);
12816 			break;
12817 		case CTL_IO_TASK:
12818 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12819 				    "Tag Type: %d\n", io->taskio.task_action,
12820 				    io->taskio.tag_num, io->taskio.tag_type);
12821 			break;
12822 		default:
12823 			panic("%s: Invalid CTL I/O type %d\n",
12824 			    __func__, io->io_hdr.io_type);
12825 		}
12826 		sbuf_cat(&sb, path_str);
12827 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12828 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12829 		sbuf_finish(&sb);
12830 		printf("%s", sbuf_data(&sb));
12831 	}
12832 #endif /* CTL_TIME_IO */
12833 
12834 	switch (io->io_hdr.io_type) {
12835 	case CTL_IO_SCSI:
12836 		break;
12837 	case CTL_IO_TASK:
12838 		if (ctl_debug & CTL_DEBUG_INFO)
12839 			ctl_io_error_print(io, NULL);
12840 		fe_done(io);
12841 		return;
12842 	default:
12843 		panic("%s: Invalid CTL I/O type %d\n",
12844 		    __func__, io->io_hdr.io_type);
12845 	}
12846 
12847 	if (lun == NULL) {
12848 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12849 				 io->io_hdr.nexus.targ_mapped_lun));
12850 		goto bailout;
12851 	}
12852 
12853 	mtx_lock(&lun->lun_lock);
12854 
12855 	/*
12856 	 * Check to see if we have any informational exception and status
12857 	 * of this command can be modified to report it in form of either
12858 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
12859 	 */
12860 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
12861 	    io->io_hdr.status == CTL_SUCCESS &&
12862 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
12863 		uint8_t mrie = lun->MODE_IE.mrie;
12864 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
12865 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
12866 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
12867 		     mrie == SIEP_MRIE_REC_UNCOND ||
12868 		     mrie == SIEP_MRIE_NO_SENSE) &&
12869 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
12870 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
12871 			ctl_set_sense(&io->scsiio,
12872 			      /*current_error*/ 1,
12873 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
12874 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
12875 			      /*asc*/ lun->ie_asc,
12876 			      /*ascq*/ lun->ie_ascq,
12877 			      SSD_ELEM_NONE);
12878 			lun->ie_reported = 1;
12879 		}
12880 	} else if (lun->ie_reported < 0)
12881 		lun->ie_reported = 0;
12882 
12883 	/*
12884 	 * Check to see if we have any errors to inject here.  We only
12885 	 * inject errors for commands that don't already have errors set.
12886 	 */
12887 	if (!STAILQ_EMPTY(&lun->error_list) &&
12888 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
12889 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
12890 		ctl_inject_error(lun, io);
12891 
12892 	/*
12893 	 * XXX KDM how do we treat commands that aren't completed
12894 	 * successfully?
12895 	 *
12896 	 * XXX KDM should we also track I/O latency?
12897 	 */
12898 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
12899 	    io->io_hdr.io_type == CTL_IO_SCSI) {
12900 		int type;
12901 #ifdef CTL_TIME_IO
12902 		struct bintime bt;
12903 
12904 		getbinuptime(&bt);
12905 		bintime_sub(&bt, &io->io_hdr.start_bt);
12906 #endif
12907 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12908 		    CTL_FLAG_DATA_IN)
12909 			type = CTL_STATS_READ;
12910 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
12911 		    CTL_FLAG_DATA_OUT)
12912 			type = CTL_STATS_WRITE;
12913 		else
12914 			type = CTL_STATS_NO_IO;
12915 
12916 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
12917 		lun->stats.operations[type] ++;
12918 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
12919 #ifdef CTL_TIME_IO
12920 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
12921 		bintime_add(&lun->stats.time[type], &bt);
12922 #endif
12923 
12924 		mtx_lock(&port->port_lock);
12925 		port->stats.bytes[type] += io->scsiio.kern_total_len;
12926 		port->stats.operations[type] ++;
12927 		port->stats.dmas[type] += io->io_hdr.num_dmas;
12928 #ifdef CTL_TIME_IO
12929 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
12930 		bintime_add(&port->stats.time[type], &bt);
12931 #endif
12932 		mtx_unlock(&port->port_lock);
12933 	}
12934 
12935 	/*
12936 	 * Remove this from the OOA queue.
12937 	 */
12938 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12939 #ifdef CTL_TIME_IO
12940 	if (TAILQ_EMPTY(&lun->ooa_queue))
12941 		lun->last_busy = getsbinuptime();
12942 #endif
12943 
12944 	/*
12945 	 * Run through the blocked queue on this LUN and see if anything
12946 	 * has become unblocked, now that this transaction is done.
12947 	 */
12948 	ctl_check_blocked(lun);
12949 
12950 	/*
12951 	 * If the LUN has been invalidated, free it if there is nothing
12952 	 * left on its OOA queue.
12953 	 */
12954 	if ((lun->flags & CTL_LUN_INVALID)
12955 	 && TAILQ_EMPTY(&lun->ooa_queue)) {
12956 		mtx_unlock(&lun->lun_lock);
12957 		ctl_free_lun(lun);
12958 	} else
12959 		mtx_unlock(&lun->lun_lock);
12960 
12961 bailout:
12962 
12963 	/*
12964 	 * If this command has been aborted, make sure we set the status
12965 	 * properly.  The FETD is responsible for freeing the I/O and doing
12966 	 * whatever it needs to do to clean up its state.
12967 	 */
12968 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
12969 		ctl_set_task_aborted(&io->scsiio);
12970 
12971 	/*
12972 	 * If enabled, print command error status.
12973 	 */
12974 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
12975 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
12976 		ctl_io_error_print(io, NULL);
12977 
12978 	/*
12979 	 * Tell the FETD or the other shelf controller we're done with this
12980 	 * command.  Note that only SCSI commands get to this point.  Task
12981 	 * management commands are completed above.
12982 	 */
12983 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
12984 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
12985 		memset(&msg, 0, sizeof(msg));
12986 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
12987 		msg.hdr.serializing_sc = io->io_hdr.remote_io;
12988 		msg.hdr.nexus = io->io_hdr.nexus;
12989 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12990 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
12991 		    M_WAITOK);
12992 	}
12993 
12994 	fe_done(io);
12995 }
12996 
12997 /*
12998  * Front end should call this if it doesn't do autosense.  When the request
12999  * sense comes back in from the initiator, we'll dequeue this and send it.
13000  */
13001 int
13002 ctl_queue_sense(union ctl_io *io)
13003 {
13004 	struct ctl_softc *softc = CTL_SOFTC(io);
13005 	struct ctl_port *port = CTL_PORT(io);
13006 	struct ctl_lun *lun;
13007 	struct scsi_sense_data *ps;
13008 	uint32_t initidx, p, targ_lun;
13009 
13010 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13011 
13012 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13013 
13014 	/*
13015 	 * LUN lookup will likely move to the ctl_work_thread() once we
13016 	 * have our new queueing infrastructure (that doesn't put things on
13017 	 * a per-LUN queue initially).  That is so that we can handle
13018 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13019 	 * can't deal with that right now.
13020 	 * If we don't have a LUN for this, just toss the sense information.
13021 	 */
13022 	mtx_lock(&softc->ctl_lock);
13023 	if (targ_lun >= ctl_max_luns ||
13024 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13025 		mtx_unlock(&softc->ctl_lock);
13026 		goto bailout;
13027 	}
13028 	mtx_lock(&lun->lun_lock);
13029 	mtx_unlock(&softc->ctl_lock);
13030 
13031 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13032 	p = initidx / CTL_MAX_INIT_PER_PORT;
13033 	if (lun->pending_sense[p] == NULL) {
13034 		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13035 		    M_CTL, M_NOWAIT | M_ZERO);
13036 	}
13037 	if ((ps = lun->pending_sense[p]) != NULL) {
13038 		ps += initidx % CTL_MAX_INIT_PER_PORT;
13039 		memset(ps, 0, sizeof(*ps));
13040 		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13041 	}
13042 	mtx_unlock(&lun->lun_lock);
13043 
13044 bailout:
13045 	ctl_free_io(io);
13046 	return (CTL_RETVAL_COMPLETE);
13047 }
13048 
13049 /*
13050  * Primary command inlet from frontend ports.  All SCSI and task I/O
13051  * requests must go through this function.
13052  */
13053 int
13054 ctl_queue(union ctl_io *io)
13055 {
13056 	struct ctl_port *port = CTL_PORT(io);
13057 
13058 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13059 
13060 #ifdef CTL_TIME_IO
13061 	io->io_hdr.start_time = time_uptime;
13062 	getbinuptime(&io->io_hdr.start_bt);
13063 #endif /* CTL_TIME_IO */
13064 
13065 	/* Map FE-specific LUN ID into global one. */
13066 	io->io_hdr.nexus.targ_mapped_lun =
13067 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13068 
13069 	switch (io->io_hdr.io_type) {
13070 	case CTL_IO_SCSI:
13071 	case CTL_IO_TASK:
13072 		if (ctl_debug & CTL_DEBUG_CDB)
13073 			ctl_io_print(io);
13074 		ctl_enqueue_incoming(io);
13075 		break;
13076 	default:
13077 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13078 		return (EINVAL);
13079 	}
13080 
13081 	return (CTL_RETVAL_COMPLETE);
13082 }
13083 
13084 #ifdef CTL_IO_DELAY
13085 static void
13086 ctl_done_timer_wakeup(void *arg)
13087 {
13088 	union ctl_io *io;
13089 
13090 	io = (union ctl_io *)arg;
13091 	ctl_done(io);
13092 }
13093 #endif /* CTL_IO_DELAY */
13094 
13095 void
13096 ctl_serseq_done(union ctl_io *io)
13097 {
13098 	struct ctl_lun *lun = CTL_LUN(io);;
13099 
13100 	if (lun->be_lun == NULL ||
13101 	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13102 		return;
13103 	mtx_lock(&lun->lun_lock);
13104 	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13105 	ctl_check_blocked(lun);
13106 	mtx_unlock(&lun->lun_lock);
13107 }
13108 
13109 void
13110 ctl_done(union ctl_io *io)
13111 {
13112 
13113 	/*
13114 	 * Enable this to catch duplicate completion issues.
13115 	 */
13116 #if 0
13117 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13118 		printf("%s: type %d msg %d cdb %x iptl: "
13119 		       "%u:%u:%u tag 0x%04x "
13120 		       "flag %#x status %x\n",
13121 			__func__,
13122 			io->io_hdr.io_type,
13123 			io->io_hdr.msg_type,
13124 			io->scsiio.cdb[0],
13125 			io->io_hdr.nexus.initid,
13126 			io->io_hdr.nexus.targ_port,
13127 			io->io_hdr.nexus.targ_lun,
13128 			(io->io_hdr.io_type ==
13129 			CTL_IO_TASK) ?
13130 			io->taskio.tag_num :
13131 			io->scsiio.tag_num,
13132 		        io->io_hdr.flags,
13133 			io->io_hdr.status);
13134 	} else
13135 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13136 #endif
13137 
13138 	/*
13139 	 * This is an internal copy of an I/O, and should not go through
13140 	 * the normal done processing logic.
13141 	 */
13142 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13143 		return;
13144 
13145 #ifdef CTL_IO_DELAY
13146 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13147 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13148 	} else {
13149 		struct ctl_lun *lun = CTL_LUN(io);
13150 
13151 		if ((lun != NULL)
13152 		 && (lun->delay_info.done_delay > 0)) {
13153 
13154 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13155 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13156 			callout_reset(&io->io_hdr.delay_callout,
13157 				      lun->delay_info.done_delay * hz,
13158 				      ctl_done_timer_wakeup, io);
13159 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13160 				lun->delay_info.done_delay = 0;
13161 			return;
13162 		}
13163 	}
13164 #endif /* CTL_IO_DELAY */
13165 
13166 	ctl_enqueue_done(io);
13167 }
13168 
13169 static void
13170 ctl_work_thread(void *arg)
13171 {
13172 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13173 	struct ctl_softc *softc = thr->ctl_softc;
13174 	union ctl_io *io;
13175 	int retval;
13176 
13177 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13178 
13179 	while (!softc->shutdown) {
13180 		/*
13181 		 * We handle the queues in this order:
13182 		 * - ISC
13183 		 * - done queue (to free up resources, unblock other commands)
13184 		 * - incoming queue
13185 		 * - RtR queue
13186 		 *
13187 		 * If those queues are empty, we break out of the loop and
13188 		 * go to sleep.
13189 		 */
13190 		mtx_lock(&thr->queue_lock);
13191 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13192 		if (io != NULL) {
13193 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13194 			mtx_unlock(&thr->queue_lock);
13195 			ctl_handle_isc(io);
13196 			continue;
13197 		}
13198 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13199 		if (io != NULL) {
13200 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13201 			/* clear any blocked commands, call fe_done */
13202 			mtx_unlock(&thr->queue_lock);
13203 			ctl_process_done(io);
13204 			continue;
13205 		}
13206 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13207 		if (io != NULL) {
13208 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13209 			mtx_unlock(&thr->queue_lock);
13210 			if (io->io_hdr.io_type == CTL_IO_TASK)
13211 				ctl_run_task(io);
13212 			else
13213 				ctl_scsiio_precheck(softc, &io->scsiio);
13214 			continue;
13215 		}
13216 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13217 		if (io != NULL) {
13218 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13219 			mtx_unlock(&thr->queue_lock);
13220 			retval = ctl_scsiio(&io->scsiio);
13221 			if (retval != CTL_RETVAL_COMPLETE)
13222 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13223 			continue;
13224 		}
13225 
13226 		/* Sleep until we have something to do. */
13227 		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13228 	}
13229 	thr->thread = NULL;
13230 	kthread_exit();
13231 }
13232 
13233 static void
13234 ctl_lun_thread(void *arg)
13235 {
13236 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13237 	struct ctl_be_lun *be_lun;
13238 
13239 	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13240 
13241 	while (!softc->shutdown) {
13242 		mtx_lock(&softc->ctl_lock);
13243 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13244 		if (be_lun != NULL) {
13245 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13246 			mtx_unlock(&softc->ctl_lock);
13247 			ctl_create_lun(be_lun);
13248 			continue;
13249 		}
13250 
13251 		/* Sleep until we have something to do. */
13252 		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13253 		    PDROP | PRIBIO, "-", 0);
13254 	}
13255 	softc->lun_thread = NULL;
13256 	kthread_exit();
13257 }
13258 
13259 static void
13260 ctl_thresh_thread(void *arg)
13261 {
13262 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13263 	struct ctl_lun *lun;
13264 	struct ctl_logical_block_provisioning_page *page;
13265 	const char *attr;
13266 	union ctl_ha_msg msg;
13267 	uint64_t thres, val;
13268 	int i, e, set;
13269 
13270 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13271 
13272 	while (!softc->shutdown) {
13273 		mtx_lock(&softc->ctl_lock);
13274 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13275 			if ((lun->flags & CTL_LUN_DISABLED) ||
13276 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13277 			    lun->backend->lun_attr == NULL)
13278 				continue;
13279 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13280 			    softc->ha_mode == CTL_HA_MODE_XFER)
13281 				continue;
13282 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13283 				continue;
13284 			e = 0;
13285 			page = &lun->MODE_LBP;
13286 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13287 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13288 					continue;
13289 				thres = scsi_4btoul(page->descr[i].count);
13290 				thres <<= CTL_LBP_EXPONENT;
13291 				switch (page->descr[i].resource) {
13292 				case 0x01:
13293 					attr = "blocksavail";
13294 					break;
13295 				case 0x02:
13296 					attr = "blocksused";
13297 					break;
13298 				case 0xf1:
13299 					attr = "poolblocksavail";
13300 					break;
13301 				case 0xf2:
13302 					attr = "poolblocksused";
13303 					break;
13304 				default:
13305 					continue;
13306 				}
13307 				mtx_unlock(&softc->ctl_lock); // XXX
13308 				val = lun->backend->lun_attr(
13309 				    lun->be_lun->be_lun, attr);
13310 				mtx_lock(&softc->ctl_lock);
13311 				if (val == UINT64_MAX)
13312 					continue;
13313 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13314 				    == SLBPPD_ARMING_INC)
13315 					e = (val >= thres);
13316 				else
13317 					e = (val <= thres);
13318 				if (e)
13319 					break;
13320 			}
13321 			mtx_lock(&lun->lun_lock);
13322 			if (e) {
13323 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13324 				    (uint8_t *)page, lun->ua_tpt_info);
13325 				if (lun->lasttpt == 0 ||
13326 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13327 					lun->lasttpt = time_uptime;
13328 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13329 					set = 1;
13330 				} else
13331 					set = 0;
13332 			} else {
13333 				lun->lasttpt = 0;
13334 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13335 				set = -1;
13336 			}
13337 			mtx_unlock(&lun->lun_lock);
13338 			if (set != 0 &&
13339 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13340 				/* Send msg to other side. */
13341 				bzero(&msg.ua, sizeof(msg.ua));
13342 				msg.hdr.msg_type = CTL_MSG_UA;
13343 				msg.hdr.nexus.initid = -1;
13344 				msg.hdr.nexus.targ_port = -1;
13345 				msg.hdr.nexus.targ_lun = lun->lun;
13346 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13347 				msg.ua.ua_all = 1;
13348 				msg.ua.ua_set = (set > 0);
13349 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13350 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13351 				mtx_unlock(&softc->ctl_lock); // XXX
13352 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13353 				    sizeof(msg.ua), M_WAITOK);
13354 				mtx_lock(&softc->ctl_lock);
13355 			}
13356 		}
13357 		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13358 		    PDROP | PRIBIO, "-", CTL_LBP_PERIOD * hz);
13359 	}
13360 	softc->thresh_thread = NULL;
13361 	kthread_exit();
13362 }
13363 
13364 static void
13365 ctl_enqueue_incoming(union ctl_io *io)
13366 {
13367 	struct ctl_softc *softc = CTL_SOFTC(io);
13368 	struct ctl_thread *thr;
13369 	u_int idx;
13370 
13371 	idx = (io->io_hdr.nexus.targ_port * 127 +
13372 	       io->io_hdr.nexus.initid) % worker_threads;
13373 	thr = &softc->threads[idx];
13374 	mtx_lock(&thr->queue_lock);
13375 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13376 	mtx_unlock(&thr->queue_lock);
13377 	wakeup(thr);
13378 }
13379 
13380 static void
13381 ctl_enqueue_rtr(union ctl_io *io)
13382 {
13383 	struct ctl_softc *softc = CTL_SOFTC(io);
13384 	struct ctl_thread *thr;
13385 
13386 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13387 	mtx_lock(&thr->queue_lock);
13388 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13389 	mtx_unlock(&thr->queue_lock);
13390 	wakeup(thr);
13391 }
13392 
13393 static void
13394 ctl_enqueue_done(union ctl_io *io)
13395 {
13396 	struct ctl_softc *softc = CTL_SOFTC(io);
13397 	struct ctl_thread *thr;
13398 
13399 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13400 	mtx_lock(&thr->queue_lock);
13401 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13402 	mtx_unlock(&thr->queue_lock);
13403 	wakeup(thr);
13404 }
13405 
13406 static void
13407 ctl_enqueue_isc(union ctl_io *io)
13408 {
13409 	struct ctl_softc *softc = CTL_SOFTC(io);
13410 	struct ctl_thread *thr;
13411 
13412 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13413 	mtx_lock(&thr->queue_lock);
13414 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13415 	mtx_unlock(&thr->queue_lock);
13416 	wakeup(thr);
13417 }
13418 
13419 /*
13420  *  vim: ts=8
13421  */
13422