xref: /freebsd/sys/cam/ctl/ctl.c (revision b08fc26cbdd00df6852e71e1be58fa9cc92019f0)
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * Copyright (c) 2014-2017 Alexander Motin <mav@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Portions of this software were developed by Edward Tomasz Napierala
8  * under sponsorship from the FreeBSD Foundation.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification.
16  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17  *    substantially similar to the "NO WARRANTY" disclaimer below
18  *    ("Disclaimer") and any redistribution must be conditioned upon
19  *    including a substantially similar Disclaimer requirement for further
20  *    binary redistribution.
21  *
22  * NO WARRANTY
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
31  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
32  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGES.
34  *
35  * $Id$
36  */
37 /*
38  * CAM Target Layer, a SCSI device emulation subsystem.
39  *
40  * Author: Ken Merry <ken@FreeBSD.org>
41  */
42 
43 #define _CTL_C
44 
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47 
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/ctype.h>
51 #include <sys/kernel.h>
52 #include <sys/types.h>
53 #include <sys/kthread.h>
54 #include <sys/bio.h>
55 #include <sys/fcntl.h>
56 #include <sys/lock.h>
57 #include <sys/module.h>
58 #include <sys/mutex.h>
59 #include <sys/condvar.h>
60 #include <sys/malloc.h>
61 #include <sys/conf.h>
62 #include <sys/ioccom.h>
63 #include <sys/queue.h>
64 #include <sys/sbuf.h>
65 #include <sys/smp.h>
66 #include <sys/endian.h>
67 #include <sys/sysctl.h>
68 #include <vm/uma.h>
69 
70 #include <cam/cam.h>
71 #include <cam/scsi/scsi_all.h>
72 #include <cam/scsi/scsi_cd.h>
73 #include <cam/scsi/scsi_da.h>
74 #include <cam/ctl/ctl_io.h>
75 #include <cam/ctl/ctl.h>
76 #include <cam/ctl/ctl_frontend.h>
77 #include <cam/ctl/ctl_util.h>
78 #include <cam/ctl/ctl_backend.h>
79 #include <cam/ctl/ctl_ioctl.h>
80 #include <cam/ctl/ctl_ha.h>
81 #include <cam/ctl/ctl_private.h>
82 #include <cam/ctl/ctl_debug.h>
83 #include <cam/ctl/ctl_scsi_all.h>
84 #include <cam/ctl/ctl_error.h>
85 
86 struct ctl_softc *control_softc = NULL;
87 
88 /*
89  * Template mode pages.
90  */
91 
92 /*
93  * Note that these are default values only.  The actual values will be
94  * filled in when the user does a mode sense.
95  */
96 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
97 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
98 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
99 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
100 	/*read_retry_count*/0,
101 	/*correction_span*/0,
102 	/*head_offset_count*/0,
103 	/*data_strobe_offset_cnt*/0,
104 	/*byte8*/SMS_RWER_LBPERE,
105 	/*write_retry_count*/0,
106 	/*reserved2*/0,
107 	/*recovery_time_limit*/{0, 0},
108 };
109 
110 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
111 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
112 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
113 	/*byte3*/SMS_RWER_PER,
114 	/*read_retry_count*/0,
115 	/*correction_span*/0,
116 	/*head_offset_count*/0,
117 	/*data_strobe_offset_cnt*/0,
118 	/*byte8*/SMS_RWER_LBPERE,
119 	/*write_retry_count*/0,
120 	/*reserved2*/0,
121 	/*recovery_time_limit*/{0, 0},
122 };
123 
124 const static struct scsi_format_page format_page_default = {
125 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
126 	/*page_length*/sizeof(struct scsi_format_page) - 2,
127 	/*tracks_per_zone*/ {0, 0},
128 	/*alt_sectors_per_zone*/ {0, 0},
129 	/*alt_tracks_per_zone*/ {0, 0},
130 	/*alt_tracks_per_lun*/ {0, 0},
131 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
132 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
133 	/*bytes_per_sector*/ {0, 0},
134 	/*interleave*/ {0, 0},
135 	/*track_skew*/ {0, 0},
136 	/*cylinder_skew*/ {0, 0},
137 	/*flags*/ SFP_HSEC,
138 	/*reserved*/ {0, 0, 0}
139 };
140 
141 const static struct scsi_format_page format_page_changeable = {
142 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
143 	/*page_length*/sizeof(struct scsi_format_page) - 2,
144 	/*tracks_per_zone*/ {0, 0},
145 	/*alt_sectors_per_zone*/ {0, 0},
146 	/*alt_tracks_per_zone*/ {0, 0},
147 	/*alt_tracks_per_lun*/ {0, 0},
148 	/*sectors_per_track*/ {0, 0},
149 	/*bytes_per_sector*/ {0, 0},
150 	/*interleave*/ {0, 0},
151 	/*track_skew*/ {0, 0},
152 	/*cylinder_skew*/ {0, 0},
153 	/*flags*/ 0,
154 	/*reserved*/ {0, 0, 0}
155 };
156 
157 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
158 	/*page_code*/SMS_RIGID_DISK_PAGE,
159 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
160 	/*cylinders*/ {0, 0, 0},
161 	/*heads*/ CTL_DEFAULT_HEADS,
162 	/*start_write_precomp*/ {0, 0, 0},
163 	/*start_reduced_current*/ {0, 0, 0},
164 	/*step_rate*/ {0, 0},
165 	/*landing_zone_cylinder*/ {0, 0, 0},
166 	/*rpl*/ SRDP_RPL_DISABLED,
167 	/*rotational_offset*/ 0,
168 	/*reserved1*/ 0,
169 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
170 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
171 	/*reserved2*/ {0, 0}
172 };
173 
174 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
175 	/*page_code*/SMS_RIGID_DISK_PAGE,
176 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
177 	/*cylinders*/ {0, 0, 0},
178 	/*heads*/ 0,
179 	/*start_write_precomp*/ {0, 0, 0},
180 	/*start_reduced_current*/ {0, 0, 0},
181 	/*step_rate*/ {0, 0},
182 	/*landing_zone_cylinder*/ {0, 0, 0},
183 	/*rpl*/ 0,
184 	/*rotational_offset*/ 0,
185 	/*reserved1*/ 0,
186 	/*rotation_rate*/ {0, 0},
187 	/*reserved2*/ {0, 0}
188 };
189 
190 const static struct scsi_da_verify_recovery_page verify_er_page_default = {
191 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
192 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
193 	/*byte3*/0,
194 	/*read_retry_count*/0,
195 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
196 	/*recovery_time_limit*/{0, 0},
197 };
198 
199 const static struct scsi_da_verify_recovery_page verify_er_page_changeable = {
200 	/*page_code*/SMS_VERIFY_ERROR_RECOVERY_PAGE,
201 	/*page_length*/sizeof(struct scsi_da_verify_recovery_page) - 2,
202 	/*byte3*/SMS_VER_PER,
203 	/*read_retry_count*/0,
204 	/*reserved*/{ 0, 0, 0, 0, 0, 0 },
205 	/*recovery_time_limit*/{0, 0},
206 };
207 
208 const static struct scsi_caching_page caching_page_default = {
209 	/*page_code*/SMS_CACHING_PAGE,
210 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
211 	/*flags1*/ SCP_DISC | SCP_WCE,
212 	/*ret_priority*/ 0,
213 	/*disable_pf_transfer_len*/ {0xff, 0xff},
214 	/*min_prefetch*/ {0, 0},
215 	/*max_prefetch*/ {0xff, 0xff},
216 	/*max_pf_ceiling*/ {0xff, 0xff},
217 	/*flags2*/ 0,
218 	/*cache_segments*/ 0,
219 	/*cache_seg_size*/ {0, 0},
220 	/*reserved*/ 0,
221 	/*non_cache_seg_size*/ {0, 0, 0}
222 };
223 
224 const static struct scsi_caching_page caching_page_changeable = {
225 	/*page_code*/SMS_CACHING_PAGE,
226 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
227 	/*flags1*/ SCP_WCE | SCP_RCD,
228 	/*ret_priority*/ 0,
229 	/*disable_pf_transfer_len*/ {0, 0},
230 	/*min_prefetch*/ {0, 0},
231 	/*max_prefetch*/ {0, 0},
232 	/*max_pf_ceiling*/ {0, 0},
233 	/*flags2*/ 0,
234 	/*cache_segments*/ 0,
235 	/*cache_seg_size*/ {0, 0},
236 	/*reserved*/ 0,
237 	/*non_cache_seg_size*/ {0, 0, 0}
238 };
239 
240 const static struct scsi_control_page control_page_default = {
241 	/*page_code*/SMS_CONTROL_MODE_PAGE,
242 	/*page_length*/sizeof(struct scsi_control_page) - 2,
243 	/*rlec*/0,
244 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
245 	/*eca_and_aen*/0,
246 	/*flags4*/SCP_TAS,
247 	/*aen_holdoff_period*/{0, 0},
248 	/*busy_timeout_period*/{0, 0},
249 	/*extended_selftest_completion_time*/{0, 0}
250 };
251 
252 const static struct scsi_control_page control_page_changeable = {
253 	/*page_code*/SMS_CONTROL_MODE_PAGE,
254 	/*page_length*/sizeof(struct scsi_control_page) - 2,
255 	/*rlec*/SCP_DSENSE,
256 	/*queue_flags*/SCP_QUEUE_ALG_MASK | SCP_NUAR,
257 	/*eca_and_aen*/SCP_SWP,
258 	/*flags4*/0,
259 	/*aen_holdoff_period*/{0, 0},
260 	/*busy_timeout_period*/{0, 0},
261 	/*extended_selftest_completion_time*/{0, 0}
262 };
263 
264 #define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
265 
266 const static struct scsi_control_ext_page control_ext_page_default = {
267 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
268 	/*subpage_code*/0x01,
269 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
270 	/*flags*/0,
271 	/*prio*/0,
272 	/*max_sense*/0
273 };
274 
275 const static struct scsi_control_ext_page control_ext_page_changeable = {
276 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
277 	/*subpage_code*/0x01,
278 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
279 	/*flags*/0,
280 	/*prio*/0,
281 	/*max_sense*/0xff
282 };
283 
284 const static struct scsi_info_exceptions_page ie_page_default = {
285 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
286 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
287 	/*info_flags*/SIEP_FLAGS_EWASC,
288 	/*mrie*/SIEP_MRIE_NO,
289 	/*interval_timer*/{0, 0, 0, 0},
290 	/*report_count*/{0, 0, 0, 1}
291 };
292 
293 const static struct scsi_info_exceptions_page ie_page_changeable = {
294 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
295 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
296 	/*info_flags*/SIEP_FLAGS_EWASC | SIEP_FLAGS_DEXCPT | SIEP_FLAGS_TEST |
297 	    SIEP_FLAGS_LOGERR,
298 	/*mrie*/0x0f,
299 	/*interval_timer*/{0xff, 0xff, 0xff, 0xff},
300 	/*report_count*/{0xff, 0xff, 0xff, 0xff}
301 };
302 
303 #define CTL_LBPM_LEN	(sizeof(struct ctl_logical_block_provisioning_page) - 4)
304 
305 const static struct ctl_logical_block_provisioning_page lbp_page_default = {{
306 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
307 	/*subpage_code*/0x02,
308 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
309 	/*flags*/0,
310 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
311 	/*descr*/{}},
312 	{{/*flags*/0,
313 	  /*resource*/0x01,
314 	  /*reserved*/{0, 0},
315 	  /*count*/{0, 0, 0, 0}},
316 	 {/*flags*/0,
317 	  /*resource*/0x02,
318 	  /*reserved*/{0, 0},
319 	  /*count*/{0, 0, 0, 0}},
320 	 {/*flags*/0,
321 	  /*resource*/0xf1,
322 	  /*reserved*/{0, 0},
323 	  /*count*/{0, 0, 0, 0}},
324 	 {/*flags*/0,
325 	  /*resource*/0xf2,
326 	  /*reserved*/{0, 0},
327 	  /*count*/{0, 0, 0, 0}}
328 	}
329 };
330 
331 const static struct ctl_logical_block_provisioning_page lbp_page_changeable = {{
332 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE | SMPH_SPF,
333 	/*subpage_code*/0x02,
334 	/*page_length*/{CTL_LBPM_LEN >> 8, CTL_LBPM_LEN},
335 	/*flags*/SLBPP_SITUA,
336 	/*reserved*/{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
337 	/*descr*/{}},
338 	{{/*flags*/0,
339 	  /*resource*/0,
340 	  /*reserved*/{0, 0},
341 	  /*count*/{0, 0, 0, 0}},
342 	 {/*flags*/0,
343 	  /*resource*/0,
344 	  /*reserved*/{0, 0},
345 	  /*count*/{0, 0, 0, 0}},
346 	 {/*flags*/0,
347 	  /*resource*/0,
348 	  /*reserved*/{0, 0},
349 	  /*count*/{0, 0, 0, 0}},
350 	 {/*flags*/0,
351 	  /*resource*/0,
352 	  /*reserved*/{0, 0},
353 	  /*count*/{0, 0, 0, 0}}
354 	}
355 };
356 
357 const static struct scsi_cddvd_capabilities_page cddvd_page_default = {
358 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
359 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
360 	/*caps1*/0x3f,
361 	/*caps2*/0x00,
362 	/*caps3*/0xf0,
363 	/*caps4*/0x00,
364 	/*caps5*/0x29,
365 	/*caps6*/0x00,
366 	/*obsolete*/{0, 0},
367 	/*nvol_levels*/{0, 0},
368 	/*buffer_size*/{8, 0},
369 	/*obsolete2*/{0, 0},
370 	/*reserved*/0,
371 	/*digital*/0,
372 	/*obsolete3*/0,
373 	/*copy_management*/0,
374 	/*reserved2*/0,
375 	/*rotation_control*/0,
376 	/*cur_write_speed*/0,
377 	/*num_speed_descr*/0,
378 };
379 
380 const static struct scsi_cddvd_capabilities_page cddvd_page_changeable = {
381 	/*page_code*/SMS_CDDVD_CAPS_PAGE,
382 	/*page_length*/sizeof(struct scsi_cddvd_capabilities_page) - 2,
383 	/*caps1*/0,
384 	/*caps2*/0,
385 	/*caps3*/0,
386 	/*caps4*/0,
387 	/*caps5*/0,
388 	/*caps6*/0,
389 	/*obsolete*/{0, 0},
390 	/*nvol_levels*/{0, 0},
391 	/*buffer_size*/{0, 0},
392 	/*obsolete2*/{0, 0},
393 	/*reserved*/0,
394 	/*digital*/0,
395 	/*obsolete3*/0,
396 	/*copy_management*/0,
397 	/*reserved2*/0,
398 	/*rotation_control*/0,
399 	/*cur_write_speed*/0,
400 	/*num_speed_descr*/0,
401 };
402 
403 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
404 static int worker_threads = -1;
405 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
406     &worker_threads, 1, "Number of worker threads");
407 static int ctl_debug = CTL_DEBUG_NONE;
408 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, debug, CTLFLAG_RWTUN,
409     &ctl_debug, 0, "Enabled debug flags");
410 static int ctl_lun_map_size = 1024;
411 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, lun_map_size, CTLFLAG_RWTUN,
412     &ctl_lun_map_size, 0, "Size of per-port LUN map (max LUN + 1)");
413 
414 /*
415  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
416  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
417  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
418  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
419  */
420 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
421 
422 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
423 				  int param);
424 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
425 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
426 static int ctl_init(void);
427 static int ctl_shutdown(void);
428 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
429 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
430 static void ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
431 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
432 			      struct ctl_ooa *ooa_hdr,
433 			      struct ctl_ooa_entry *kern_entries);
434 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
435 		     struct thread *td);
436 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
437 			 struct ctl_be_lun *be_lun);
438 static int ctl_free_lun(struct ctl_lun *lun);
439 static void ctl_create_lun(struct ctl_be_lun *be_lun);
440 
441 static int ctl_do_mode_select(union ctl_io *io);
442 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
443 			   uint64_t res_key, uint64_t sa_res_key,
444 			   uint8_t type, uint32_t residx,
445 			   struct ctl_scsiio *ctsio,
446 			   struct scsi_per_res_out *cdb,
447 			   struct scsi_per_res_out_parms* param);
448 static void ctl_pro_preempt_other(struct ctl_lun *lun,
449 				  union ctl_ha_msg *msg);
450 static void ctl_hndl_per_res_out_on_other_sc(union ctl_io *io);
451 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
452 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
453 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
454 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
455 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
456 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
457 					 int alloc_len);
458 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
459 					 int alloc_len);
460 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
461 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
462 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
463 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
464 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
465 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
466     bool seq);
467 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
468 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
469     union ctl_io *pending_io, union ctl_io *ooa_io);
470 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
471 				union ctl_io *starting_io);
472 static int ctl_check_blocked(struct ctl_lun *lun);
473 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
474 				const struct ctl_cmd_entry *entry,
475 				struct ctl_scsiio *ctsio);
476 static void ctl_failover_lun(union ctl_io *io);
477 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
478 			       struct ctl_scsiio *ctsio);
479 static int ctl_scsiio(struct ctl_scsiio *ctsio);
480 
481 static int ctl_target_reset(union ctl_io *io);
482 static void ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx,
483 			 ctl_ua_type ua_type);
484 static int ctl_lun_reset(union ctl_io *io);
485 static int ctl_abort_task(union ctl_io *io);
486 static int ctl_abort_task_set(union ctl_io *io);
487 static int ctl_query_task(union ctl_io *io, int task_set);
488 static void ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
489 			      ctl_ua_type ua_type);
490 static int ctl_i_t_nexus_reset(union ctl_io *io);
491 static int ctl_query_async_event(union ctl_io *io);
492 static void ctl_run_task(union ctl_io *io);
493 #ifdef CTL_IO_DELAY
494 static void ctl_datamove_timer_wakeup(void *arg);
495 static void ctl_done_timer_wakeup(void *arg);
496 #endif /* CTL_IO_DELAY */
497 
498 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
499 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
500 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
501 static void ctl_datamove_remote_write(union ctl_io *io);
502 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
503 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
504 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
505 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
506 				    ctl_ha_dt_cb callback);
507 static void ctl_datamove_remote_read(union ctl_io *io);
508 static void ctl_datamove_remote(union ctl_io *io);
509 static void ctl_process_done(union ctl_io *io);
510 static void ctl_lun_thread(void *arg);
511 static void ctl_thresh_thread(void *arg);
512 static void ctl_work_thread(void *arg);
513 static void ctl_enqueue_incoming(union ctl_io *io);
514 static void ctl_enqueue_rtr(union ctl_io *io);
515 static void ctl_enqueue_done(union ctl_io *io);
516 static void ctl_enqueue_isc(union ctl_io *io);
517 static const struct ctl_cmd_entry *
518     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
519 static const struct ctl_cmd_entry *
520     ctl_validate_command(struct ctl_scsiio *ctsio);
521 static int ctl_cmd_applicable(uint8_t lun_type,
522     const struct ctl_cmd_entry *entry);
523 static int ctl_ha_init(void);
524 static int ctl_ha_shutdown(void);
525 
526 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
527 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
528 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
529 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
530 
531 /*
532  * Load the serialization table.  This isn't very pretty, but is probably
533  * the easiest way to do it.
534  */
535 #include "ctl_ser_table.c"
536 
537 /*
538  * We only need to define open, close and ioctl routines for this driver.
539  */
540 static struct cdevsw ctl_cdevsw = {
541 	.d_version =	D_VERSION,
542 	.d_flags =	0,
543 	.d_open =	ctl_open,
544 	.d_close =	ctl_close,
545 	.d_ioctl =	ctl_ioctl,
546 	.d_name =	"ctl",
547 };
548 
549 
550 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
551 
552 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
553 
554 static moduledata_t ctl_moduledata = {
555 	"ctl",
556 	ctl_module_event_handler,
557 	NULL
558 };
559 
560 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
561 MODULE_VERSION(ctl, 1);
562 
563 static struct ctl_frontend ha_frontend =
564 {
565 	.name = "ha",
566 	.init = ctl_ha_init,
567 	.shutdown = ctl_ha_shutdown,
568 };
569 
570 static int
571 ctl_ha_init(void)
572 {
573 	struct ctl_softc *softc = control_softc;
574 
575 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
576 	                    &softc->othersc_pool) != 0)
577 		return (ENOMEM);
578 	if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
579 		ctl_pool_free(softc->othersc_pool);
580 		return (EIO);
581 	}
582 	if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
583 	    != CTL_HA_STATUS_SUCCESS) {
584 		ctl_ha_msg_destroy(softc);
585 		ctl_pool_free(softc->othersc_pool);
586 		return (EIO);
587 	}
588 	return (0);
589 };
590 
591 static int
592 ctl_ha_shutdown(void)
593 {
594 	struct ctl_softc *softc = control_softc;
595 	struct ctl_port *port;
596 
597 	ctl_ha_msg_shutdown(softc);
598 	if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL) != CTL_HA_STATUS_SUCCESS)
599 		return (EIO);
600 	if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
601 		return (EIO);
602 	ctl_pool_free(softc->othersc_pool);
603 	while ((port = STAILQ_FIRST(&ha_frontend.port_list)) != NULL) {
604 		ctl_port_deregister(port);
605 		free(port->port_name, M_CTL);
606 		free(port, M_CTL);
607 	}
608 	return (0);
609 };
610 
611 static void
612 ctl_ha_datamove(union ctl_io *io)
613 {
614 	struct ctl_lun *lun = CTL_LUN(io);
615 	struct ctl_sg_entry *sgl;
616 	union ctl_ha_msg msg;
617 	uint32_t sg_entries_sent;
618 	int do_sg_copy, i, j;
619 
620 	memset(&msg.dt, 0, sizeof(msg.dt));
621 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
622 	msg.hdr.original_sc = io->io_hdr.original_sc;
623 	msg.hdr.serializing_sc = io;
624 	msg.hdr.nexus = io->io_hdr.nexus;
625 	msg.hdr.status = io->io_hdr.status;
626 	msg.dt.flags = io->io_hdr.flags;
627 
628 	/*
629 	 * We convert everything into a S/G list here.  We can't
630 	 * pass by reference, only by value between controllers.
631 	 * So we can't pass a pointer to the S/G list, only as many
632 	 * S/G entries as we can fit in here.  If it's possible for
633 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
634 	 * then we need to break this up into multiple transfers.
635 	 */
636 	if (io->scsiio.kern_sg_entries == 0) {
637 		msg.dt.kern_sg_entries = 1;
638 #if 0
639 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
640 			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
641 		} else {
642 			/* XXX KDM use busdma here! */
643 			msg.dt.sg_list[0].addr =
644 			    (void *)vtophys(io->scsiio.kern_data_ptr);
645 		}
646 #else
647 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
648 		    ("HA does not support BUS_ADDR"));
649 		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
650 #endif
651 		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
652 		do_sg_copy = 0;
653 	} else {
654 		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
655 		do_sg_copy = 1;
656 	}
657 
658 	msg.dt.kern_data_len = io->scsiio.kern_data_len;
659 	msg.dt.kern_total_len = io->scsiio.kern_total_len;
660 	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
661 	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
662 	msg.dt.sg_sequence = 0;
663 
664 	/*
665 	 * Loop until we've sent all of the S/G entries.  On the
666 	 * other end, we'll recompose these S/G entries into one
667 	 * contiguous list before processing.
668 	 */
669 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
670 	    msg.dt.sg_sequence++) {
671 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
672 		    sizeof(msg.dt.sg_list[0])),
673 		    msg.dt.kern_sg_entries - sg_entries_sent);
674 		if (do_sg_copy != 0) {
675 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
676 			for (i = sg_entries_sent, j = 0;
677 			     i < msg.dt.cur_sg_entries; i++, j++) {
678 #if 0
679 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
680 					msg.dt.sg_list[j].addr = sgl[i].addr;
681 				} else {
682 					/* XXX KDM use busdma here! */
683 					msg.dt.sg_list[j].addr =
684 					    (void *)vtophys(sgl[i].addr);
685 				}
686 #else
687 				KASSERT((io->io_hdr.flags &
688 				    CTL_FLAG_BUS_ADDR) == 0,
689 				    ("HA does not support BUS_ADDR"));
690 				msg.dt.sg_list[j].addr = sgl[i].addr;
691 #endif
692 				msg.dt.sg_list[j].len = sgl[i].len;
693 			}
694 		}
695 
696 		sg_entries_sent += msg.dt.cur_sg_entries;
697 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
698 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
699 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
700 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
701 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
702 			io->io_hdr.port_status = 31341;
703 			io->scsiio.be_move_done(io);
704 			return;
705 		}
706 		msg.dt.sent_sg_entries = sg_entries_sent;
707 	}
708 
709 	/*
710 	 * Officially handover the request from us to peer.
711 	 * If failover has just happened, then we must return error.
712 	 * If failover happen just after, then it is not our problem.
713 	 */
714 	if (lun)
715 		mtx_lock(&lun->lun_lock);
716 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
717 		if (lun)
718 			mtx_unlock(&lun->lun_lock);
719 		io->io_hdr.port_status = 31342;
720 		io->scsiio.be_move_done(io);
721 		return;
722 	}
723 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
724 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
725 	if (lun)
726 		mtx_unlock(&lun->lun_lock);
727 }
728 
729 static void
730 ctl_ha_done(union ctl_io *io)
731 {
732 	union ctl_ha_msg msg;
733 
734 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
735 		memset(&msg, 0, sizeof(msg));
736 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
737 		msg.hdr.original_sc = io->io_hdr.original_sc;
738 		msg.hdr.nexus = io->io_hdr.nexus;
739 		msg.hdr.status = io->io_hdr.status;
740 		msg.scsi.scsi_status = io->scsiio.scsi_status;
741 		msg.scsi.tag_num = io->scsiio.tag_num;
742 		msg.scsi.tag_type = io->scsiio.tag_type;
743 		msg.scsi.sense_len = io->scsiio.sense_len;
744 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
745 		    io->scsiio.sense_len);
746 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
747 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
748 		    msg.scsi.sense_len, M_WAITOK);
749 	}
750 	ctl_free_io(io);
751 }
752 
753 static void
754 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
755 			    union ctl_ha_msg *msg_info)
756 {
757 	struct ctl_scsiio *ctsio;
758 
759 	if (msg_info->hdr.original_sc == NULL) {
760 		printf("%s: original_sc == NULL!\n", __func__);
761 		/* XXX KDM now what? */
762 		return;
763 	}
764 
765 	ctsio = &msg_info->hdr.original_sc->scsiio;
766 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
767 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
768 	ctsio->io_hdr.status = msg_info->hdr.status;
769 	ctsio->scsi_status = msg_info->scsi.scsi_status;
770 	ctsio->sense_len = msg_info->scsi.sense_len;
771 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
772 	       msg_info->scsi.sense_len);
773 	ctl_enqueue_isc((union ctl_io *)ctsio);
774 }
775 
776 static void
777 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
778 				union ctl_ha_msg *msg_info)
779 {
780 	struct ctl_scsiio *ctsio;
781 
782 	if (msg_info->hdr.serializing_sc == NULL) {
783 		printf("%s: serializing_sc == NULL!\n", __func__);
784 		/* XXX KDM now what? */
785 		return;
786 	}
787 
788 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
789 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
790 	ctl_enqueue_isc((union ctl_io *)ctsio);
791 }
792 
793 void
794 ctl_isc_announce_lun(struct ctl_lun *lun)
795 {
796 	struct ctl_softc *softc = lun->ctl_softc;
797 	union ctl_ha_msg *msg;
798 	struct ctl_ha_msg_lun_pr_key pr_key;
799 	int i, k;
800 
801 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
802 		return;
803 	mtx_lock(&lun->lun_lock);
804 	i = sizeof(msg->lun);
805 	if (lun->lun_devid)
806 		i += lun->lun_devid->len;
807 	i += sizeof(pr_key) * lun->pr_key_count;
808 alloc:
809 	mtx_unlock(&lun->lun_lock);
810 	msg = malloc(i, M_CTL, M_WAITOK);
811 	mtx_lock(&lun->lun_lock);
812 	k = sizeof(msg->lun);
813 	if (lun->lun_devid)
814 		k += lun->lun_devid->len;
815 	k += sizeof(pr_key) * lun->pr_key_count;
816 	if (i < k) {
817 		free(msg, M_CTL);
818 		i = k;
819 		goto alloc;
820 	}
821 	bzero(&msg->lun, sizeof(msg->lun));
822 	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
823 	msg->hdr.nexus.targ_lun = lun->lun;
824 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
825 	msg->lun.flags = lun->flags;
826 	msg->lun.pr_generation = lun->pr_generation;
827 	msg->lun.pr_res_idx = lun->pr_res_idx;
828 	msg->lun.pr_res_type = lun->pr_res_type;
829 	msg->lun.pr_key_count = lun->pr_key_count;
830 	i = 0;
831 	if (lun->lun_devid) {
832 		msg->lun.lun_devid_len = lun->lun_devid->len;
833 		memcpy(&msg->lun.data[i], lun->lun_devid->data,
834 		    msg->lun.lun_devid_len);
835 		i += msg->lun.lun_devid_len;
836 	}
837 	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
838 		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
839 			continue;
840 		pr_key.pr_iid = k;
841 		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
842 		i += sizeof(pr_key);
843 	}
844 	mtx_unlock(&lun->lun_lock);
845 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
846 	    M_WAITOK);
847 	free(msg, M_CTL);
848 
849 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
850 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
851 			ctl_isc_announce_mode(lun, -1,
852 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
853 			    lun->mode_pages.index[i].subpage);
854 		}
855 	}
856 }
857 
858 void
859 ctl_isc_announce_port(struct ctl_port *port)
860 {
861 	struct ctl_softc *softc = port->ctl_softc;
862 	union ctl_ha_msg *msg;
863 	int i;
864 
865 	if (port->targ_port < softc->port_min ||
866 	    port->targ_port >= softc->port_max ||
867 	    softc->ha_link != CTL_HA_LINK_ONLINE)
868 		return;
869 	i = sizeof(msg->port) + strlen(port->port_name) + 1;
870 	if (port->lun_map)
871 		i += port->lun_map_size * sizeof(uint32_t);
872 	if (port->port_devid)
873 		i += port->port_devid->len;
874 	if (port->target_devid)
875 		i += port->target_devid->len;
876 	if (port->init_devid)
877 		i += port->init_devid->len;
878 	msg = malloc(i, M_CTL, M_WAITOK);
879 	bzero(&msg->port, sizeof(msg->port));
880 	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
881 	msg->hdr.nexus.targ_port = port->targ_port;
882 	msg->port.port_type = port->port_type;
883 	msg->port.physical_port = port->physical_port;
884 	msg->port.virtual_port = port->virtual_port;
885 	msg->port.status = port->status;
886 	i = 0;
887 	msg->port.name_len = sprintf(&msg->port.data[i],
888 	    "%d:%s", softc->ha_id, port->port_name) + 1;
889 	i += msg->port.name_len;
890 	if (port->lun_map) {
891 		msg->port.lun_map_len = port->lun_map_size * sizeof(uint32_t);
892 		memcpy(&msg->port.data[i], port->lun_map,
893 		    msg->port.lun_map_len);
894 		i += msg->port.lun_map_len;
895 	}
896 	if (port->port_devid) {
897 		msg->port.port_devid_len = port->port_devid->len;
898 		memcpy(&msg->port.data[i], port->port_devid->data,
899 		    msg->port.port_devid_len);
900 		i += msg->port.port_devid_len;
901 	}
902 	if (port->target_devid) {
903 		msg->port.target_devid_len = port->target_devid->len;
904 		memcpy(&msg->port.data[i], port->target_devid->data,
905 		    msg->port.target_devid_len);
906 		i += msg->port.target_devid_len;
907 	}
908 	if (port->init_devid) {
909 		msg->port.init_devid_len = port->init_devid->len;
910 		memcpy(&msg->port.data[i], port->init_devid->data,
911 		    msg->port.init_devid_len);
912 		i += msg->port.init_devid_len;
913 	}
914 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
915 	    M_WAITOK);
916 	free(msg, M_CTL);
917 }
918 
919 void
920 ctl_isc_announce_iid(struct ctl_port *port, int iid)
921 {
922 	struct ctl_softc *softc = port->ctl_softc;
923 	union ctl_ha_msg *msg;
924 	int i, l;
925 
926 	if (port->targ_port < softc->port_min ||
927 	    port->targ_port >= softc->port_max ||
928 	    softc->ha_link != CTL_HA_LINK_ONLINE)
929 		return;
930 	mtx_lock(&softc->ctl_lock);
931 	i = sizeof(msg->iid);
932 	l = 0;
933 	if (port->wwpn_iid[iid].name)
934 		l = strlen(port->wwpn_iid[iid].name) + 1;
935 	i += l;
936 	msg = malloc(i, M_CTL, M_NOWAIT);
937 	if (msg == NULL) {
938 		mtx_unlock(&softc->ctl_lock);
939 		return;
940 	}
941 	bzero(&msg->iid, sizeof(msg->iid));
942 	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
943 	msg->hdr.nexus.targ_port = port->targ_port;
944 	msg->hdr.nexus.initid = iid;
945 	msg->iid.in_use = port->wwpn_iid[iid].in_use;
946 	msg->iid.name_len = l;
947 	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
948 	if (port->wwpn_iid[iid].name)
949 		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
950 	mtx_unlock(&softc->ctl_lock);
951 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
952 	free(msg, M_CTL);
953 }
954 
955 void
956 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
957     uint8_t page, uint8_t subpage)
958 {
959 	struct ctl_softc *softc = lun->ctl_softc;
960 	union ctl_ha_msg msg;
961 	u_int i;
962 
963 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
964 		return;
965 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
966 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
967 		    page && lun->mode_pages.index[i].subpage == subpage)
968 			break;
969 	}
970 	if (i == CTL_NUM_MODE_PAGES)
971 		return;
972 
973 	/* Don't try to replicate pages not present on this device. */
974 	if (lun->mode_pages.index[i].page_data == NULL)
975 		return;
976 
977 	bzero(&msg.mode, sizeof(msg.mode));
978 	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
979 	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
980 	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
981 	msg.hdr.nexus.targ_lun = lun->lun;
982 	msg.hdr.nexus.targ_mapped_lun = lun->lun;
983 	msg.mode.page_code = page;
984 	msg.mode.subpage = subpage;
985 	msg.mode.page_len = lun->mode_pages.index[i].page_len;
986 	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
987 	    msg.mode.page_len);
988 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
989 	    M_WAITOK);
990 }
991 
992 static void
993 ctl_isc_ha_link_up(struct ctl_softc *softc)
994 {
995 	struct ctl_port *port;
996 	struct ctl_lun *lun;
997 	union ctl_ha_msg msg;
998 	int i;
999 
1000 	/* Announce this node parameters to peer for validation. */
1001 	msg.login.msg_type = CTL_MSG_LOGIN;
1002 	msg.login.version = CTL_HA_VERSION;
1003 	msg.login.ha_mode = softc->ha_mode;
1004 	msg.login.ha_id = softc->ha_id;
1005 	msg.login.max_luns = CTL_MAX_LUNS;
1006 	msg.login.max_ports = CTL_MAX_PORTS;
1007 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
1008 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
1009 	    M_WAITOK);
1010 
1011 	STAILQ_FOREACH(port, &softc->port_list, links) {
1012 		ctl_isc_announce_port(port);
1013 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1014 			if (port->wwpn_iid[i].in_use)
1015 				ctl_isc_announce_iid(port, i);
1016 		}
1017 	}
1018 	STAILQ_FOREACH(lun, &softc->lun_list, links)
1019 		ctl_isc_announce_lun(lun);
1020 }
1021 
1022 static void
1023 ctl_isc_ha_link_down(struct ctl_softc *softc)
1024 {
1025 	struct ctl_port *port;
1026 	struct ctl_lun *lun;
1027 	union ctl_io *io;
1028 	int i;
1029 
1030 	mtx_lock(&softc->ctl_lock);
1031 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1032 		mtx_lock(&lun->lun_lock);
1033 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
1034 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1035 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1036 		}
1037 		mtx_unlock(&lun->lun_lock);
1038 
1039 		mtx_unlock(&softc->ctl_lock);
1040 		io = ctl_alloc_io(softc->othersc_pool);
1041 		mtx_lock(&softc->ctl_lock);
1042 		ctl_zero_io(io);
1043 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
1044 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
1045 		ctl_enqueue_isc(io);
1046 	}
1047 
1048 	STAILQ_FOREACH(port, &softc->port_list, links) {
1049 		if (port->targ_port >= softc->port_min &&
1050 		    port->targ_port < softc->port_max)
1051 			continue;
1052 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1053 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1054 			port->wwpn_iid[i].in_use = 0;
1055 			free(port->wwpn_iid[i].name, M_CTL);
1056 			port->wwpn_iid[i].name = NULL;
1057 		}
1058 	}
1059 	mtx_unlock(&softc->ctl_lock);
1060 }
1061 
1062 static void
1063 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1064 {
1065 	struct ctl_lun *lun;
1066 	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1067 
1068 	mtx_lock(&softc->ctl_lock);
1069 	if (msg->hdr.nexus.targ_mapped_lun >= CTL_MAX_LUNS ||
1070 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) == NULL) {
1071 		mtx_unlock(&softc->ctl_lock);
1072 		return;
1073 	}
1074 	mtx_lock(&lun->lun_lock);
1075 	mtx_unlock(&softc->ctl_lock);
1076 	if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES && msg->ua.ua_set)
1077 		memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1078 	if (msg->ua.ua_all) {
1079 		if (msg->ua.ua_set)
1080 			ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1081 		else
1082 			ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1083 	} else {
1084 		if (msg->ua.ua_set)
1085 			ctl_est_ua(lun, iid, msg->ua.ua_type);
1086 		else
1087 			ctl_clr_ua(lun, iid, msg->ua.ua_type);
1088 	}
1089 	mtx_unlock(&lun->lun_lock);
1090 }
1091 
1092 static void
1093 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1094 {
1095 	struct ctl_lun *lun;
1096 	struct ctl_ha_msg_lun_pr_key pr_key;
1097 	int i, k;
1098 	ctl_lun_flags oflags;
1099 	uint32_t targ_lun;
1100 
1101 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1102 	mtx_lock(&softc->ctl_lock);
1103 	if (targ_lun >= CTL_MAX_LUNS ||
1104 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1105 		mtx_unlock(&softc->ctl_lock);
1106 		return;
1107 	}
1108 	mtx_lock(&lun->lun_lock);
1109 	mtx_unlock(&softc->ctl_lock);
1110 	if (lun->flags & CTL_LUN_DISABLED) {
1111 		mtx_unlock(&lun->lun_lock);
1112 		return;
1113 	}
1114 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1115 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1116 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1117 		mtx_unlock(&lun->lun_lock);
1118 		printf("%s: Received conflicting HA LUN %d\n",
1119 		    __func__, targ_lun);
1120 		return;
1121 	} else {
1122 		/* Record whether peer is primary. */
1123 		oflags = lun->flags;
1124 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1125 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1126 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1127 		else
1128 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1129 		if (oflags != lun->flags)
1130 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1131 
1132 		/* If peer is primary and we are not -- use data */
1133 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1134 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1135 			lun->pr_generation = msg->lun.pr_generation;
1136 			lun->pr_res_idx = msg->lun.pr_res_idx;
1137 			lun->pr_res_type = msg->lun.pr_res_type;
1138 			lun->pr_key_count = msg->lun.pr_key_count;
1139 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1140 				ctl_clr_prkey(lun, k);
1141 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1142 				memcpy(&pr_key, &msg->lun.data[i],
1143 				    sizeof(pr_key));
1144 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1145 				ctl_set_prkey(lun, pr_key.pr_iid,
1146 				    pr_key.pr_key);
1147 				i += sizeof(pr_key);
1148 			}
1149 		}
1150 
1151 		mtx_unlock(&lun->lun_lock);
1152 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1153 		    __func__, targ_lun,
1154 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1155 		    "primary" : "secondary"));
1156 
1157 		/* If we are primary but peer doesn't know -- notify */
1158 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1159 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1160 			ctl_isc_announce_lun(lun);
1161 	}
1162 }
1163 
1164 static void
1165 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1166 {
1167 	struct ctl_port *port;
1168 	struct ctl_lun *lun;
1169 	int i, new;
1170 
1171 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1172 	if (port == NULL) {
1173 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1174 		    msg->hdr.nexus.targ_port));
1175 		new = 1;
1176 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1177 		port->frontend = &ha_frontend;
1178 		port->targ_port = msg->hdr.nexus.targ_port;
1179 		port->fe_datamove = ctl_ha_datamove;
1180 		port->fe_done = ctl_ha_done;
1181 	} else if (port->frontend == &ha_frontend) {
1182 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1183 		    msg->hdr.nexus.targ_port));
1184 		new = 0;
1185 	} else {
1186 		printf("%s: Received conflicting HA port %d\n",
1187 		    __func__, msg->hdr.nexus.targ_port);
1188 		return;
1189 	}
1190 	port->port_type = msg->port.port_type;
1191 	port->physical_port = msg->port.physical_port;
1192 	port->virtual_port = msg->port.virtual_port;
1193 	port->status = msg->port.status;
1194 	i = 0;
1195 	free(port->port_name, M_CTL);
1196 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1197 	    M_CTL);
1198 	i += msg->port.name_len;
1199 	if (msg->port.lun_map_len != 0) {
1200 		if (port->lun_map == NULL ||
1201 		    port->lun_map_size * sizeof(uint32_t) <
1202 		    msg->port.lun_map_len) {
1203 			port->lun_map_size = 0;
1204 			free(port->lun_map, M_CTL);
1205 			port->lun_map = malloc(msg->port.lun_map_len,
1206 			    M_CTL, M_WAITOK);
1207 		}
1208 		memcpy(port->lun_map, &msg->port.data[i], msg->port.lun_map_len);
1209 		port->lun_map_size = msg->port.lun_map_len / sizeof(uint32_t);
1210 		i += msg->port.lun_map_len;
1211 	} else {
1212 		port->lun_map_size = 0;
1213 		free(port->lun_map, M_CTL);
1214 		port->lun_map = NULL;
1215 	}
1216 	if (msg->port.port_devid_len != 0) {
1217 		if (port->port_devid == NULL ||
1218 		    port->port_devid->len < msg->port.port_devid_len) {
1219 			free(port->port_devid, M_CTL);
1220 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1221 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1222 		}
1223 		memcpy(port->port_devid->data, &msg->port.data[i],
1224 		    msg->port.port_devid_len);
1225 		port->port_devid->len = msg->port.port_devid_len;
1226 		i += msg->port.port_devid_len;
1227 	} else {
1228 		free(port->port_devid, M_CTL);
1229 		port->port_devid = NULL;
1230 	}
1231 	if (msg->port.target_devid_len != 0) {
1232 		if (port->target_devid == NULL ||
1233 		    port->target_devid->len < msg->port.target_devid_len) {
1234 			free(port->target_devid, M_CTL);
1235 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1236 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1237 		}
1238 		memcpy(port->target_devid->data, &msg->port.data[i],
1239 		    msg->port.target_devid_len);
1240 		port->target_devid->len = msg->port.target_devid_len;
1241 		i += msg->port.target_devid_len;
1242 	} else {
1243 		free(port->target_devid, M_CTL);
1244 		port->target_devid = NULL;
1245 	}
1246 	if (msg->port.init_devid_len != 0) {
1247 		if (port->init_devid == NULL ||
1248 		    port->init_devid->len < msg->port.init_devid_len) {
1249 			free(port->init_devid, M_CTL);
1250 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1251 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1252 		}
1253 		memcpy(port->init_devid->data, &msg->port.data[i],
1254 		    msg->port.init_devid_len);
1255 		port->init_devid->len = msg->port.init_devid_len;
1256 		i += msg->port.init_devid_len;
1257 	} else {
1258 		free(port->init_devid, M_CTL);
1259 		port->init_devid = NULL;
1260 	}
1261 	if (new) {
1262 		if (ctl_port_register(port) != 0) {
1263 			printf("%s: ctl_port_register() failed with error\n",
1264 			    __func__);
1265 		}
1266 	}
1267 	mtx_lock(&softc->ctl_lock);
1268 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1269 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
1270 			continue;
1271 		mtx_lock(&lun->lun_lock);
1272 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1273 		mtx_unlock(&lun->lun_lock);
1274 	}
1275 	mtx_unlock(&softc->ctl_lock);
1276 }
1277 
1278 static void
1279 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1280 {
1281 	struct ctl_port *port;
1282 	int iid;
1283 
1284 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1285 	if (port == NULL) {
1286 		printf("%s: Received IID for unknown port %d\n",
1287 		    __func__, msg->hdr.nexus.targ_port);
1288 		return;
1289 	}
1290 	iid = msg->hdr.nexus.initid;
1291 	if (port->wwpn_iid[iid].in_use != 0 &&
1292 	    msg->iid.in_use == 0)
1293 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
1294 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1295 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1296 	free(port->wwpn_iid[iid].name, M_CTL);
1297 	if (msg->iid.name_len) {
1298 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1299 		    msg->iid.name_len, M_CTL);
1300 	} else
1301 		port->wwpn_iid[iid].name = NULL;
1302 }
1303 
1304 static void
1305 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1306 {
1307 
1308 	if (msg->login.version != CTL_HA_VERSION) {
1309 		printf("CTL HA peers have different versions %d != %d\n",
1310 		    msg->login.version, CTL_HA_VERSION);
1311 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1312 		return;
1313 	}
1314 	if (msg->login.ha_mode != softc->ha_mode) {
1315 		printf("CTL HA peers have different ha_mode %d != %d\n",
1316 		    msg->login.ha_mode, softc->ha_mode);
1317 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1318 		return;
1319 	}
1320 	if (msg->login.ha_id == softc->ha_id) {
1321 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1322 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1323 		return;
1324 	}
1325 	if (msg->login.max_luns != CTL_MAX_LUNS ||
1326 	    msg->login.max_ports != CTL_MAX_PORTS ||
1327 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1328 		printf("CTL HA peers have different limits\n");
1329 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1330 		return;
1331 	}
1332 }
1333 
1334 static void
1335 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1336 {
1337 	struct ctl_lun *lun;
1338 	u_int i;
1339 	uint32_t initidx, targ_lun;
1340 
1341 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1342 	mtx_lock(&softc->ctl_lock);
1343 	if (targ_lun >= CTL_MAX_LUNS ||
1344 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
1345 		mtx_unlock(&softc->ctl_lock);
1346 		return;
1347 	}
1348 	mtx_lock(&lun->lun_lock);
1349 	mtx_unlock(&softc->ctl_lock);
1350 	if (lun->flags & CTL_LUN_DISABLED) {
1351 		mtx_unlock(&lun->lun_lock);
1352 		return;
1353 	}
1354 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1355 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1356 		    msg->mode.page_code &&
1357 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1358 			break;
1359 	}
1360 	if (i == CTL_NUM_MODE_PAGES) {
1361 		mtx_unlock(&lun->lun_lock);
1362 		return;
1363 	}
1364 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1365 	    lun->mode_pages.index[i].page_len);
1366 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1367 	if (initidx != -1)
1368 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1369 	mtx_unlock(&lun->lun_lock);
1370 }
1371 
1372 /*
1373  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1374  * subsystem come in here.
1375  */
1376 static void
1377 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1378 {
1379 	struct ctl_softc *softc = control_softc;
1380 	union ctl_io *io;
1381 	struct ctl_prio *presio;
1382 	ctl_ha_status isc_status;
1383 
1384 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1385 	if (event == CTL_HA_EVT_MSG_RECV) {
1386 		union ctl_ha_msg *msg, msgbuf;
1387 
1388 		if (param > sizeof(msgbuf))
1389 			msg = malloc(param, M_CTL, M_WAITOK);
1390 		else
1391 			msg = &msgbuf;
1392 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1393 		    M_WAITOK);
1394 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1395 			printf("%s: Error receiving message: %d\n",
1396 			    __func__, isc_status);
1397 			if (msg != &msgbuf)
1398 				free(msg, M_CTL);
1399 			return;
1400 		}
1401 
1402 		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1403 		switch (msg->hdr.msg_type) {
1404 		case CTL_MSG_SERIALIZE:
1405 			io = ctl_alloc_io(softc->othersc_pool);
1406 			ctl_zero_io(io);
1407 			// populate ctsio from msg
1408 			io->io_hdr.io_type = CTL_IO_SCSI;
1409 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1410 			io->io_hdr.original_sc = msg->hdr.original_sc;
1411 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1412 					    CTL_FLAG_IO_ACTIVE;
1413 			/*
1414 			 * If we're in serialization-only mode, we don't
1415 			 * want to go through full done processing.  Thus
1416 			 * the COPY flag.
1417 			 *
1418 			 * XXX KDM add another flag that is more specific.
1419 			 */
1420 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1421 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1422 			io->io_hdr.nexus = msg->hdr.nexus;
1423 #if 0
1424 			printf("port %u, iid %u, lun %u\n",
1425 			       io->io_hdr.nexus.targ_port,
1426 			       io->io_hdr.nexus.initid,
1427 			       io->io_hdr.nexus.targ_lun);
1428 #endif
1429 			io->scsiio.tag_num = msg->scsi.tag_num;
1430 			io->scsiio.tag_type = msg->scsi.tag_type;
1431 #ifdef CTL_TIME_IO
1432 			io->io_hdr.start_time = time_uptime;
1433 			getbinuptime(&io->io_hdr.start_bt);
1434 #endif /* CTL_TIME_IO */
1435 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1436 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1437 			       CTL_MAX_CDBLEN);
1438 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1439 				const struct ctl_cmd_entry *entry;
1440 
1441 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1442 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1443 				io->io_hdr.flags |=
1444 					entry->flags & CTL_FLAG_DATA_MASK;
1445 			}
1446 			ctl_enqueue_isc(io);
1447 			break;
1448 
1449 		/* Performed on the Originating SC, XFER mode only */
1450 		case CTL_MSG_DATAMOVE: {
1451 			struct ctl_sg_entry *sgl;
1452 			int i, j;
1453 
1454 			io = msg->hdr.original_sc;
1455 			if (io == NULL) {
1456 				printf("%s: original_sc == NULL!\n", __func__);
1457 				/* XXX KDM do something here */
1458 				break;
1459 			}
1460 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1461 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1462 			/*
1463 			 * Keep track of this, we need to send it back over
1464 			 * when the datamove is complete.
1465 			 */
1466 			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1467 			if (msg->hdr.status == CTL_SUCCESS)
1468 				io->io_hdr.status = msg->hdr.status;
1469 
1470 			if (msg->dt.sg_sequence == 0) {
1471 #ifdef CTL_TIME_IO
1472 				getbinuptime(&io->io_hdr.dma_start_bt);
1473 #endif
1474 				i = msg->dt.kern_sg_entries +
1475 				    msg->dt.kern_data_len /
1476 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1477 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1478 				    M_WAITOK | M_ZERO);
1479 				io->io_hdr.remote_sglist = sgl;
1480 				io->io_hdr.local_sglist =
1481 				    &sgl[msg->dt.kern_sg_entries];
1482 
1483 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1484 
1485 				io->scsiio.kern_sg_entries =
1486 					msg->dt.kern_sg_entries;
1487 				io->scsiio.rem_sg_entries =
1488 					msg->dt.kern_sg_entries;
1489 				io->scsiio.kern_data_len =
1490 					msg->dt.kern_data_len;
1491 				io->scsiio.kern_total_len =
1492 					msg->dt.kern_total_len;
1493 				io->scsiio.kern_data_resid =
1494 					msg->dt.kern_data_resid;
1495 				io->scsiio.kern_rel_offset =
1496 					msg->dt.kern_rel_offset;
1497 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1498 				io->io_hdr.flags |= msg->dt.flags &
1499 				    CTL_FLAG_BUS_ADDR;
1500 			} else
1501 				sgl = (struct ctl_sg_entry *)
1502 					io->scsiio.kern_data_ptr;
1503 
1504 			for (i = msg->dt.sent_sg_entries, j = 0;
1505 			     i < (msg->dt.sent_sg_entries +
1506 			     msg->dt.cur_sg_entries); i++, j++) {
1507 				sgl[i].addr = msg->dt.sg_list[j].addr;
1508 				sgl[i].len = msg->dt.sg_list[j].len;
1509 
1510 #if 0
1511 				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1512 				    __func__, sgl[i].addr, sgl[i].len, j, i);
1513 #endif
1514 			}
1515 
1516 			/*
1517 			 * If this is the last piece of the I/O, we've got
1518 			 * the full S/G list.  Queue processing in the thread.
1519 			 * Otherwise wait for the next piece.
1520 			 */
1521 			if (msg->dt.sg_last != 0)
1522 				ctl_enqueue_isc(io);
1523 			break;
1524 		}
1525 		/* Performed on the Serializing (primary) SC, XFER mode only */
1526 		case CTL_MSG_DATAMOVE_DONE: {
1527 			if (msg->hdr.serializing_sc == NULL) {
1528 				printf("%s: serializing_sc == NULL!\n",
1529 				       __func__);
1530 				/* XXX KDM now what? */
1531 				break;
1532 			}
1533 			/*
1534 			 * We grab the sense information here in case
1535 			 * there was a failure, so we can return status
1536 			 * back to the initiator.
1537 			 */
1538 			io = msg->hdr.serializing_sc;
1539 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1540 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1541 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1542 			io->io_hdr.port_status = msg->scsi.port_status;
1543 			io->scsiio.kern_data_resid = msg->scsi.kern_data_resid;
1544 			if (msg->hdr.status != CTL_STATUS_NONE) {
1545 				io->io_hdr.status = msg->hdr.status;
1546 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1547 				io->scsiio.sense_len = msg->scsi.sense_len;
1548 				memcpy(&io->scsiio.sense_data,
1549 				    &msg->scsi.sense_data,
1550 				    msg->scsi.sense_len);
1551 				if (msg->hdr.status == CTL_SUCCESS)
1552 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1553 			}
1554 			ctl_enqueue_isc(io);
1555 			break;
1556 		}
1557 
1558 		/* Preformed on Originating SC, SER_ONLY mode */
1559 		case CTL_MSG_R2R:
1560 			io = msg->hdr.original_sc;
1561 			if (io == NULL) {
1562 				printf("%s: original_sc == NULL!\n",
1563 				    __func__);
1564 				break;
1565 			}
1566 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1567 			io->io_hdr.msg_type = CTL_MSG_R2R;
1568 			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1569 			ctl_enqueue_isc(io);
1570 			break;
1571 
1572 		/*
1573 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1574 		 * mode.
1575 		 * Performed on the Originating (i.e. secondary) SC in XFER
1576 		 * mode
1577 		 */
1578 		case CTL_MSG_FINISH_IO:
1579 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1580 				ctl_isc_handler_finish_xfer(softc, msg);
1581 			else
1582 				ctl_isc_handler_finish_ser_only(softc, msg);
1583 			break;
1584 
1585 		/* Preformed on Originating SC */
1586 		case CTL_MSG_BAD_JUJU:
1587 			io = msg->hdr.original_sc;
1588 			if (io == NULL) {
1589 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1590 				       __func__);
1591 				break;
1592 			}
1593 			ctl_copy_sense_data(msg, io);
1594 			/*
1595 			 * IO should have already been cleaned up on other
1596 			 * SC so clear this flag so we won't send a message
1597 			 * back to finish the IO there.
1598 			 */
1599 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1600 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1601 
1602 			/* io = msg->hdr.serializing_sc; */
1603 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1604 			ctl_enqueue_isc(io);
1605 			break;
1606 
1607 		/* Handle resets sent from the other side */
1608 		case CTL_MSG_MANAGE_TASKS: {
1609 			struct ctl_taskio *taskio;
1610 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1611 			    softc->othersc_pool);
1612 			ctl_zero_io((union ctl_io *)taskio);
1613 			taskio->io_hdr.io_type = CTL_IO_TASK;
1614 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1615 			taskio->io_hdr.nexus = msg->hdr.nexus;
1616 			taskio->task_action = msg->task.task_action;
1617 			taskio->tag_num = msg->task.tag_num;
1618 			taskio->tag_type = msg->task.tag_type;
1619 #ifdef CTL_TIME_IO
1620 			taskio->io_hdr.start_time = time_uptime;
1621 			getbinuptime(&taskio->io_hdr.start_bt);
1622 #endif /* CTL_TIME_IO */
1623 			ctl_run_task((union ctl_io *)taskio);
1624 			break;
1625 		}
1626 		/* Persistent Reserve action which needs attention */
1627 		case CTL_MSG_PERS_ACTION:
1628 			presio = (struct ctl_prio *)ctl_alloc_io(
1629 			    softc->othersc_pool);
1630 			ctl_zero_io((union ctl_io *)presio);
1631 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1632 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1633 			presio->io_hdr.nexus = msg->hdr.nexus;
1634 			presio->pr_msg = msg->pr;
1635 			ctl_enqueue_isc((union ctl_io *)presio);
1636 			break;
1637 		case CTL_MSG_UA:
1638 			ctl_isc_ua(softc, msg, param);
1639 			break;
1640 		case CTL_MSG_PORT_SYNC:
1641 			ctl_isc_port_sync(softc, msg, param);
1642 			break;
1643 		case CTL_MSG_LUN_SYNC:
1644 			ctl_isc_lun_sync(softc, msg, param);
1645 			break;
1646 		case CTL_MSG_IID_SYNC:
1647 			ctl_isc_iid_sync(softc, msg, param);
1648 			break;
1649 		case CTL_MSG_LOGIN:
1650 			ctl_isc_login(softc, msg, param);
1651 			break;
1652 		case CTL_MSG_MODE_SYNC:
1653 			ctl_isc_mode_sync(softc, msg, param);
1654 			break;
1655 		default:
1656 			printf("Received HA message of unknown type %d\n",
1657 			    msg->hdr.msg_type);
1658 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1659 			break;
1660 		}
1661 		if (msg != &msgbuf)
1662 			free(msg, M_CTL);
1663 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1664 		printf("CTL: HA link status changed from %d to %d\n",
1665 		    softc->ha_link, param);
1666 		if (param == softc->ha_link)
1667 			return;
1668 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1669 			softc->ha_link = param;
1670 			ctl_isc_ha_link_down(softc);
1671 		} else {
1672 			softc->ha_link = param;
1673 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1674 				ctl_isc_ha_link_up(softc);
1675 		}
1676 		return;
1677 	} else {
1678 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1679 		return;
1680 	}
1681 }
1682 
1683 static void
1684 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1685 {
1686 
1687 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1688 	    src->scsi.sense_len);
1689 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1690 	dest->scsiio.sense_len = src->scsi.sense_len;
1691 	dest->io_hdr.status = src->hdr.status;
1692 }
1693 
1694 static void
1695 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1696 {
1697 
1698 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1699 	    src->scsiio.sense_len);
1700 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1701 	dest->scsi.sense_len = src->scsiio.sense_len;
1702 	dest->hdr.status = src->io_hdr.status;
1703 }
1704 
1705 void
1706 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1707 {
1708 	struct ctl_softc *softc = lun->ctl_softc;
1709 	ctl_ua_type *pu;
1710 
1711 	if (initidx < softc->init_min || initidx >= softc->init_max)
1712 		return;
1713 	mtx_assert(&lun->lun_lock, MA_OWNED);
1714 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1715 	if (pu == NULL)
1716 		return;
1717 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1718 }
1719 
1720 void
1721 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1722 {
1723 	int i;
1724 
1725 	mtx_assert(&lun->lun_lock, MA_OWNED);
1726 	if (lun->pending_ua[port] == NULL)
1727 		return;
1728 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1729 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1730 			continue;
1731 		lun->pending_ua[port][i] |= ua;
1732 	}
1733 }
1734 
1735 void
1736 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1737 {
1738 	struct ctl_softc *softc = lun->ctl_softc;
1739 	int i;
1740 
1741 	mtx_assert(&lun->lun_lock, MA_OWNED);
1742 	for (i = softc->port_min; i < softc->port_max; i++)
1743 		ctl_est_ua_port(lun, i, except, ua);
1744 }
1745 
1746 void
1747 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1748 {
1749 	struct ctl_softc *softc = lun->ctl_softc;
1750 	ctl_ua_type *pu;
1751 
1752 	if (initidx < softc->init_min || initidx >= softc->init_max)
1753 		return;
1754 	mtx_assert(&lun->lun_lock, MA_OWNED);
1755 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1756 	if (pu == NULL)
1757 		return;
1758 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1759 }
1760 
1761 void
1762 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1763 {
1764 	struct ctl_softc *softc = lun->ctl_softc;
1765 	int i, j;
1766 
1767 	mtx_assert(&lun->lun_lock, MA_OWNED);
1768 	for (i = softc->port_min; i < softc->port_max; i++) {
1769 		if (lun->pending_ua[i] == NULL)
1770 			continue;
1771 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1772 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1773 				continue;
1774 			lun->pending_ua[i][j] &= ~ua;
1775 		}
1776 	}
1777 }
1778 
1779 void
1780 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1781     ctl_ua_type ua_type)
1782 {
1783 	struct ctl_lun *lun;
1784 
1785 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1786 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1787 		mtx_lock(&lun->lun_lock);
1788 		ctl_clr_ua(lun, initidx, ua_type);
1789 		mtx_unlock(&lun->lun_lock);
1790 	}
1791 }
1792 
1793 static int
1794 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1795 {
1796 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1797 	struct ctl_lun *lun;
1798 	struct ctl_lun_req ireq;
1799 	int error, value;
1800 
1801 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1802 	error = sysctl_handle_int(oidp, &value, 0, req);
1803 	if ((error != 0) || (req->newptr == NULL))
1804 		return (error);
1805 
1806 	mtx_lock(&softc->ctl_lock);
1807 	if (value == 0)
1808 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1809 	else
1810 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1811 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1812 		mtx_unlock(&softc->ctl_lock);
1813 		bzero(&ireq, sizeof(ireq));
1814 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1815 		ireq.reqdata.modify.lun_id = lun->lun;
1816 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1817 		    curthread);
1818 		if (ireq.status != CTL_LUN_OK) {
1819 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1820 			    __func__, ireq.status, ireq.error_str);
1821 		}
1822 		mtx_lock(&softc->ctl_lock);
1823 	}
1824 	mtx_unlock(&softc->ctl_lock);
1825 	return (0);
1826 }
1827 
1828 static int
1829 ctl_init(void)
1830 {
1831 	struct make_dev_args args;
1832 	struct ctl_softc *softc;
1833 	int i, error;
1834 
1835 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1836 			       M_WAITOK | M_ZERO);
1837 
1838 	make_dev_args_init(&args);
1839 	args.mda_devsw = &ctl_cdevsw;
1840 	args.mda_uid = UID_ROOT;
1841 	args.mda_gid = GID_OPERATOR;
1842 	args.mda_mode = 0600;
1843 	args.mda_si_drv1 = softc;
1844 	error = make_dev_s(&args, &softc->dev, "cam/ctl");
1845 	if (error != 0) {
1846 		free(softc, M_DEVBUF);
1847 		control_softc = NULL;
1848 		return (error);
1849 	}
1850 
1851 	sysctl_ctx_init(&softc->sysctl_ctx);
1852 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1853 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1854 		CTLFLAG_RD, 0, "CAM Target Layer");
1855 
1856 	if (softc->sysctl_tree == NULL) {
1857 		printf("%s: unable to allocate sysctl tree\n", __func__);
1858 		destroy_dev(softc->dev);
1859 		free(softc, M_DEVBUF);
1860 		control_softc = NULL;
1861 		return (ENOMEM);
1862 	}
1863 
1864 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1865 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1866 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1867 	softc->flags = 0;
1868 
1869 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1870 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1871 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1872 
1873 	/*
1874 	 * In Copan's HA scheme, the "master" and "slave" roles are
1875 	 * figured out through the slot the controller is in.  Although it
1876 	 * is an active/active system, someone has to be in charge.
1877 	 */
1878 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1879 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1880 	    "HA head ID (0 - no HA)");
1881 	if (softc->ha_id == 0 || softc->ha_id > NUM_HA_SHELVES) {
1882 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1883 		softc->is_single = 1;
1884 		softc->port_cnt = CTL_MAX_PORTS;
1885 		softc->port_min = 0;
1886 	} else {
1887 		softc->port_cnt = CTL_MAX_PORTS / NUM_HA_SHELVES;
1888 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1889 	}
1890 	softc->port_max = softc->port_min + softc->port_cnt;
1891 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1892 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1893 
1894 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1895 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1896 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1897 
1898 	STAILQ_INIT(&softc->lun_list);
1899 	STAILQ_INIT(&softc->pending_lun_queue);
1900 	STAILQ_INIT(&softc->fe_list);
1901 	STAILQ_INIT(&softc->port_list);
1902 	STAILQ_INIT(&softc->be_list);
1903 	ctl_tpc_init(softc);
1904 
1905 	if (worker_threads <= 0)
1906 		worker_threads = max(1, mp_ncpus / 4);
1907 	if (worker_threads > CTL_MAX_THREADS)
1908 		worker_threads = CTL_MAX_THREADS;
1909 
1910 	for (i = 0; i < worker_threads; i++) {
1911 		struct ctl_thread *thr = &softc->threads[i];
1912 
1913 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1914 		thr->ctl_softc = softc;
1915 		STAILQ_INIT(&thr->incoming_queue);
1916 		STAILQ_INIT(&thr->rtr_queue);
1917 		STAILQ_INIT(&thr->done_queue);
1918 		STAILQ_INIT(&thr->isc_queue);
1919 
1920 		error = kproc_kthread_add(ctl_work_thread, thr,
1921 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1922 		if (error != 0) {
1923 			printf("error creating CTL work thread!\n");
1924 			return (error);
1925 		}
1926 	}
1927 	error = kproc_kthread_add(ctl_lun_thread, softc,
1928 	    &softc->ctl_proc, &softc->lun_thread, 0, 0, "ctl", "lun");
1929 	if (error != 0) {
1930 		printf("error creating CTL lun thread!\n");
1931 		return (error);
1932 	}
1933 	error = kproc_kthread_add(ctl_thresh_thread, softc,
1934 	    &softc->ctl_proc, &softc->thresh_thread, 0, 0, "ctl", "thresh");
1935 	if (error != 0) {
1936 		printf("error creating CTL threshold thread!\n");
1937 		return (error);
1938 	}
1939 
1940 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1941 	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1942 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1943 
1944 	if (softc->is_single == 0) {
1945 		if (ctl_frontend_register(&ha_frontend) != 0)
1946 			softc->is_single = 1;
1947 	}
1948 	return (0);
1949 }
1950 
1951 static int
1952 ctl_shutdown(void)
1953 {
1954 	struct ctl_softc *softc = control_softc;
1955 	int i;
1956 
1957 	if (softc->is_single == 0)
1958 		ctl_frontend_deregister(&ha_frontend);
1959 
1960 	destroy_dev(softc->dev);
1961 
1962 	/* Shutdown CTL threads. */
1963 	softc->shutdown = 1;
1964 	for (i = 0; i < worker_threads; i++) {
1965 		struct ctl_thread *thr = &softc->threads[i];
1966 		while (thr->thread != NULL) {
1967 			wakeup(thr);
1968 			if (thr->thread != NULL)
1969 				pause("CTL thr shutdown", 1);
1970 		}
1971 		mtx_destroy(&thr->queue_lock);
1972 	}
1973 	while (softc->lun_thread != NULL) {
1974 		wakeup(&softc->pending_lun_queue);
1975 		if (softc->lun_thread != NULL)
1976 			pause("CTL thr shutdown", 1);
1977 	}
1978 	while (softc->thresh_thread != NULL) {
1979 		wakeup(softc->thresh_thread);
1980 		if (softc->thresh_thread != NULL)
1981 			pause("CTL thr shutdown", 1);
1982 	}
1983 
1984 	ctl_tpc_shutdown(softc);
1985 	uma_zdestroy(softc->io_zone);
1986 	mtx_destroy(&softc->ctl_lock);
1987 
1988 	sysctl_ctx_free(&softc->sysctl_ctx);
1989 
1990 	free(softc, M_DEVBUF);
1991 	control_softc = NULL;
1992 	return (0);
1993 }
1994 
1995 static int
1996 ctl_module_event_handler(module_t mod, int what, void *arg)
1997 {
1998 
1999 	switch (what) {
2000 	case MOD_LOAD:
2001 		return (ctl_init());
2002 	case MOD_UNLOAD:
2003 		return (ctl_shutdown());
2004 	default:
2005 		return (EOPNOTSUPP);
2006 	}
2007 }
2008 
2009 /*
2010  * XXX KDM should we do some access checks here?  Bump a reference count to
2011  * prevent a CTL module from being unloaded while someone has it open?
2012  */
2013 static int
2014 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
2015 {
2016 	return (0);
2017 }
2018 
2019 static int
2020 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
2021 {
2022 	return (0);
2023 }
2024 
2025 /*
2026  * Remove an initiator by port number and initiator ID.
2027  * Returns 0 for success, -1 for failure.
2028  */
2029 int
2030 ctl_remove_initiator(struct ctl_port *port, int iid)
2031 {
2032 	struct ctl_softc *softc = port->ctl_softc;
2033 	int last;
2034 
2035 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2036 
2037 	if (iid > CTL_MAX_INIT_PER_PORT) {
2038 		printf("%s: initiator ID %u > maximun %u!\n",
2039 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
2040 		return (-1);
2041 	}
2042 
2043 	mtx_lock(&softc->ctl_lock);
2044 	last = (--port->wwpn_iid[iid].in_use == 0);
2045 	port->wwpn_iid[iid].last_use = time_uptime;
2046 	mtx_unlock(&softc->ctl_lock);
2047 	if (last)
2048 		ctl_i_t_nexus_loss(softc, iid, CTL_UA_POWERON);
2049 	ctl_isc_announce_iid(port, iid);
2050 
2051 	return (0);
2052 }
2053 
2054 /*
2055  * Add an initiator to the initiator map.
2056  * Returns iid for success, < 0 for failure.
2057  */
2058 int
2059 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2060 {
2061 	struct ctl_softc *softc = port->ctl_softc;
2062 	time_t best_time;
2063 	int i, best;
2064 
2065 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2066 
2067 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2068 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2069 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2070 		free(name, M_CTL);
2071 		return (-1);
2072 	}
2073 
2074 	mtx_lock(&softc->ctl_lock);
2075 
2076 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2077 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2078 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2079 				iid = i;
2080 				break;
2081 			}
2082 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2083 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2084 				iid = i;
2085 				break;
2086 			}
2087 		}
2088 	}
2089 
2090 	if (iid < 0) {
2091 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2092 			if (port->wwpn_iid[i].in_use == 0 &&
2093 			    port->wwpn_iid[i].wwpn == 0 &&
2094 			    port->wwpn_iid[i].name == NULL) {
2095 				iid = i;
2096 				break;
2097 			}
2098 		}
2099 	}
2100 
2101 	if (iid < 0) {
2102 		best = -1;
2103 		best_time = INT32_MAX;
2104 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2105 			if (port->wwpn_iid[i].in_use == 0) {
2106 				if (port->wwpn_iid[i].last_use < best_time) {
2107 					best = i;
2108 					best_time = port->wwpn_iid[i].last_use;
2109 				}
2110 			}
2111 		}
2112 		iid = best;
2113 	}
2114 
2115 	if (iid < 0) {
2116 		mtx_unlock(&softc->ctl_lock);
2117 		free(name, M_CTL);
2118 		return (-2);
2119 	}
2120 
2121 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2122 		/*
2123 		 * This is not an error yet.
2124 		 */
2125 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2126 #if 0
2127 			printf("%s: port %d iid %u WWPN %#jx arrived"
2128 			    " again\n", __func__, port->targ_port,
2129 			    iid, (uintmax_t)wwpn);
2130 #endif
2131 			goto take;
2132 		}
2133 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2134 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2135 #if 0
2136 			printf("%s: port %d iid %u name '%s' arrived"
2137 			    " again\n", __func__, port->targ_port,
2138 			    iid, name);
2139 #endif
2140 			goto take;
2141 		}
2142 
2143 		/*
2144 		 * This is an error, but what do we do about it?  The
2145 		 * driver is telling us we have a new WWPN for this
2146 		 * initiator ID, so we pretty much need to use it.
2147 		 */
2148 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2149 		    " but WWPN %#jx '%s' is still at that address\n",
2150 		    __func__, port->targ_port, iid, wwpn, name,
2151 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2152 		    port->wwpn_iid[iid].name);
2153 	}
2154 take:
2155 	free(port->wwpn_iid[iid].name, M_CTL);
2156 	port->wwpn_iid[iid].name = name;
2157 	port->wwpn_iid[iid].wwpn = wwpn;
2158 	port->wwpn_iid[iid].in_use++;
2159 	mtx_unlock(&softc->ctl_lock);
2160 	ctl_isc_announce_iid(port, iid);
2161 
2162 	return (iid);
2163 }
2164 
2165 static int
2166 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2167 {
2168 	int len;
2169 
2170 	switch (port->port_type) {
2171 	case CTL_PORT_FC:
2172 	{
2173 		struct scsi_transportid_fcp *id =
2174 		    (struct scsi_transportid_fcp *)buf;
2175 		if (port->wwpn_iid[iid].wwpn == 0)
2176 			return (0);
2177 		memset(id, 0, sizeof(*id));
2178 		id->format_protocol = SCSI_PROTO_FC;
2179 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2180 		return (sizeof(*id));
2181 	}
2182 	case CTL_PORT_ISCSI:
2183 	{
2184 		struct scsi_transportid_iscsi_port *id =
2185 		    (struct scsi_transportid_iscsi_port *)buf;
2186 		if (port->wwpn_iid[iid].name == NULL)
2187 			return (0);
2188 		memset(id, 0, 256);
2189 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2190 		    SCSI_PROTO_ISCSI;
2191 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2192 		len = roundup2(min(len, 252), 4);
2193 		scsi_ulto2b(len, id->additional_length);
2194 		return (sizeof(*id) + len);
2195 	}
2196 	case CTL_PORT_SAS:
2197 	{
2198 		struct scsi_transportid_sas *id =
2199 		    (struct scsi_transportid_sas *)buf;
2200 		if (port->wwpn_iid[iid].wwpn == 0)
2201 			return (0);
2202 		memset(id, 0, sizeof(*id));
2203 		id->format_protocol = SCSI_PROTO_SAS;
2204 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2205 		return (sizeof(*id));
2206 	}
2207 	default:
2208 	{
2209 		struct scsi_transportid_spi *id =
2210 		    (struct scsi_transportid_spi *)buf;
2211 		memset(id, 0, sizeof(*id));
2212 		id->format_protocol = SCSI_PROTO_SPI;
2213 		scsi_ulto2b(iid, id->scsi_addr);
2214 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2215 		return (sizeof(*id));
2216 	}
2217 	}
2218 }
2219 
2220 /*
2221  * Serialize a command that went down the "wrong" side, and so was sent to
2222  * this controller for execution.  The logic is a little different than the
2223  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2224  * sent back to the other side, but in the success case, we execute the
2225  * command on this side (XFER mode) or tell the other side to execute it
2226  * (SER_ONLY mode).
2227  */
2228 static void
2229 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2230 {
2231 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
2232 	struct ctl_port *port = CTL_PORT(ctsio);
2233 	union ctl_ha_msg msg_info;
2234 	struct ctl_lun *lun;
2235 	const struct ctl_cmd_entry *entry;
2236 	uint32_t targ_lun;
2237 
2238 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2239 
2240 	/* Make sure that we know about this port. */
2241 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2242 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2243 					 /*retry_count*/ 1);
2244 		goto badjuju;
2245 	}
2246 
2247 	/* Make sure that we know about this LUN. */
2248 	mtx_lock(&softc->ctl_lock);
2249 	if (targ_lun >= CTL_MAX_LUNS ||
2250 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
2251 		mtx_unlock(&softc->ctl_lock);
2252 
2253 		/*
2254 		 * The other node would not send this request to us unless
2255 		 * received announce that we are primary node for this LUN.
2256 		 * If this LUN does not exist now, it is probably result of
2257 		 * a race, so respond to initiator in the most opaque way.
2258 		 */
2259 		ctl_set_busy(ctsio);
2260 		goto badjuju;
2261 	}
2262 	mtx_lock(&lun->lun_lock);
2263 	mtx_unlock(&softc->ctl_lock);
2264 
2265 	/*
2266 	 * If the LUN is invalid, pretend that it doesn't exist.
2267 	 * It will go away as soon as all pending I/Os completed.
2268 	 */
2269 	if (lun->flags & CTL_LUN_DISABLED) {
2270 		mtx_unlock(&lun->lun_lock);
2271 		ctl_set_busy(ctsio);
2272 		goto badjuju;
2273 	}
2274 
2275 	entry = ctl_get_cmd_entry(ctsio, NULL);
2276 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2277 		mtx_unlock(&lun->lun_lock);
2278 		goto badjuju;
2279 	}
2280 
2281 	CTL_LUN(ctsio) = lun;
2282 	CTL_BACKEND_LUN(ctsio) = lun->be_lun;
2283 
2284 	/*
2285 	 * Every I/O goes into the OOA queue for a
2286 	 * particular LUN, and stays there until completion.
2287 	 */
2288 #ifdef CTL_TIME_IO
2289 	if (TAILQ_EMPTY(&lun->ooa_queue))
2290 		lun->idle_time += getsbinuptime() - lun->last_busy;
2291 #endif
2292 	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2293 
2294 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2295 		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2296 		 ooa_links))) {
2297 	case CTL_ACTION_BLOCK:
2298 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2299 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2300 				  blocked_links);
2301 		mtx_unlock(&lun->lun_lock);
2302 		break;
2303 	case CTL_ACTION_PASS:
2304 	case CTL_ACTION_SKIP:
2305 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2306 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2307 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2308 			mtx_unlock(&lun->lun_lock);
2309 		} else {
2310 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2311 			mtx_unlock(&lun->lun_lock);
2312 
2313 			/* send msg back to other side */
2314 			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2315 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2316 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2317 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2318 			    sizeof(msg_info.hdr), M_WAITOK);
2319 		}
2320 		break;
2321 	case CTL_ACTION_OVERLAP:
2322 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2323 		mtx_unlock(&lun->lun_lock);
2324 		ctl_set_overlapped_cmd(ctsio);
2325 		goto badjuju;
2326 	case CTL_ACTION_OVERLAP_TAG:
2327 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2328 		mtx_unlock(&lun->lun_lock);
2329 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2330 		goto badjuju;
2331 	case CTL_ACTION_ERROR:
2332 	default:
2333 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2334 		mtx_unlock(&lun->lun_lock);
2335 
2336 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2337 					 /*retry_count*/ 0);
2338 badjuju:
2339 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2340 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2341 		msg_info.hdr.serializing_sc = NULL;
2342 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2343 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2344 		    sizeof(msg_info.scsi), M_WAITOK);
2345 		ctl_free_io((union ctl_io *)ctsio);
2346 		break;
2347 	}
2348 }
2349 
2350 /*
2351  * Returns 0 for success, errno for failure.
2352  */
2353 static void
2354 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2355 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2356 {
2357 	union ctl_io *io;
2358 
2359 	mtx_lock(&lun->lun_lock);
2360 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2361 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2362 	     ooa_links)) {
2363 		struct ctl_ooa_entry *entry;
2364 
2365 		/*
2366 		 * If we've got more than we can fit, just count the
2367 		 * remaining entries.
2368 		 */
2369 		if (*cur_fill_num >= ooa_hdr->alloc_num)
2370 			continue;
2371 
2372 		entry = &kern_entries[*cur_fill_num];
2373 
2374 		entry->tag_num = io->scsiio.tag_num;
2375 		entry->lun_num = lun->lun;
2376 #ifdef CTL_TIME_IO
2377 		entry->start_bt = io->io_hdr.start_bt;
2378 #endif
2379 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2380 		entry->cdb_len = io->scsiio.cdb_len;
2381 		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2382 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2383 
2384 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2385 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2386 
2387 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2388 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2389 
2390 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2391 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2392 
2393 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2394 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2395 	}
2396 	mtx_unlock(&lun->lun_lock);
2397 }
2398 
2399 static void *
2400 ctl_copyin_alloc(void *user_addr, unsigned int len, char *error_str,
2401 		 size_t error_str_len)
2402 {
2403 	void *kptr;
2404 
2405 	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2406 
2407 	if (copyin(user_addr, kptr, len) != 0) {
2408 		snprintf(error_str, error_str_len, "Error copying %d bytes "
2409 			 "from user address %p to kernel address %p", len,
2410 			 user_addr, kptr);
2411 		free(kptr, M_CTL);
2412 		return (NULL);
2413 	}
2414 
2415 	return (kptr);
2416 }
2417 
2418 static void
2419 ctl_free_args(int num_args, struct ctl_be_arg *args)
2420 {
2421 	int i;
2422 
2423 	if (args == NULL)
2424 		return;
2425 
2426 	for (i = 0; i < num_args; i++) {
2427 		free(args[i].kname, M_CTL);
2428 		free(args[i].kvalue, M_CTL);
2429 	}
2430 
2431 	free(args, M_CTL);
2432 }
2433 
2434 static struct ctl_be_arg *
2435 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2436 		char *error_str, size_t error_str_len)
2437 {
2438 	struct ctl_be_arg *args;
2439 	int i;
2440 
2441 	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2442 				error_str, error_str_len);
2443 
2444 	if (args == NULL)
2445 		goto bailout;
2446 
2447 	for (i = 0; i < num_args; i++) {
2448 		args[i].kname = NULL;
2449 		args[i].kvalue = NULL;
2450 	}
2451 
2452 	for (i = 0; i < num_args; i++) {
2453 		uint8_t *tmpptr;
2454 
2455 		if (args[i].namelen == 0) {
2456 			snprintf(error_str, error_str_len, "Argument %d "
2457 				 "name length is zero", i);
2458 			goto bailout;
2459 		}
2460 
2461 		args[i].kname = ctl_copyin_alloc(args[i].name,
2462 			args[i].namelen, error_str, error_str_len);
2463 		if (args[i].kname == NULL)
2464 			goto bailout;
2465 
2466 		if (args[i].kname[args[i].namelen - 1] != '\0') {
2467 			snprintf(error_str, error_str_len, "Argument %d "
2468 				 "name is not NUL-terminated", i);
2469 			goto bailout;
2470 		}
2471 
2472 		if (args[i].flags & CTL_BEARG_RD) {
2473 			if (args[i].vallen == 0) {
2474 				snprintf(error_str, error_str_len, "Argument %d "
2475 					 "value length is zero", i);
2476 				goto bailout;
2477 			}
2478 
2479 			tmpptr = ctl_copyin_alloc(args[i].value,
2480 				args[i].vallen, error_str, error_str_len);
2481 			if (tmpptr == NULL)
2482 				goto bailout;
2483 
2484 			if ((args[i].flags & CTL_BEARG_ASCII)
2485 			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2486 				snprintf(error_str, error_str_len, "Argument "
2487 				    "%d value is not NUL-terminated", i);
2488 				free(tmpptr, M_CTL);
2489 				goto bailout;
2490 			}
2491 			args[i].kvalue = tmpptr;
2492 		} else {
2493 			args[i].kvalue = malloc(args[i].vallen,
2494 			    M_CTL, M_WAITOK | M_ZERO);
2495 		}
2496 	}
2497 
2498 	return (args);
2499 bailout:
2500 
2501 	ctl_free_args(num_args, args);
2502 
2503 	return (NULL);
2504 }
2505 
2506 static void
2507 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2508 {
2509 	int i;
2510 
2511 	for (i = 0; i < num_args; i++) {
2512 		if (args[i].flags & CTL_BEARG_WR)
2513 			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2514 	}
2515 }
2516 
2517 /*
2518  * Escape characters that are illegal or not recommended in XML.
2519  */
2520 int
2521 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2522 {
2523 	char *end = str + size;
2524 	int retval;
2525 
2526 	retval = 0;
2527 
2528 	for (; *str && str < end; str++) {
2529 		switch (*str) {
2530 		case '&':
2531 			retval = sbuf_printf(sb, "&amp;");
2532 			break;
2533 		case '>':
2534 			retval = sbuf_printf(sb, "&gt;");
2535 			break;
2536 		case '<':
2537 			retval = sbuf_printf(sb, "&lt;");
2538 			break;
2539 		default:
2540 			retval = sbuf_putc(sb, *str);
2541 			break;
2542 		}
2543 
2544 		if (retval != 0)
2545 			break;
2546 
2547 	}
2548 
2549 	return (retval);
2550 }
2551 
2552 static void
2553 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2554 {
2555 	struct scsi_vpd_id_descriptor *desc;
2556 	int i;
2557 
2558 	if (id == NULL || id->len < 4)
2559 		return;
2560 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2561 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2562 	case SVPD_ID_TYPE_T10:
2563 		sbuf_printf(sb, "t10.");
2564 		break;
2565 	case SVPD_ID_TYPE_EUI64:
2566 		sbuf_printf(sb, "eui.");
2567 		break;
2568 	case SVPD_ID_TYPE_NAA:
2569 		sbuf_printf(sb, "naa.");
2570 		break;
2571 	case SVPD_ID_TYPE_SCSI_NAME:
2572 		break;
2573 	}
2574 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2575 	case SVPD_ID_CODESET_BINARY:
2576 		for (i = 0; i < desc->length; i++)
2577 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2578 		break;
2579 	case SVPD_ID_CODESET_ASCII:
2580 		sbuf_printf(sb, "%.*s", (int)desc->length,
2581 		    (char *)desc->identifier);
2582 		break;
2583 	case SVPD_ID_CODESET_UTF8:
2584 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2585 		break;
2586 	}
2587 }
2588 
2589 static int
2590 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2591 	  struct thread *td)
2592 {
2593 	struct ctl_softc *softc = dev->si_drv1;
2594 	struct ctl_port *port;
2595 	struct ctl_lun *lun;
2596 	int retval;
2597 
2598 	retval = 0;
2599 
2600 	switch (cmd) {
2601 	case CTL_IO:
2602 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2603 		break;
2604 	case CTL_ENABLE_PORT:
2605 	case CTL_DISABLE_PORT:
2606 	case CTL_SET_PORT_WWNS: {
2607 		struct ctl_port *port;
2608 		struct ctl_port_entry *entry;
2609 
2610 		entry = (struct ctl_port_entry *)addr;
2611 
2612 		mtx_lock(&softc->ctl_lock);
2613 		STAILQ_FOREACH(port, &softc->port_list, links) {
2614 			int action, done;
2615 
2616 			if (port->targ_port < softc->port_min ||
2617 			    port->targ_port >= softc->port_max)
2618 				continue;
2619 
2620 			action = 0;
2621 			done = 0;
2622 			if ((entry->port_type == CTL_PORT_NONE)
2623 			 && (entry->targ_port == port->targ_port)) {
2624 				/*
2625 				 * If the user only wants to enable or
2626 				 * disable or set WWNs on a specific port,
2627 				 * do the operation and we're done.
2628 				 */
2629 				action = 1;
2630 				done = 1;
2631 			} else if (entry->port_type & port->port_type) {
2632 				/*
2633 				 * Compare the user's type mask with the
2634 				 * particular frontend type to see if we
2635 				 * have a match.
2636 				 */
2637 				action = 1;
2638 				done = 0;
2639 
2640 				/*
2641 				 * Make sure the user isn't trying to set
2642 				 * WWNs on multiple ports at the same time.
2643 				 */
2644 				if (cmd == CTL_SET_PORT_WWNS) {
2645 					printf("%s: Can't set WWNs on "
2646 					       "multiple ports\n", __func__);
2647 					retval = EINVAL;
2648 					break;
2649 				}
2650 			}
2651 			if (action == 0)
2652 				continue;
2653 
2654 			/*
2655 			 * XXX KDM we have to drop the lock here, because
2656 			 * the online/offline operations can potentially
2657 			 * block.  We need to reference count the frontends
2658 			 * so they can't go away,
2659 			 */
2660 			if (cmd == CTL_ENABLE_PORT) {
2661 				mtx_unlock(&softc->ctl_lock);
2662 				ctl_port_online(port);
2663 				mtx_lock(&softc->ctl_lock);
2664 			} else if (cmd == CTL_DISABLE_PORT) {
2665 				mtx_unlock(&softc->ctl_lock);
2666 				ctl_port_offline(port);
2667 				mtx_lock(&softc->ctl_lock);
2668 			} else if (cmd == CTL_SET_PORT_WWNS) {
2669 				ctl_port_set_wwns(port,
2670 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2671 				    1 : 0, entry->wwnn,
2672 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2673 				    1 : 0, entry->wwpn);
2674 			}
2675 			if (done != 0)
2676 				break;
2677 		}
2678 		mtx_unlock(&softc->ctl_lock);
2679 		break;
2680 	}
2681 	case CTL_GET_OOA: {
2682 		struct ctl_ooa *ooa_hdr;
2683 		struct ctl_ooa_entry *entries;
2684 		uint32_t cur_fill_num;
2685 
2686 		ooa_hdr = (struct ctl_ooa *)addr;
2687 
2688 		if ((ooa_hdr->alloc_len == 0)
2689 		 || (ooa_hdr->alloc_num == 0)) {
2690 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2691 			       "must be non-zero\n", __func__,
2692 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2693 			retval = EINVAL;
2694 			break;
2695 		}
2696 
2697 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2698 		    sizeof(struct ctl_ooa_entry))) {
2699 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2700 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2701 			       __func__, ooa_hdr->alloc_len,
2702 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2703 			retval = EINVAL;
2704 			break;
2705 		}
2706 
2707 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2708 		if (entries == NULL) {
2709 			printf("%s: could not allocate %d bytes for OOA "
2710 			       "dump\n", __func__, ooa_hdr->alloc_len);
2711 			retval = ENOMEM;
2712 			break;
2713 		}
2714 
2715 		mtx_lock(&softc->ctl_lock);
2716 		if ((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0 &&
2717 		    (ooa_hdr->lun_num >= CTL_MAX_LUNS ||
2718 		     softc->ctl_luns[ooa_hdr->lun_num] == NULL)) {
2719 			mtx_unlock(&softc->ctl_lock);
2720 			free(entries, M_CTL);
2721 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2722 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2723 			retval = EINVAL;
2724 			break;
2725 		}
2726 
2727 		cur_fill_num = 0;
2728 
2729 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2730 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2731 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2732 				    ooa_hdr, entries);
2733 			}
2734 		} else {
2735 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2736 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2737 			    entries);
2738 		}
2739 		mtx_unlock(&softc->ctl_lock);
2740 
2741 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2742 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2743 			sizeof(struct ctl_ooa_entry);
2744 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2745 		if (retval != 0) {
2746 			printf("%s: error copying out %d bytes for OOA dump\n",
2747 			       __func__, ooa_hdr->fill_len);
2748 		}
2749 
2750 		getbinuptime(&ooa_hdr->cur_bt);
2751 
2752 		if (cur_fill_num > ooa_hdr->alloc_num) {
2753 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2754 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2755 		} else {
2756 			ooa_hdr->dropped_num = 0;
2757 			ooa_hdr->status = CTL_OOA_OK;
2758 		}
2759 
2760 		free(entries, M_CTL);
2761 		break;
2762 	}
2763 	case CTL_DELAY_IO: {
2764 		struct ctl_io_delay_info *delay_info;
2765 
2766 		delay_info = (struct ctl_io_delay_info *)addr;
2767 
2768 #ifdef CTL_IO_DELAY
2769 		mtx_lock(&softc->ctl_lock);
2770 		if (delay_info->lun_id >= CTL_MAX_LUNS ||
2771 		    (lun = softc->ctl_luns[delay_info->lun_id]) == NULL) {
2772 			mtx_unlock(&softc->ctl_lock);
2773 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2774 			break;
2775 		}
2776 		mtx_lock(&lun->lun_lock);
2777 		mtx_unlock(&softc->ctl_lock);
2778 		delay_info->status = CTL_DELAY_STATUS_OK;
2779 		switch (delay_info->delay_type) {
2780 		case CTL_DELAY_TYPE_CONT:
2781 		case CTL_DELAY_TYPE_ONESHOT:
2782 			break;
2783 		default:
2784 			delay_info->status = CTL_DELAY_STATUS_INVALID_TYPE;
2785 			break;
2786 		}
2787 		switch (delay_info->delay_loc) {
2788 		case CTL_DELAY_LOC_DATAMOVE:
2789 			lun->delay_info.datamove_type = delay_info->delay_type;
2790 			lun->delay_info.datamove_delay = delay_info->delay_secs;
2791 			break;
2792 		case CTL_DELAY_LOC_DONE:
2793 			lun->delay_info.done_type = delay_info->delay_type;
2794 			lun->delay_info.done_delay = delay_info->delay_secs;
2795 			break;
2796 		default:
2797 			delay_info->status = CTL_DELAY_STATUS_INVALID_LOC;
2798 			break;
2799 		}
2800 		mtx_unlock(&lun->lun_lock);
2801 #else
2802 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2803 #endif /* CTL_IO_DELAY */
2804 		break;
2805 	}
2806 #ifdef CTL_LEGACY_STATS
2807 	case CTL_GETSTATS: {
2808 		struct ctl_stats *stats = (struct ctl_stats *)addr;
2809 		int i;
2810 
2811 		/*
2812 		 * XXX KDM no locking here.  If the LUN list changes,
2813 		 * things can blow up.
2814 		 */
2815 		i = 0;
2816 		stats->status = CTL_SS_OK;
2817 		stats->fill_len = 0;
2818 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2819 			if (stats->fill_len + sizeof(lun->legacy_stats) >
2820 			    stats->alloc_len) {
2821 				stats->status = CTL_SS_NEED_MORE_SPACE;
2822 				break;
2823 			}
2824 			retval = copyout(&lun->legacy_stats, &stats->lun_stats[i++],
2825 					 sizeof(lun->legacy_stats));
2826 			if (retval != 0)
2827 				break;
2828 			stats->fill_len += sizeof(lun->legacy_stats);
2829 		}
2830 		stats->num_luns = softc->num_luns;
2831 		stats->flags = CTL_STATS_FLAG_NONE;
2832 #ifdef CTL_TIME_IO
2833 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
2834 #endif
2835 		getnanouptime(&stats->timestamp);
2836 		break;
2837 	}
2838 #endif /* CTL_LEGACY_STATS */
2839 	case CTL_ERROR_INJECT: {
2840 		struct ctl_error_desc *err_desc, *new_err_desc;
2841 
2842 		err_desc = (struct ctl_error_desc *)addr;
2843 
2844 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2845 				      M_WAITOK | M_ZERO);
2846 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2847 
2848 		mtx_lock(&softc->ctl_lock);
2849 		if (err_desc->lun_id >= CTL_MAX_LUNS ||
2850 		    (lun = softc->ctl_luns[err_desc->lun_id]) == NULL) {
2851 			mtx_unlock(&softc->ctl_lock);
2852 			free(new_err_desc, M_CTL);
2853 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2854 			       __func__, (uintmax_t)err_desc->lun_id);
2855 			retval = EINVAL;
2856 			break;
2857 		}
2858 		mtx_lock(&lun->lun_lock);
2859 		mtx_unlock(&softc->ctl_lock);
2860 
2861 		/*
2862 		 * We could do some checking here to verify the validity
2863 		 * of the request, but given the complexity of error
2864 		 * injection requests, the checking logic would be fairly
2865 		 * complex.
2866 		 *
2867 		 * For now, if the request is invalid, it just won't get
2868 		 * executed and might get deleted.
2869 		 */
2870 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2871 
2872 		/*
2873 		 * XXX KDM check to make sure the serial number is unique,
2874 		 * in case we somehow manage to wrap.  That shouldn't
2875 		 * happen for a very long time, but it's the right thing to
2876 		 * do.
2877 		 */
2878 		new_err_desc->serial = lun->error_serial;
2879 		err_desc->serial = lun->error_serial;
2880 		lun->error_serial++;
2881 
2882 		mtx_unlock(&lun->lun_lock);
2883 		break;
2884 	}
2885 	case CTL_ERROR_INJECT_DELETE: {
2886 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2887 		int delete_done;
2888 
2889 		delete_desc = (struct ctl_error_desc *)addr;
2890 		delete_done = 0;
2891 
2892 		mtx_lock(&softc->ctl_lock);
2893 		if (delete_desc->lun_id >= CTL_MAX_LUNS ||
2894 		    (lun = softc->ctl_luns[delete_desc->lun_id]) == NULL) {
2895 			mtx_unlock(&softc->ctl_lock);
2896 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2897 			       __func__, (uintmax_t)delete_desc->lun_id);
2898 			retval = EINVAL;
2899 			break;
2900 		}
2901 		mtx_lock(&lun->lun_lock);
2902 		mtx_unlock(&softc->ctl_lock);
2903 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2904 			if (desc->serial != delete_desc->serial)
2905 				continue;
2906 
2907 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2908 				      links);
2909 			free(desc, M_CTL);
2910 			delete_done = 1;
2911 		}
2912 		mtx_unlock(&lun->lun_lock);
2913 		if (delete_done == 0) {
2914 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2915 			       "error serial %ju on LUN %u\n", __func__,
2916 			       delete_desc->serial, delete_desc->lun_id);
2917 			retval = EINVAL;
2918 			break;
2919 		}
2920 		break;
2921 	}
2922 	case CTL_DUMP_STRUCTS: {
2923 		int j, k;
2924 		struct ctl_port *port;
2925 		struct ctl_frontend *fe;
2926 
2927 		mtx_lock(&softc->ctl_lock);
2928 		printf("CTL Persistent Reservation information start:\n");
2929 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2930 			mtx_lock(&lun->lun_lock);
2931 			if ((lun->flags & CTL_LUN_DISABLED) != 0) {
2932 				mtx_unlock(&lun->lun_lock);
2933 				continue;
2934 			}
2935 
2936 			for (j = 0; j < CTL_MAX_PORTS; j++) {
2937 				if (lun->pr_keys[j] == NULL)
2938 					continue;
2939 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2940 					if (lun->pr_keys[j][k] == 0)
2941 						continue;
2942 					printf("  LUN %ju port %d iid %d key "
2943 					       "%#jx\n", lun->lun, j, k,
2944 					       (uintmax_t)lun->pr_keys[j][k]);
2945 				}
2946 			}
2947 			mtx_unlock(&lun->lun_lock);
2948 		}
2949 		printf("CTL Persistent Reservation information end\n");
2950 		printf("CTL Ports:\n");
2951 		STAILQ_FOREACH(port, &softc->port_list, links) {
2952 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2953 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2954 			       port->frontend->name, port->port_type,
2955 			       port->physical_port, port->virtual_port,
2956 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2957 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2958 				if (port->wwpn_iid[j].in_use == 0 &&
2959 				    port->wwpn_iid[j].wwpn == 0 &&
2960 				    port->wwpn_iid[j].name == NULL)
2961 					continue;
2962 
2963 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2964 				    j, port->wwpn_iid[j].in_use,
2965 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2966 				    port->wwpn_iid[j].name);
2967 			}
2968 		}
2969 		printf("CTL Port information end\n");
2970 		mtx_unlock(&softc->ctl_lock);
2971 		/*
2972 		 * XXX KDM calling this without a lock.  We'd likely want
2973 		 * to drop the lock before calling the frontend's dump
2974 		 * routine anyway.
2975 		 */
2976 		printf("CTL Frontends:\n");
2977 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2978 			printf("  Frontend '%s'\n", fe->name);
2979 			if (fe->fe_dump != NULL)
2980 				fe->fe_dump();
2981 		}
2982 		printf("CTL Frontend information end\n");
2983 		break;
2984 	}
2985 	case CTL_LUN_REQ: {
2986 		struct ctl_lun_req *lun_req;
2987 		struct ctl_backend_driver *backend;
2988 
2989 		lun_req = (struct ctl_lun_req *)addr;
2990 
2991 		backend = ctl_backend_find(lun_req->backend);
2992 		if (backend == NULL) {
2993 			lun_req->status = CTL_LUN_ERROR;
2994 			snprintf(lun_req->error_str,
2995 				 sizeof(lun_req->error_str),
2996 				 "Backend \"%s\" not found.",
2997 				 lun_req->backend);
2998 			break;
2999 		}
3000 		if (lun_req->num_be_args > 0) {
3001 			lun_req->kern_be_args = ctl_copyin_args(
3002 				lun_req->num_be_args,
3003 				lun_req->be_args,
3004 				lun_req->error_str,
3005 				sizeof(lun_req->error_str));
3006 			if (lun_req->kern_be_args == NULL) {
3007 				lun_req->status = CTL_LUN_ERROR;
3008 				break;
3009 			}
3010 		}
3011 
3012 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3013 
3014 		if (lun_req->num_be_args > 0) {
3015 			ctl_copyout_args(lun_req->num_be_args,
3016 				      lun_req->kern_be_args);
3017 			ctl_free_args(lun_req->num_be_args,
3018 				      lun_req->kern_be_args);
3019 		}
3020 		break;
3021 	}
3022 	case CTL_LUN_LIST: {
3023 		struct sbuf *sb;
3024 		struct ctl_lun_list *list;
3025 		struct ctl_option *opt;
3026 
3027 		list = (struct ctl_lun_list *)addr;
3028 
3029 		/*
3030 		 * Allocate a fixed length sbuf here, based on the length
3031 		 * of the user's buffer.  We could allocate an auto-extending
3032 		 * buffer, and then tell the user how much larger our
3033 		 * amount of data is than his buffer, but that presents
3034 		 * some problems:
3035 		 *
3036 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3037 		 *     we can't hold a lock while calling them with an
3038 		 *     auto-extending buffer.
3039  		 *
3040 		 * 2.  There is not currently a LUN reference counting
3041 		 *     mechanism, outside of outstanding transactions on
3042 		 *     the LUN's OOA queue.  So a LUN could go away on us
3043 		 *     while we're getting the LUN number, backend-specific
3044 		 *     information, etc.  Thus, given the way things
3045 		 *     currently work, we need to hold the CTL lock while
3046 		 *     grabbing LUN information.
3047 		 *
3048 		 * So, from the user's standpoint, the best thing to do is
3049 		 * allocate what he thinks is a reasonable buffer length,
3050 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3051 		 * double the buffer length and try again.  (And repeat
3052 		 * that until he succeeds.)
3053 		 */
3054 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3055 		if (sb == NULL) {
3056 			list->status = CTL_LUN_LIST_ERROR;
3057 			snprintf(list->error_str, sizeof(list->error_str),
3058 				 "Unable to allocate %d bytes for LUN list",
3059 				 list->alloc_len);
3060 			break;
3061 		}
3062 
3063 		sbuf_printf(sb, "<ctllunlist>\n");
3064 
3065 		mtx_lock(&softc->ctl_lock);
3066 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3067 			mtx_lock(&lun->lun_lock);
3068 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3069 					     (uintmax_t)lun->lun);
3070 
3071 			/*
3072 			 * Bail out as soon as we see that we've overfilled
3073 			 * the buffer.
3074 			 */
3075 			if (retval != 0)
3076 				break;
3077 
3078 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3079 					     "</backend_type>\n",
3080 					     (lun->backend == NULL) ?  "none" :
3081 					     lun->backend->name);
3082 
3083 			if (retval != 0)
3084 				break;
3085 
3086 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3087 					     lun->be_lun->lun_type);
3088 
3089 			if (retval != 0)
3090 				break;
3091 
3092 			if (lun->backend == NULL) {
3093 				retval = sbuf_printf(sb, "</lun>\n");
3094 				if (retval != 0)
3095 					break;
3096 				continue;
3097 			}
3098 
3099 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3100 					     (lun->be_lun->maxlba > 0) ?
3101 					     lun->be_lun->maxlba + 1 : 0);
3102 
3103 			if (retval != 0)
3104 				break;
3105 
3106 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3107 					     lun->be_lun->blocksize);
3108 
3109 			if (retval != 0)
3110 				break;
3111 
3112 			retval = sbuf_printf(sb, "\t<serial_number>");
3113 
3114 			if (retval != 0)
3115 				break;
3116 
3117 			retval = ctl_sbuf_printf_esc(sb,
3118 			    lun->be_lun->serial_num,
3119 			    sizeof(lun->be_lun->serial_num));
3120 
3121 			if (retval != 0)
3122 				break;
3123 
3124 			retval = sbuf_printf(sb, "</serial_number>\n");
3125 
3126 			if (retval != 0)
3127 				break;
3128 
3129 			retval = sbuf_printf(sb, "\t<device_id>");
3130 
3131 			if (retval != 0)
3132 				break;
3133 
3134 			retval = ctl_sbuf_printf_esc(sb,
3135 			    lun->be_lun->device_id,
3136 			    sizeof(lun->be_lun->device_id));
3137 
3138 			if (retval != 0)
3139 				break;
3140 
3141 			retval = sbuf_printf(sb, "</device_id>\n");
3142 
3143 			if (retval != 0)
3144 				break;
3145 
3146 			if (lun->backend->lun_info != NULL) {
3147 				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3148 				if (retval != 0)
3149 					break;
3150 			}
3151 			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3152 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3153 				    opt->name, opt->value, opt->name);
3154 				if (retval != 0)
3155 					break;
3156 			}
3157 
3158 			retval = sbuf_printf(sb, "</lun>\n");
3159 
3160 			if (retval != 0)
3161 				break;
3162 			mtx_unlock(&lun->lun_lock);
3163 		}
3164 		if (lun != NULL)
3165 			mtx_unlock(&lun->lun_lock);
3166 		mtx_unlock(&softc->ctl_lock);
3167 
3168 		if ((retval != 0)
3169 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3170 			retval = 0;
3171 			sbuf_delete(sb);
3172 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3173 			snprintf(list->error_str, sizeof(list->error_str),
3174 				 "Out of space, %d bytes is too small",
3175 				 list->alloc_len);
3176 			break;
3177 		}
3178 
3179 		sbuf_finish(sb);
3180 
3181 		retval = copyout(sbuf_data(sb), list->lun_xml,
3182 				 sbuf_len(sb) + 1);
3183 
3184 		list->fill_len = sbuf_len(sb) + 1;
3185 		list->status = CTL_LUN_LIST_OK;
3186 		sbuf_delete(sb);
3187 		break;
3188 	}
3189 	case CTL_ISCSI: {
3190 		struct ctl_iscsi *ci;
3191 		struct ctl_frontend *fe;
3192 
3193 		ci = (struct ctl_iscsi *)addr;
3194 
3195 		fe = ctl_frontend_find("iscsi");
3196 		if (fe == NULL) {
3197 			ci->status = CTL_ISCSI_ERROR;
3198 			snprintf(ci->error_str, sizeof(ci->error_str),
3199 			    "Frontend \"iscsi\" not found.");
3200 			break;
3201 		}
3202 
3203 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3204 		break;
3205 	}
3206 	case CTL_PORT_REQ: {
3207 		struct ctl_req *req;
3208 		struct ctl_frontend *fe;
3209 
3210 		req = (struct ctl_req *)addr;
3211 
3212 		fe = ctl_frontend_find(req->driver);
3213 		if (fe == NULL) {
3214 			req->status = CTL_LUN_ERROR;
3215 			snprintf(req->error_str, sizeof(req->error_str),
3216 			    "Frontend \"%s\" not found.", req->driver);
3217 			break;
3218 		}
3219 		if (req->num_args > 0) {
3220 			req->kern_args = ctl_copyin_args(req->num_args,
3221 			    req->args, req->error_str, sizeof(req->error_str));
3222 			if (req->kern_args == NULL) {
3223 				req->status = CTL_LUN_ERROR;
3224 				break;
3225 			}
3226 		}
3227 
3228 		if (fe->ioctl)
3229 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3230 		else
3231 			retval = ENODEV;
3232 
3233 		if (req->num_args > 0) {
3234 			ctl_copyout_args(req->num_args, req->kern_args);
3235 			ctl_free_args(req->num_args, req->kern_args);
3236 		}
3237 		break;
3238 	}
3239 	case CTL_PORT_LIST: {
3240 		struct sbuf *sb;
3241 		struct ctl_port *port;
3242 		struct ctl_lun_list *list;
3243 		struct ctl_option *opt;
3244 		int j;
3245 		uint32_t plun;
3246 
3247 		list = (struct ctl_lun_list *)addr;
3248 
3249 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3250 		if (sb == NULL) {
3251 			list->status = CTL_LUN_LIST_ERROR;
3252 			snprintf(list->error_str, sizeof(list->error_str),
3253 				 "Unable to allocate %d bytes for LUN list",
3254 				 list->alloc_len);
3255 			break;
3256 		}
3257 
3258 		sbuf_printf(sb, "<ctlportlist>\n");
3259 
3260 		mtx_lock(&softc->ctl_lock);
3261 		STAILQ_FOREACH(port, &softc->port_list, links) {
3262 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3263 					     (uintmax_t)port->targ_port);
3264 
3265 			/*
3266 			 * Bail out as soon as we see that we've overfilled
3267 			 * the buffer.
3268 			 */
3269 			if (retval != 0)
3270 				break;
3271 
3272 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3273 			    "</frontend_type>\n", port->frontend->name);
3274 			if (retval != 0)
3275 				break;
3276 
3277 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3278 					     port->port_type);
3279 			if (retval != 0)
3280 				break;
3281 
3282 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3283 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3284 			if (retval != 0)
3285 				break;
3286 
3287 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3288 			    port->port_name);
3289 			if (retval != 0)
3290 				break;
3291 
3292 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3293 			    port->physical_port);
3294 			if (retval != 0)
3295 				break;
3296 
3297 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3298 			    port->virtual_port);
3299 			if (retval != 0)
3300 				break;
3301 
3302 			if (port->target_devid != NULL) {
3303 				sbuf_printf(sb, "\t<target>");
3304 				ctl_id_sbuf(port->target_devid, sb);
3305 				sbuf_printf(sb, "</target>\n");
3306 			}
3307 
3308 			if (port->port_devid != NULL) {
3309 				sbuf_printf(sb, "\t<port>");
3310 				ctl_id_sbuf(port->port_devid, sb);
3311 				sbuf_printf(sb, "</port>\n");
3312 			}
3313 
3314 			if (port->port_info != NULL) {
3315 				retval = port->port_info(port->onoff_arg, sb);
3316 				if (retval != 0)
3317 					break;
3318 			}
3319 			STAILQ_FOREACH(opt, &port->options, links) {
3320 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3321 				    opt->name, opt->value, opt->name);
3322 				if (retval != 0)
3323 					break;
3324 			}
3325 
3326 			if (port->lun_map != NULL) {
3327 				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3328 				for (j = 0; j < port->lun_map_size; j++) {
3329 					plun = ctl_lun_map_from_port(port, j);
3330 					if (plun == UINT32_MAX)
3331 						continue;
3332 					sbuf_printf(sb,
3333 					    "\t<lun id=\"%u\">%u</lun>\n",
3334 					    j, plun);
3335 				}
3336 			}
3337 
3338 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3339 				if (port->wwpn_iid[j].in_use == 0 ||
3340 				    (port->wwpn_iid[j].wwpn == 0 &&
3341 				     port->wwpn_iid[j].name == NULL))
3342 					continue;
3343 
3344 				if (port->wwpn_iid[j].name != NULL)
3345 					retval = sbuf_printf(sb,
3346 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3347 					    j, port->wwpn_iid[j].name);
3348 				else
3349 					retval = sbuf_printf(sb,
3350 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3351 					    j, port->wwpn_iid[j].wwpn);
3352 				if (retval != 0)
3353 					break;
3354 			}
3355 			if (retval != 0)
3356 				break;
3357 
3358 			retval = sbuf_printf(sb, "</targ_port>\n");
3359 			if (retval != 0)
3360 				break;
3361 		}
3362 		mtx_unlock(&softc->ctl_lock);
3363 
3364 		if ((retval != 0)
3365 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3366 			retval = 0;
3367 			sbuf_delete(sb);
3368 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3369 			snprintf(list->error_str, sizeof(list->error_str),
3370 				 "Out of space, %d bytes is too small",
3371 				 list->alloc_len);
3372 			break;
3373 		}
3374 
3375 		sbuf_finish(sb);
3376 
3377 		retval = copyout(sbuf_data(sb), list->lun_xml,
3378 				 sbuf_len(sb) + 1);
3379 
3380 		list->fill_len = sbuf_len(sb) + 1;
3381 		list->status = CTL_LUN_LIST_OK;
3382 		sbuf_delete(sb);
3383 		break;
3384 	}
3385 	case CTL_LUN_MAP: {
3386 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3387 		struct ctl_port *port;
3388 
3389 		mtx_lock(&softc->ctl_lock);
3390 		if (lm->port < softc->port_min ||
3391 		    lm->port >= softc->port_max ||
3392 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3393 			mtx_unlock(&softc->ctl_lock);
3394 			return (ENXIO);
3395 		}
3396 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3397 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3398 				if (ctl_lun_map_to_port(port, lun->lun) ==
3399 				    UINT32_MAX)
3400 					continue;
3401 				mtx_lock(&lun->lun_lock);
3402 				ctl_est_ua_port(lun, lm->port, -1,
3403 				    CTL_UA_LUN_CHANGE);
3404 				mtx_unlock(&lun->lun_lock);
3405 			}
3406 		}
3407 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3408 		if (lm->plun != UINT32_MAX) {
3409 			if (lm->lun == UINT32_MAX)
3410 				retval = ctl_lun_map_unset(port, lm->plun);
3411 			else if (lm->lun < CTL_MAX_LUNS &&
3412 			    softc->ctl_luns[lm->lun] != NULL)
3413 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3414 			else
3415 				return (ENXIO);
3416 		} else {
3417 			if (lm->lun == UINT32_MAX)
3418 				retval = ctl_lun_map_deinit(port);
3419 			else
3420 				retval = ctl_lun_map_init(port);
3421 		}
3422 		if (port->status & CTL_PORT_STATUS_ONLINE)
3423 			ctl_isc_announce_port(port);
3424 		break;
3425 	}
3426 	case CTL_GET_LUN_STATS: {
3427 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3428 		int i;
3429 
3430 		/*
3431 		 * XXX KDM no locking here.  If the LUN list changes,
3432 		 * things can blow up.
3433 		 */
3434 		i = 0;
3435 		stats->status = CTL_SS_OK;
3436 		stats->fill_len = 0;
3437 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3438 			if (lun->lun < stats->first_item)
3439 				continue;
3440 			if (stats->fill_len + sizeof(lun->stats) >
3441 			    stats->alloc_len) {
3442 				stats->status = CTL_SS_NEED_MORE_SPACE;
3443 				break;
3444 			}
3445 			retval = copyout(&lun->stats, &stats->stats[i++],
3446 					 sizeof(lun->stats));
3447 			if (retval != 0)
3448 				break;
3449 			stats->fill_len += sizeof(lun->stats);
3450 		}
3451 		stats->num_items = softc->num_luns;
3452 		stats->flags = CTL_STATS_FLAG_NONE;
3453 #ifdef CTL_TIME_IO
3454 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3455 #endif
3456 		getnanouptime(&stats->timestamp);
3457 		break;
3458 	}
3459 	case CTL_GET_PORT_STATS: {
3460 		struct ctl_get_io_stats *stats = (struct ctl_get_io_stats *)addr;
3461 		int i;
3462 
3463 		/*
3464 		 * XXX KDM no locking here.  If the LUN list changes,
3465 		 * things can blow up.
3466 		 */
3467 		i = 0;
3468 		stats->status = CTL_SS_OK;
3469 		stats->fill_len = 0;
3470 		STAILQ_FOREACH(port, &softc->port_list, links) {
3471 			if (port->targ_port < stats->first_item)
3472 				continue;
3473 			if (stats->fill_len + sizeof(port->stats) >
3474 			    stats->alloc_len) {
3475 				stats->status = CTL_SS_NEED_MORE_SPACE;
3476 				break;
3477 			}
3478 			retval = copyout(&port->stats, &stats->stats[i++],
3479 					 sizeof(port->stats));
3480 			if (retval != 0)
3481 				break;
3482 			stats->fill_len += sizeof(port->stats);
3483 		}
3484 		stats->num_items = softc->num_ports;
3485 		stats->flags = CTL_STATS_FLAG_NONE;
3486 #ifdef CTL_TIME_IO
3487 		stats->flags |= CTL_STATS_FLAG_TIME_VALID;
3488 #endif
3489 		getnanouptime(&stats->timestamp);
3490 		break;
3491 	}
3492 	default: {
3493 		/* XXX KDM should we fix this? */
3494 #if 0
3495 		struct ctl_backend_driver *backend;
3496 		unsigned int type;
3497 		int found;
3498 
3499 		found = 0;
3500 
3501 		/*
3502 		 * We encode the backend type as the ioctl type for backend
3503 		 * ioctls.  So parse it out here, and then search for a
3504 		 * backend of this type.
3505 		 */
3506 		type = _IOC_TYPE(cmd);
3507 
3508 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3509 			if (backend->type == type) {
3510 				found = 1;
3511 				break;
3512 			}
3513 		}
3514 		if (found == 0) {
3515 			printf("ctl: unknown ioctl command %#lx or backend "
3516 			       "%d\n", cmd, type);
3517 			retval = EINVAL;
3518 			break;
3519 		}
3520 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3521 #endif
3522 		retval = ENOTTY;
3523 		break;
3524 	}
3525 	}
3526 	return (retval);
3527 }
3528 
3529 uint32_t
3530 ctl_get_initindex(struct ctl_nexus *nexus)
3531 {
3532 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3533 }
3534 
3535 int
3536 ctl_lun_map_init(struct ctl_port *port)
3537 {
3538 	struct ctl_softc *softc = port->ctl_softc;
3539 	struct ctl_lun *lun;
3540 	int size = ctl_lun_map_size;
3541 	uint32_t i;
3542 
3543 	if (port->lun_map == NULL || port->lun_map_size < size) {
3544 		port->lun_map_size = 0;
3545 		free(port->lun_map, M_CTL);
3546 		port->lun_map = malloc(size * sizeof(uint32_t),
3547 		    M_CTL, M_NOWAIT);
3548 	}
3549 	if (port->lun_map == NULL)
3550 		return (ENOMEM);
3551 	for (i = 0; i < size; i++)
3552 		port->lun_map[i] = UINT32_MAX;
3553 	port->lun_map_size = size;
3554 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3555 		if (port->lun_disable != NULL) {
3556 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3557 				port->lun_disable(port->targ_lun_arg, lun->lun);
3558 		}
3559 		ctl_isc_announce_port(port);
3560 	}
3561 	return (0);
3562 }
3563 
3564 int
3565 ctl_lun_map_deinit(struct ctl_port *port)
3566 {
3567 	struct ctl_softc *softc = port->ctl_softc;
3568 	struct ctl_lun *lun;
3569 
3570 	if (port->lun_map == NULL)
3571 		return (0);
3572 	port->lun_map_size = 0;
3573 	free(port->lun_map, M_CTL);
3574 	port->lun_map = NULL;
3575 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3576 		if (port->lun_enable != NULL) {
3577 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3578 				port->lun_enable(port->targ_lun_arg, lun->lun);
3579 		}
3580 		ctl_isc_announce_port(port);
3581 	}
3582 	return (0);
3583 }
3584 
3585 int
3586 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3587 {
3588 	int status;
3589 	uint32_t old;
3590 
3591 	if (port->lun_map == NULL) {
3592 		status = ctl_lun_map_init(port);
3593 		if (status != 0)
3594 			return (status);
3595 	}
3596 	if (plun >= port->lun_map_size)
3597 		return (EINVAL);
3598 	old = port->lun_map[plun];
3599 	port->lun_map[plun] = glun;
3600 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old == UINT32_MAX) {
3601 		if (port->lun_enable != NULL)
3602 			port->lun_enable(port->targ_lun_arg, plun);
3603 		ctl_isc_announce_port(port);
3604 	}
3605 	return (0);
3606 }
3607 
3608 int
3609 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3610 {
3611 	uint32_t old;
3612 
3613 	if (port->lun_map == NULL || plun >= port->lun_map_size)
3614 		return (0);
3615 	old = port->lun_map[plun];
3616 	port->lun_map[plun] = UINT32_MAX;
3617 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old != UINT32_MAX) {
3618 		if (port->lun_disable != NULL)
3619 			port->lun_disable(port->targ_lun_arg, plun);
3620 		ctl_isc_announce_port(port);
3621 	}
3622 	return (0);
3623 }
3624 
3625 uint32_t
3626 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3627 {
3628 
3629 	if (port == NULL)
3630 		return (UINT32_MAX);
3631 	if (port->lun_map == NULL)
3632 		return (lun_id);
3633 	if (lun_id > port->lun_map_size)
3634 		return (UINT32_MAX);
3635 	return (port->lun_map[lun_id]);
3636 }
3637 
3638 uint32_t
3639 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3640 {
3641 	uint32_t i;
3642 
3643 	if (port == NULL)
3644 		return (UINT32_MAX);
3645 	if (port->lun_map == NULL)
3646 		return (lun_id);
3647 	for (i = 0; i < port->lun_map_size; i++) {
3648 		if (port->lun_map[i] == lun_id)
3649 			return (i);
3650 	}
3651 	return (UINT32_MAX);
3652 }
3653 
3654 uint32_t
3655 ctl_decode_lun(uint64_t encoded)
3656 {
3657 	uint8_t lun[8];
3658 	uint32_t result = 0xffffffff;
3659 
3660 	be64enc(lun, encoded);
3661 	switch (lun[0] & RPL_LUNDATA_ATYP_MASK) {
3662 	case RPL_LUNDATA_ATYP_PERIPH:
3663 		if ((lun[0] & 0x3f) == 0 && lun[2] == 0 && lun[3] == 0 &&
3664 		    lun[4] == 0 && lun[5] == 0 && lun[6] == 0 && lun[7] == 0)
3665 			result = lun[1];
3666 		break;
3667 	case RPL_LUNDATA_ATYP_FLAT:
3668 		if (lun[2] == 0 && lun[3] == 0 && lun[4] == 0 && lun[5] == 0 &&
3669 		    lun[6] == 0 && lun[7] == 0)
3670 			result = ((lun[0] & 0x3f) << 8) + lun[1];
3671 		break;
3672 	case RPL_LUNDATA_ATYP_EXTLUN:
3673 		switch (lun[0] & RPL_LUNDATA_EXT_EAM_MASK) {
3674 		case 0x02:
3675 			switch (lun[0] & RPL_LUNDATA_EXT_LEN_MASK) {
3676 			case 0x00:
3677 				result = lun[1];
3678 				break;
3679 			case 0x10:
3680 				result = (lun[1] << 16) + (lun[2] << 8) +
3681 				    lun[3];
3682 				break;
3683 			case 0x20:
3684 				if (lun[1] == 0 && lun[6] == 0 && lun[7] == 0)
3685 					result = (lun[2] << 24) +
3686 					    (lun[3] << 16) + (lun[4] << 8) +
3687 					    lun[5];
3688 				break;
3689 			}
3690 			break;
3691 		case RPL_LUNDATA_EXT_EAM_NOT_SPEC:
3692 			result = 0xffffffff;
3693 			break;
3694 		}
3695 		break;
3696 	}
3697 	return (result);
3698 }
3699 
3700 uint64_t
3701 ctl_encode_lun(uint32_t decoded)
3702 {
3703 	uint64_t l = decoded;
3704 
3705 	if (l <= 0xff)
3706 		return (((uint64_t)RPL_LUNDATA_ATYP_PERIPH << 56) | (l << 48));
3707 	if (l <= 0x3fff)
3708 		return (((uint64_t)RPL_LUNDATA_ATYP_FLAT << 56) | (l << 48));
3709 	if (l <= 0xffffff)
3710 		return (((uint64_t)(RPL_LUNDATA_ATYP_EXTLUN | 0x12) << 56) |
3711 		    (l << 32));
3712 	return ((((uint64_t)RPL_LUNDATA_ATYP_EXTLUN | 0x22) << 56) | (l << 16));
3713 }
3714 
3715 int
3716 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3717 {
3718 	int i;
3719 
3720 	for (i = first; i < last; i++) {
3721 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3722 			return (i);
3723 	}
3724 	return (-1);
3725 }
3726 
3727 int
3728 ctl_set_mask(uint32_t *mask, uint32_t bit)
3729 {
3730 	uint32_t chunk, piece;
3731 
3732 	chunk = bit >> 5;
3733 	piece = bit % (sizeof(uint32_t) * 8);
3734 
3735 	if ((mask[chunk] & (1 << piece)) != 0)
3736 		return (-1);
3737 	else
3738 		mask[chunk] |= (1 << piece);
3739 
3740 	return (0);
3741 }
3742 
3743 int
3744 ctl_clear_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_is_set(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 (0);
3769 	else
3770 		return (1);
3771 }
3772 
3773 static uint64_t
3774 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3775 {
3776 	uint64_t *t;
3777 
3778 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3779 	if (t == NULL)
3780 		return (0);
3781 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3782 }
3783 
3784 static void
3785 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3786 {
3787 	uint64_t *t;
3788 
3789 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3790 	if (t == NULL)
3791 		return;
3792 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3793 }
3794 
3795 static void
3796 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3797 {
3798 	uint64_t *p;
3799 	u_int i;
3800 
3801 	i = residx/CTL_MAX_INIT_PER_PORT;
3802 	if (lun->pr_keys[i] != NULL)
3803 		return;
3804 	mtx_unlock(&lun->lun_lock);
3805 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3806 	    M_WAITOK | M_ZERO);
3807 	mtx_lock(&lun->lun_lock);
3808 	if (lun->pr_keys[i] == NULL)
3809 		lun->pr_keys[i] = p;
3810 	else
3811 		free(p, M_CTL);
3812 }
3813 
3814 static void
3815 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3816 {
3817 	uint64_t *t;
3818 
3819 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3820 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3821 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3822 }
3823 
3824 /*
3825  * ctl_softc, pool_name, total_ctl_io are passed in.
3826  * npool is passed out.
3827  */
3828 int
3829 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3830 		uint32_t total_ctl_io, void **npool)
3831 {
3832 	struct ctl_io_pool *pool;
3833 
3834 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3835 					    M_NOWAIT | M_ZERO);
3836 	if (pool == NULL)
3837 		return (ENOMEM);
3838 
3839 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3840 	pool->ctl_softc = ctl_softc;
3841 #ifdef IO_POOLS
3842 	pool->zone = uma_zsecond_create(pool->name, NULL,
3843 	    NULL, NULL, NULL, ctl_softc->io_zone);
3844 	/* uma_prealloc(pool->zone, total_ctl_io); */
3845 #else
3846 	pool->zone = ctl_softc->io_zone;
3847 #endif
3848 
3849 	*npool = pool;
3850 	return (0);
3851 }
3852 
3853 void
3854 ctl_pool_free(struct ctl_io_pool *pool)
3855 {
3856 
3857 	if (pool == NULL)
3858 		return;
3859 
3860 #ifdef IO_POOLS
3861 	uma_zdestroy(pool->zone);
3862 #endif
3863 	free(pool, M_CTL);
3864 }
3865 
3866 union ctl_io *
3867 ctl_alloc_io(void *pool_ref)
3868 {
3869 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3870 	union ctl_io *io;
3871 
3872 	io = uma_zalloc(pool->zone, M_WAITOK);
3873 	if (io != NULL) {
3874 		io->io_hdr.pool = pool_ref;
3875 		CTL_SOFTC(io) = pool->ctl_softc;
3876 	}
3877 	return (io);
3878 }
3879 
3880 union ctl_io *
3881 ctl_alloc_io_nowait(void *pool_ref)
3882 {
3883 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3884 	union ctl_io *io;
3885 
3886 	io = uma_zalloc(pool->zone, M_NOWAIT);
3887 	if (io != NULL) {
3888 		io->io_hdr.pool = pool_ref;
3889 		CTL_SOFTC(io) = pool->ctl_softc;
3890 	}
3891 	return (io);
3892 }
3893 
3894 void
3895 ctl_free_io(union ctl_io *io)
3896 {
3897 	struct ctl_io_pool *pool;
3898 
3899 	if (io == NULL)
3900 		return;
3901 
3902 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3903 	uma_zfree(pool->zone, io);
3904 }
3905 
3906 void
3907 ctl_zero_io(union ctl_io *io)
3908 {
3909 	struct ctl_io_pool *pool;
3910 
3911 	if (io == NULL)
3912 		return;
3913 
3914 	/*
3915 	 * May need to preserve linked list pointers at some point too.
3916 	 */
3917 	pool = io->io_hdr.pool;
3918 	memset(io, 0, sizeof(*io));
3919 	io->io_hdr.pool = pool;
3920 	CTL_SOFTC(io) = pool->ctl_softc;
3921 }
3922 
3923 int
3924 ctl_expand_number(const char *buf, uint64_t *num)
3925 {
3926 	char *endptr;
3927 	uint64_t number;
3928 	unsigned shift;
3929 
3930 	number = strtoq(buf, &endptr, 0);
3931 
3932 	switch (tolower((unsigned char)*endptr)) {
3933 	case 'e':
3934 		shift = 60;
3935 		break;
3936 	case 'p':
3937 		shift = 50;
3938 		break;
3939 	case 't':
3940 		shift = 40;
3941 		break;
3942 	case 'g':
3943 		shift = 30;
3944 		break;
3945 	case 'm':
3946 		shift = 20;
3947 		break;
3948 	case 'k':
3949 		shift = 10;
3950 		break;
3951 	case 'b':
3952 	case '\0': /* No unit. */
3953 		*num = number;
3954 		return (0);
3955 	default:
3956 		/* Unrecognized unit. */
3957 		return (-1);
3958 	}
3959 
3960 	if ((number << shift) >> shift != number) {
3961 		/* Overflow */
3962 		return (-1);
3963 	}
3964 	*num = number << shift;
3965 	return (0);
3966 }
3967 
3968 
3969 /*
3970  * This routine could be used in the future to load default and/or saved
3971  * mode page parameters for a particuar lun.
3972  */
3973 static int
3974 ctl_init_page_index(struct ctl_lun *lun)
3975 {
3976 	int i, page_code;
3977 	struct ctl_page_index *page_index;
3978 	const char *value;
3979 	uint64_t ival;
3980 
3981 	memcpy(&lun->mode_pages.index, page_index_template,
3982 	       sizeof(page_index_template));
3983 
3984 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3985 
3986 		page_index = &lun->mode_pages.index[i];
3987 		if (lun->be_lun->lun_type == T_DIRECT &&
3988 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3989 			continue;
3990 		if (lun->be_lun->lun_type == T_PROCESSOR &&
3991 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3992 			continue;
3993 		if (lun->be_lun->lun_type == T_CDROM &&
3994 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3995 			continue;
3996 
3997 		page_code = page_index->page_code & SMPH_PC_MASK;
3998 		switch (page_code) {
3999 		case SMS_RW_ERROR_RECOVERY_PAGE: {
4000 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4001 			    ("subpage %#x for page %#x is incorrect!",
4002 			    page_index->subpage, page_code));
4003 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
4004 			       &rw_er_page_default,
4005 			       sizeof(rw_er_page_default));
4006 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
4007 			       &rw_er_page_changeable,
4008 			       sizeof(rw_er_page_changeable));
4009 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
4010 			       &rw_er_page_default,
4011 			       sizeof(rw_er_page_default));
4012 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
4013 			       &rw_er_page_default,
4014 			       sizeof(rw_er_page_default));
4015 			page_index->page_data =
4016 				(uint8_t *)lun->mode_pages.rw_er_page;
4017 			break;
4018 		}
4019 		case SMS_FORMAT_DEVICE_PAGE: {
4020 			struct scsi_format_page *format_page;
4021 
4022 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4023 			    ("subpage %#x for page %#x is incorrect!",
4024 			    page_index->subpage, page_code));
4025 
4026 			/*
4027 			 * Sectors per track are set above.  Bytes per
4028 			 * sector need to be set here on a per-LUN basis.
4029 			 */
4030 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4031 			       &format_page_default,
4032 			       sizeof(format_page_default));
4033 			memcpy(&lun->mode_pages.format_page[
4034 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4035 			       sizeof(format_page_changeable));
4036 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4037 			       &format_page_default,
4038 			       sizeof(format_page_default));
4039 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4040 			       &format_page_default,
4041 			       sizeof(format_page_default));
4042 
4043 			format_page = &lun->mode_pages.format_page[
4044 				CTL_PAGE_CURRENT];
4045 			scsi_ulto2b(lun->be_lun->blocksize,
4046 				    format_page->bytes_per_sector);
4047 
4048 			format_page = &lun->mode_pages.format_page[
4049 				CTL_PAGE_DEFAULT];
4050 			scsi_ulto2b(lun->be_lun->blocksize,
4051 				    format_page->bytes_per_sector);
4052 
4053 			format_page = &lun->mode_pages.format_page[
4054 				CTL_PAGE_SAVED];
4055 			scsi_ulto2b(lun->be_lun->blocksize,
4056 				    format_page->bytes_per_sector);
4057 
4058 			page_index->page_data =
4059 				(uint8_t *)lun->mode_pages.format_page;
4060 			break;
4061 		}
4062 		case SMS_RIGID_DISK_PAGE: {
4063 			struct scsi_rigid_disk_page *rigid_disk_page;
4064 			uint32_t sectors_per_cylinder;
4065 			uint64_t cylinders;
4066 #ifndef	__XSCALE__
4067 			int shift;
4068 #endif /* !__XSCALE__ */
4069 
4070 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4071 			    ("subpage %#x for page %#x is incorrect!",
4072 			    page_index->subpage, page_code));
4073 
4074 			/*
4075 			 * Rotation rate and sectors per track are set
4076 			 * above.  We calculate the cylinders here based on
4077 			 * capacity.  Due to the number of heads and
4078 			 * sectors per track we're using, smaller arrays
4079 			 * may turn out to have 0 cylinders.  Linux and
4080 			 * FreeBSD don't pay attention to these mode pages
4081 			 * to figure out capacity, but Solaris does.  It
4082 			 * seems to deal with 0 cylinders just fine, and
4083 			 * works out a fake geometry based on the capacity.
4084 			 */
4085 			memcpy(&lun->mode_pages.rigid_disk_page[
4086 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4087 			       sizeof(rigid_disk_page_default));
4088 			memcpy(&lun->mode_pages.rigid_disk_page[
4089 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4090 			       sizeof(rigid_disk_page_changeable));
4091 
4092 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4093 				CTL_DEFAULT_HEADS;
4094 
4095 			/*
4096 			 * The divide method here will be more accurate,
4097 			 * probably, but results in floating point being
4098 			 * used in the kernel on i386 (__udivdi3()).  On the
4099 			 * XScale, though, __udivdi3() is implemented in
4100 			 * software.
4101 			 *
4102 			 * The shift method for cylinder calculation is
4103 			 * accurate if sectors_per_cylinder is a power of
4104 			 * 2.  Otherwise it might be slightly off -- you
4105 			 * might have a bit of a truncation problem.
4106 			 */
4107 #ifdef	__XSCALE__
4108 			cylinders = (lun->be_lun->maxlba + 1) /
4109 				sectors_per_cylinder;
4110 #else
4111 			for (shift = 31; shift > 0; shift--) {
4112 				if (sectors_per_cylinder & (1 << shift))
4113 					break;
4114 			}
4115 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4116 #endif
4117 
4118 			/*
4119 			 * We've basically got 3 bytes, or 24 bits for the
4120 			 * cylinder size in the mode page.  If we're over,
4121 			 * just round down to 2^24.
4122 			 */
4123 			if (cylinders > 0xffffff)
4124 				cylinders = 0xffffff;
4125 
4126 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4127 				CTL_PAGE_DEFAULT];
4128 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4129 
4130 			if ((value = ctl_get_opt(&lun->be_lun->options,
4131 			    "rpm")) != NULL) {
4132 				scsi_ulto2b(strtol(value, NULL, 0),
4133 				     rigid_disk_page->rotation_rate);
4134 			}
4135 
4136 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
4137 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4138 			       sizeof(rigid_disk_page_default));
4139 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
4140 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
4141 			       sizeof(rigid_disk_page_default));
4142 
4143 			page_index->page_data =
4144 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4145 			break;
4146 		}
4147 		case SMS_VERIFY_ERROR_RECOVERY_PAGE: {
4148 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4149 			    ("subpage %#x for page %#x is incorrect!",
4150 			    page_index->subpage, page_code));
4151 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CURRENT],
4152 			       &verify_er_page_default,
4153 			       sizeof(verify_er_page_default));
4154 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_CHANGEABLE],
4155 			       &verify_er_page_changeable,
4156 			       sizeof(verify_er_page_changeable));
4157 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_DEFAULT],
4158 			       &verify_er_page_default,
4159 			       sizeof(verify_er_page_default));
4160 			memcpy(&lun->mode_pages.verify_er_page[CTL_PAGE_SAVED],
4161 			       &verify_er_page_default,
4162 			       sizeof(verify_er_page_default));
4163 			page_index->page_data =
4164 				(uint8_t *)lun->mode_pages.verify_er_page;
4165 			break;
4166 		}
4167 		case SMS_CACHING_PAGE: {
4168 			struct scsi_caching_page *caching_page;
4169 
4170 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4171 			    ("subpage %#x for page %#x is incorrect!",
4172 			    page_index->subpage, page_code));
4173 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4174 			       &caching_page_default,
4175 			       sizeof(caching_page_default));
4176 			memcpy(&lun->mode_pages.caching_page[
4177 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4178 			       sizeof(caching_page_changeable));
4179 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4180 			       &caching_page_default,
4181 			       sizeof(caching_page_default));
4182 			caching_page = &lun->mode_pages.caching_page[
4183 			    CTL_PAGE_SAVED];
4184 			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4185 			if (value != NULL && strcmp(value, "off") == 0)
4186 				caching_page->flags1 &= ~SCP_WCE;
4187 			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4188 			if (value != NULL && strcmp(value, "off") == 0)
4189 				caching_page->flags1 |= SCP_RCD;
4190 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4191 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4192 			       sizeof(caching_page_default));
4193 			page_index->page_data =
4194 				(uint8_t *)lun->mode_pages.caching_page;
4195 			break;
4196 		}
4197 		case SMS_CONTROL_MODE_PAGE: {
4198 			switch (page_index->subpage) {
4199 			case SMS_SUBPAGE_PAGE_0: {
4200 				struct scsi_control_page *control_page;
4201 
4202 				memcpy(&lun->mode_pages.control_page[
4203 				    CTL_PAGE_DEFAULT],
4204 				       &control_page_default,
4205 				       sizeof(control_page_default));
4206 				memcpy(&lun->mode_pages.control_page[
4207 				    CTL_PAGE_CHANGEABLE],
4208 				       &control_page_changeable,
4209 				       sizeof(control_page_changeable));
4210 				memcpy(&lun->mode_pages.control_page[
4211 				    CTL_PAGE_SAVED],
4212 				       &control_page_default,
4213 				       sizeof(control_page_default));
4214 				control_page = &lun->mode_pages.control_page[
4215 				    CTL_PAGE_SAVED];
4216 				value = ctl_get_opt(&lun->be_lun->options,
4217 				    "reordering");
4218 				if (value != NULL &&
4219 				    strcmp(value, "unrestricted") == 0) {
4220 					control_page->queue_flags &=
4221 					    ~SCP_QUEUE_ALG_MASK;
4222 					control_page->queue_flags |=
4223 					    SCP_QUEUE_ALG_UNRESTRICTED;
4224 				}
4225 				memcpy(&lun->mode_pages.control_page[
4226 				    CTL_PAGE_CURRENT],
4227 				       &lun->mode_pages.control_page[
4228 				    CTL_PAGE_SAVED],
4229 				       sizeof(control_page_default));
4230 				page_index->page_data =
4231 				    (uint8_t *)lun->mode_pages.control_page;
4232 				break;
4233 			}
4234 			case 0x01:
4235 				memcpy(&lun->mode_pages.control_ext_page[
4236 				    CTL_PAGE_DEFAULT],
4237 				       &control_ext_page_default,
4238 				       sizeof(control_ext_page_default));
4239 				memcpy(&lun->mode_pages.control_ext_page[
4240 				    CTL_PAGE_CHANGEABLE],
4241 				       &control_ext_page_changeable,
4242 				       sizeof(control_ext_page_changeable));
4243 				memcpy(&lun->mode_pages.control_ext_page[
4244 				    CTL_PAGE_SAVED],
4245 				       &control_ext_page_default,
4246 				       sizeof(control_ext_page_default));
4247 				memcpy(&lun->mode_pages.control_ext_page[
4248 				    CTL_PAGE_CURRENT],
4249 				       &lun->mode_pages.control_ext_page[
4250 				    CTL_PAGE_SAVED],
4251 				       sizeof(control_ext_page_default));
4252 				page_index->page_data =
4253 				    (uint8_t *)lun->mode_pages.control_ext_page;
4254 				break;
4255 			default:
4256 				panic("subpage %#x for page %#x is incorrect!",
4257 				      page_index->subpage, page_code);
4258 			}
4259 			break;
4260 		}
4261 		case SMS_INFO_EXCEPTIONS_PAGE: {
4262 			switch (page_index->subpage) {
4263 			case SMS_SUBPAGE_PAGE_0:
4264 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4265 				       &ie_page_default,
4266 				       sizeof(ie_page_default));
4267 				memcpy(&lun->mode_pages.ie_page[
4268 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4269 				       sizeof(ie_page_changeable));
4270 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4271 				       &ie_page_default,
4272 				       sizeof(ie_page_default));
4273 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4274 				       &ie_page_default,
4275 				       sizeof(ie_page_default));
4276 				page_index->page_data =
4277 					(uint8_t *)lun->mode_pages.ie_page;
4278 				break;
4279 			case 0x02: {
4280 				struct ctl_logical_block_provisioning_page *page;
4281 
4282 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4283 				       &lbp_page_default,
4284 				       sizeof(lbp_page_default));
4285 				memcpy(&lun->mode_pages.lbp_page[
4286 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4287 				       sizeof(lbp_page_changeable));
4288 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4289 				       &lbp_page_default,
4290 				       sizeof(lbp_page_default));
4291 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4292 				value = ctl_get_opt(&lun->be_lun->options,
4293 				    "avail-threshold");
4294 				if (value != NULL &&
4295 				    ctl_expand_number(value, &ival) == 0) {
4296 					page->descr[0].flags |= SLBPPD_ENABLED |
4297 					    SLBPPD_ARMING_DEC;
4298 					if (lun->be_lun->blocksize)
4299 						ival /= lun->be_lun->blocksize;
4300 					else
4301 						ival /= 512;
4302 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4303 					    page->descr[0].count);
4304 				}
4305 				value = ctl_get_opt(&lun->be_lun->options,
4306 				    "used-threshold");
4307 				if (value != NULL &&
4308 				    ctl_expand_number(value, &ival) == 0) {
4309 					page->descr[1].flags |= SLBPPD_ENABLED |
4310 					    SLBPPD_ARMING_INC;
4311 					if (lun->be_lun->blocksize)
4312 						ival /= lun->be_lun->blocksize;
4313 					else
4314 						ival /= 512;
4315 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4316 					    page->descr[1].count);
4317 				}
4318 				value = ctl_get_opt(&lun->be_lun->options,
4319 				    "pool-avail-threshold");
4320 				if (value != NULL &&
4321 				    ctl_expand_number(value, &ival) == 0) {
4322 					page->descr[2].flags |= SLBPPD_ENABLED |
4323 					    SLBPPD_ARMING_DEC;
4324 					if (lun->be_lun->blocksize)
4325 						ival /= lun->be_lun->blocksize;
4326 					else
4327 						ival /= 512;
4328 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4329 					    page->descr[2].count);
4330 				}
4331 				value = ctl_get_opt(&lun->be_lun->options,
4332 				    "pool-used-threshold");
4333 				if (value != NULL &&
4334 				    ctl_expand_number(value, &ival) == 0) {
4335 					page->descr[3].flags |= SLBPPD_ENABLED |
4336 					    SLBPPD_ARMING_INC;
4337 					if (lun->be_lun->blocksize)
4338 						ival /= lun->be_lun->blocksize;
4339 					else
4340 						ival /= 512;
4341 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4342 					    page->descr[3].count);
4343 				}
4344 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4345 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4346 				       sizeof(lbp_page_default));
4347 				page_index->page_data =
4348 					(uint8_t *)lun->mode_pages.lbp_page;
4349 				break;
4350 			}
4351 			default:
4352 				panic("subpage %#x for page %#x is incorrect!",
4353 				      page_index->subpage, page_code);
4354 			}
4355 			break;
4356 		}
4357 		case SMS_CDDVD_CAPS_PAGE:{
4358 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4359 			    ("subpage %#x for page %#x is incorrect!",
4360 			    page_index->subpage, page_code));
4361 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4362 			       &cddvd_page_default,
4363 			       sizeof(cddvd_page_default));
4364 			memcpy(&lun->mode_pages.cddvd_page[
4365 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4366 			       sizeof(cddvd_page_changeable));
4367 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4368 			       &cddvd_page_default,
4369 			       sizeof(cddvd_page_default));
4370 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4371 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4372 			       sizeof(cddvd_page_default));
4373 			page_index->page_data =
4374 				(uint8_t *)lun->mode_pages.cddvd_page;
4375 			break;
4376 		}
4377 		default:
4378 			panic("invalid page code value %#x", page_code);
4379 		}
4380 	}
4381 
4382 	return (CTL_RETVAL_COMPLETE);
4383 }
4384 
4385 static int
4386 ctl_init_log_page_index(struct ctl_lun *lun)
4387 {
4388 	struct ctl_page_index *page_index;
4389 	int i, j, k, prev;
4390 
4391 	memcpy(&lun->log_pages.index, log_page_index_template,
4392 	       sizeof(log_page_index_template));
4393 
4394 	prev = -1;
4395 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4396 
4397 		page_index = &lun->log_pages.index[i];
4398 		if (lun->be_lun->lun_type == T_DIRECT &&
4399 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4400 			continue;
4401 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4402 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4403 			continue;
4404 		if (lun->be_lun->lun_type == T_CDROM &&
4405 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4406 			continue;
4407 
4408 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4409 		    lun->backend->lun_attr == NULL)
4410 			continue;
4411 
4412 		if (page_index->page_code != prev) {
4413 			lun->log_pages.pages_page[j] = page_index->page_code;
4414 			prev = page_index->page_code;
4415 			j++;
4416 		}
4417 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4418 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4419 		k++;
4420 	}
4421 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4422 	lun->log_pages.index[0].page_len = j;
4423 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4424 	lun->log_pages.index[1].page_len = k * 2;
4425 	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4426 	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4427 	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4428 	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4429 	lun->log_pages.index[4].page_data = (uint8_t *)&lun->log_pages.ie_page;
4430 	lun->log_pages.index[4].page_len = sizeof(lun->log_pages.ie_page);
4431 
4432 	return (CTL_RETVAL_COMPLETE);
4433 }
4434 
4435 static int
4436 hex2bin(const char *str, uint8_t *buf, int buf_size)
4437 {
4438 	int i;
4439 	u_char c;
4440 
4441 	memset(buf, 0, buf_size);
4442 	while (isspace(str[0]))
4443 		str++;
4444 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4445 		str += 2;
4446 	buf_size *= 2;
4447 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4448 		while (str[i] == '-')	/* Skip dashes in UUIDs. */
4449 			str++;
4450 		c = str[i];
4451 		if (isdigit(c))
4452 			c -= '0';
4453 		else if (isalpha(c))
4454 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4455 		else
4456 			break;
4457 		if (c >= 16)
4458 			break;
4459 		if ((i & 1) == 0)
4460 			buf[i / 2] |= (c << 4);
4461 		else
4462 			buf[i / 2] |= c;
4463 	}
4464 	return ((i + 1) / 2);
4465 }
4466 
4467 /*
4468  * LUN allocation.
4469  *
4470  * Requirements:
4471  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4472  *   wants us to allocate the LUN and he can block.
4473  * - ctl_softc is always set
4474  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4475  *
4476  * Returns 0 for success, non-zero (errno) for failure.
4477  */
4478 static int
4479 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4480 	      struct ctl_be_lun *const be_lun)
4481 {
4482 	struct ctl_lun *nlun, *lun;
4483 	struct scsi_vpd_id_descriptor *desc;
4484 	struct scsi_vpd_id_t10 *t10id;
4485 	const char *eui, *naa, *scsiname, *uuid, *vendor, *value;
4486 	int lun_number, lun_malloced;
4487 	int devidlen, idlen1, idlen2 = 0, len;
4488 
4489 	if (be_lun == NULL)
4490 		return (EINVAL);
4491 
4492 	/*
4493 	 * We currently only support Direct Access or Processor LUN types.
4494 	 */
4495 	switch (be_lun->lun_type) {
4496 	case T_DIRECT:
4497 	case T_PROCESSOR:
4498 	case T_CDROM:
4499 		break;
4500 	case T_SEQUENTIAL:
4501 	case T_CHANGER:
4502 	default:
4503 		be_lun->lun_config_status(be_lun->be_lun,
4504 					  CTL_LUN_CONFIG_FAILURE);
4505 		break;
4506 	}
4507 	if (ctl_lun == NULL) {
4508 		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4509 		lun_malloced = 1;
4510 	} else {
4511 		lun_malloced = 0;
4512 		lun = ctl_lun;
4513 	}
4514 
4515 	memset(lun, 0, sizeof(*lun));
4516 	if (lun_malloced)
4517 		lun->flags = CTL_LUN_MALLOCED;
4518 
4519 	/* Generate LUN ID. */
4520 	devidlen = max(CTL_DEVID_MIN_LEN,
4521 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4522 	idlen1 = sizeof(*t10id) + devidlen;
4523 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4524 	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4525 	if (scsiname != NULL) {
4526 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4527 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4528 	}
4529 	eui = ctl_get_opt(&be_lun->options, "eui");
4530 	if (eui != NULL) {
4531 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4532 	}
4533 	naa = ctl_get_opt(&be_lun->options, "naa");
4534 	if (naa != NULL) {
4535 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4536 	}
4537 	uuid = ctl_get_opt(&be_lun->options, "uuid");
4538 	if (uuid != NULL) {
4539 		len += sizeof(struct scsi_vpd_id_descriptor) + 18;
4540 	}
4541 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4542 	    M_CTL, M_WAITOK | M_ZERO);
4543 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4544 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4545 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4546 	desc->length = idlen1;
4547 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4548 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4549 	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4550 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4551 	} else {
4552 		strncpy(t10id->vendor, vendor,
4553 		    min(sizeof(t10id->vendor), strlen(vendor)));
4554 	}
4555 	strncpy((char *)t10id->vendor_spec_id,
4556 	    (char *)be_lun->device_id, devidlen);
4557 	if (scsiname != NULL) {
4558 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4559 		    desc->length);
4560 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4561 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4562 		    SVPD_ID_TYPE_SCSI_NAME;
4563 		desc->length = idlen2;
4564 		strlcpy(desc->identifier, scsiname, idlen2);
4565 	}
4566 	if (eui != NULL) {
4567 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4568 		    desc->length);
4569 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4570 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4571 		    SVPD_ID_TYPE_EUI64;
4572 		desc->length = hex2bin(eui, desc->identifier, 16);
4573 		desc->length = desc->length > 12 ? 16 :
4574 		    (desc->length > 8 ? 12 : 8);
4575 		len -= 16 - desc->length;
4576 	}
4577 	if (naa != NULL) {
4578 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4579 		    desc->length);
4580 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4581 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4582 		    SVPD_ID_TYPE_NAA;
4583 		desc->length = hex2bin(naa, desc->identifier, 16);
4584 		desc->length = desc->length > 8 ? 16 : 8;
4585 		len -= 16 - desc->length;
4586 	}
4587 	if (uuid != NULL) {
4588 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4589 		    desc->length);
4590 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4591 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4592 		    SVPD_ID_TYPE_UUID;
4593 		desc->identifier[0] = 0x10;
4594 		hex2bin(uuid, &desc->identifier[2], 16);
4595 		desc->length = 18;
4596 	}
4597 	lun->lun_devid->len = len;
4598 
4599 	mtx_lock(&ctl_softc->ctl_lock);
4600 	/*
4601 	 * See if the caller requested a particular LUN number.  If so, see
4602 	 * if it is available.  Otherwise, allocate the first available LUN.
4603 	 */
4604 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4605 		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4606 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4607 			mtx_unlock(&ctl_softc->ctl_lock);
4608 			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4609 				printf("ctl: requested LUN ID %d is higher "
4610 				       "than CTL_MAX_LUNS - 1 (%d)\n",
4611 				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4612 			} else {
4613 				/*
4614 				 * XXX KDM return an error, or just assign
4615 				 * another LUN ID in this case??
4616 				 */
4617 				printf("ctl: requested LUN ID %d is already "
4618 				       "in use\n", be_lun->req_lun_id);
4619 			}
4620 fail:
4621 			free(lun->lun_devid, M_CTL);
4622 			if (lun->flags & CTL_LUN_MALLOCED)
4623 				free(lun, M_CTL);
4624 			be_lun->lun_config_status(be_lun->be_lun,
4625 						  CTL_LUN_CONFIG_FAILURE);
4626 			return (ENOSPC);
4627 		}
4628 		lun_number = be_lun->req_lun_id;
4629 	} else {
4630 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4631 		if (lun_number == -1) {
4632 			mtx_unlock(&ctl_softc->ctl_lock);
4633 			printf("ctl: can't allocate LUN, out of LUNs\n");
4634 			goto fail;
4635 		}
4636 	}
4637 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4638 	mtx_unlock(&ctl_softc->ctl_lock);
4639 
4640 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4641 	lun->lun = lun_number;
4642 	lun->be_lun = be_lun;
4643 	/*
4644 	 * The processor LUN is always enabled.  Disk LUNs come on line
4645 	 * disabled, and must be enabled by the backend.
4646 	 */
4647 	lun->flags |= CTL_LUN_DISABLED;
4648 	lun->backend = be_lun->be;
4649 	be_lun->ctl_lun = lun;
4650 	be_lun->lun_id = lun_number;
4651 	atomic_add_int(&be_lun->be->num_luns, 1);
4652 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4653 		lun->flags |= CTL_LUN_EJECTED;
4654 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4655 		lun->flags |= CTL_LUN_NO_MEDIA;
4656 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4657 		lun->flags |= CTL_LUN_STOPPED;
4658 
4659 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4660 		lun->flags |= CTL_LUN_PRIMARY_SC;
4661 
4662 	value = ctl_get_opt(&be_lun->options, "removable");
4663 	if (value != NULL) {
4664 		if (strcmp(value, "on") == 0)
4665 			lun->flags |= CTL_LUN_REMOVABLE;
4666 	} else if (be_lun->lun_type == T_CDROM)
4667 		lun->flags |= CTL_LUN_REMOVABLE;
4668 
4669 	lun->ctl_softc = ctl_softc;
4670 #ifdef CTL_TIME_IO
4671 	lun->last_busy = getsbinuptime();
4672 #endif
4673 	TAILQ_INIT(&lun->ooa_queue);
4674 	TAILQ_INIT(&lun->blocked_queue);
4675 	STAILQ_INIT(&lun->error_list);
4676 	lun->ie_reported = 1;
4677 	callout_init_mtx(&lun->ie_callout, &lun->lun_lock, 0);
4678 	ctl_tpc_lun_init(lun);
4679 	if (lun->flags & CTL_LUN_REMOVABLE) {
4680 		lun->prevent = malloc((CTL_MAX_INITIATORS + 31) / 32 * 4,
4681 		    M_CTL, M_WAITOK);
4682 	}
4683 
4684 	/*
4685 	 * Initialize the mode and log page index.
4686 	 */
4687 	ctl_init_page_index(lun);
4688 	ctl_init_log_page_index(lun);
4689 
4690 	/* Setup statistics gathering */
4691 #ifdef CTL_LEGACY_STATS
4692 	lun->legacy_stats.device_type = be_lun->lun_type;
4693 	lun->legacy_stats.lun_number = lun_number;
4694 	lun->legacy_stats.blocksize = be_lun->blocksize;
4695 	if (be_lun->blocksize == 0)
4696 		lun->legacy_stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4697 	for (len = 0; len < CTL_MAX_PORTS; len++)
4698 		lun->legacy_stats.ports[len].targ_port = len;
4699 #endif /* CTL_LEGACY_STATS */
4700 	lun->stats.item = lun_number;
4701 
4702 	/*
4703 	 * Now, before we insert this lun on the lun list, set the lun
4704 	 * inventory changed UA for all other luns.
4705 	 */
4706 	mtx_lock(&ctl_softc->ctl_lock);
4707 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4708 		mtx_lock(&nlun->lun_lock);
4709 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4710 		mtx_unlock(&nlun->lun_lock);
4711 	}
4712 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4713 	ctl_softc->ctl_luns[lun_number] = lun;
4714 	ctl_softc->num_luns++;
4715 	mtx_unlock(&ctl_softc->ctl_lock);
4716 
4717 	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4718 	return (0);
4719 }
4720 
4721 /*
4722  * Delete a LUN.
4723  * Assumptions:
4724  * - LUN has already been marked invalid and any pending I/O has been taken
4725  *   care of.
4726  */
4727 static int
4728 ctl_free_lun(struct ctl_lun *lun)
4729 {
4730 	struct ctl_softc *softc = lun->ctl_softc;
4731 	struct ctl_lun *nlun;
4732 	int i;
4733 
4734 	mtx_assert(&softc->ctl_lock, MA_OWNED);
4735 
4736 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4737 
4738 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4739 
4740 	softc->ctl_luns[lun->lun] = NULL;
4741 
4742 	if (!TAILQ_EMPTY(&lun->ooa_queue))
4743 		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4744 
4745 	softc->num_luns--;
4746 
4747 	/*
4748 	 * Tell the backend to free resources, if this LUN has a backend.
4749 	 */
4750 	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4751 	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4752 
4753 	lun->ie_reportcnt = UINT32_MAX;
4754 	callout_drain(&lun->ie_callout);
4755 
4756 	ctl_tpc_lun_shutdown(lun);
4757 	mtx_destroy(&lun->lun_lock);
4758 	free(lun->lun_devid, M_CTL);
4759 	for (i = 0; i < CTL_MAX_PORTS; i++)
4760 		free(lun->pending_ua[i], M_CTL);
4761 	for (i = 0; i < CTL_MAX_PORTS; i++)
4762 		free(lun->pr_keys[i], M_CTL);
4763 	free(lun->write_buffer, M_CTL);
4764 	free(lun->prevent, M_CTL);
4765 	if (lun->flags & CTL_LUN_MALLOCED)
4766 		free(lun, M_CTL);
4767 
4768 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4769 		mtx_lock(&nlun->lun_lock);
4770 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4771 		mtx_unlock(&nlun->lun_lock);
4772 	}
4773 
4774 	return (0);
4775 }
4776 
4777 static void
4778 ctl_create_lun(struct ctl_be_lun *be_lun)
4779 {
4780 
4781 	/*
4782 	 * ctl_alloc_lun() should handle all potential failure cases.
4783 	 */
4784 	ctl_alloc_lun(control_softc, NULL, be_lun);
4785 }
4786 
4787 int
4788 ctl_add_lun(struct ctl_be_lun *be_lun)
4789 {
4790 	struct ctl_softc *softc = control_softc;
4791 
4792 	mtx_lock(&softc->ctl_lock);
4793 	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4794 	mtx_unlock(&softc->ctl_lock);
4795 	wakeup(&softc->pending_lun_queue);
4796 
4797 	return (0);
4798 }
4799 
4800 int
4801 ctl_enable_lun(struct ctl_be_lun *be_lun)
4802 {
4803 	struct ctl_softc *softc;
4804 	struct ctl_port *port, *nport;
4805 	struct ctl_lun *lun;
4806 	int retval;
4807 
4808 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4809 	softc = lun->ctl_softc;
4810 
4811 	mtx_lock(&softc->ctl_lock);
4812 	mtx_lock(&lun->lun_lock);
4813 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4814 		/*
4815 		 * eh?  Why did we get called if the LUN is already
4816 		 * enabled?
4817 		 */
4818 		mtx_unlock(&lun->lun_lock);
4819 		mtx_unlock(&softc->ctl_lock);
4820 		return (0);
4821 	}
4822 	lun->flags &= ~CTL_LUN_DISABLED;
4823 	mtx_unlock(&lun->lun_lock);
4824 
4825 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4826 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4827 		    port->lun_map != NULL || port->lun_enable == NULL)
4828 			continue;
4829 
4830 		/*
4831 		 * Drop the lock while we call the FETD's enable routine.
4832 		 * This can lead to a callback into CTL (at least in the
4833 		 * case of the internal initiator frontend.
4834 		 */
4835 		mtx_unlock(&softc->ctl_lock);
4836 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4837 		mtx_lock(&softc->ctl_lock);
4838 		if (retval != 0) {
4839 			printf("%s: FETD %s port %d returned error "
4840 			       "%d for lun_enable on lun %jd\n",
4841 			       __func__, port->port_name, port->targ_port,
4842 			       retval, (intmax_t)lun->lun);
4843 		}
4844 	}
4845 
4846 	mtx_unlock(&softc->ctl_lock);
4847 	ctl_isc_announce_lun(lun);
4848 
4849 	return (0);
4850 }
4851 
4852 int
4853 ctl_disable_lun(struct ctl_be_lun *be_lun)
4854 {
4855 	struct ctl_softc *softc;
4856 	struct ctl_port *port;
4857 	struct ctl_lun *lun;
4858 	int retval;
4859 
4860 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4861 	softc = lun->ctl_softc;
4862 
4863 	mtx_lock(&softc->ctl_lock);
4864 	mtx_lock(&lun->lun_lock);
4865 	if (lun->flags & CTL_LUN_DISABLED) {
4866 		mtx_unlock(&lun->lun_lock);
4867 		mtx_unlock(&softc->ctl_lock);
4868 		return (0);
4869 	}
4870 	lun->flags |= CTL_LUN_DISABLED;
4871 	mtx_unlock(&lun->lun_lock);
4872 
4873 	STAILQ_FOREACH(port, &softc->port_list, links) {
4874 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4875 		    port->lun_map != NULL || port->lun_disable == NULL)
4876 			continue;
4877 
4878 		/*
4879 		 * Drop the lock before we call the frontend's disable
4880 		 * routine, to avoid lock order reversals.
4881 		 *
4882 		 * XXX KDM what happens if the frontend list changes while
4883 		 * we're traversing it?  It's unlikely, but should be handled.
4884 		 */
4885 		mtx_unlock(&softc->ctl_lock);
4886 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4887 		mtx_lock(&softc->ctl_lock);
4888 		if (retval != 0) {
4889 			printf("%s: FETD %s port %d returned error "
4890 			       "%d for lun_disable on lun %jd\n",
4891 			       __func__, port->port_name, port->targ_port,
4892 			       retval, (intmax_t)lun->lun);
4893 		}
4894 	}
4895 
4896 	mtx_unlock(&softc->ctl_lock);
4897 	ctl_isc_announce_lun(lun);
4898 
4899 	return (0);
4900 }
4901 
4902 int
4903 ctl_start_lun(struct ctl_be_lun *be_lun)
4904 {
4905 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4906 
4907 	mtx_lock(&lun->lun_lock);
4908 	lun->flags &= ~CTL_LUN_STOPPED;
4909 	mtx_unlock(&lun->lun_lock);
4910 	return (0);
4911 }
4912 
4913 int
4914 ctl_stop_lun(struct ctl_be_lun *be_lun)
4915 {
4916 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4917 
4918 	mtx_lock(&lun->lun_lock);
4919 	lun->flags |= CTL_LUN_STOPPED;
4920 	mtx_unlock(&lun->lun_lock);
4921 	return (0);
4922 }
4923 
4924 int
4925 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4926 {
4927 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4928 
4929 	mtx_lock(&lun->lun_lock);
4930 	lun->flags |= CTL_LUN_NO_MEDIA;
4931 	mtx_unlock(&lun->lun_lock);
4932 	return (0);
4933 }
4934 
4935 int
4936 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4937 {
4938 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4939 	union ctl_ha_msg msg;
4940 
4941 	mtx_lock(&lun->lun_lock);
4942 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4943 	if (lun->flags & CTL_LUN_REMOVABLE)
4944 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4945 	mtx_unlock(&lun->lun_lock);
4946 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4947 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4948 		bzero(&msg.ua, sizeof(msg.ua));
4949 		msg.hdr.msg_type = CTL_MSG_UA;
4950 		msg.hdr.nexus.initid = -1;
4951 		msg.hdr.nexus.targ_port = -1;
4952 		msg.hdr.nexus.targ_lun = lun->lun;
4953 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4954 		msg.ua.ua_all = 1;
4955 		msg.ua.ua_set = 1;
4956 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4957 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4958 		    M_WAITOK);
4959 	}
4960 	return (0);
4961 }
4962 
4963 int
4964 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4965 {
4966 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4967 
4968 	mtx_lock(&lun->lun_lock);
4969 	lun->flags |= CTL_LUN_EJECTED;
4970 	mtx_unlock(&lun->lun_lock);
4971 	return (0);
4972 }
4973 
4974 int
4975 ctl_lun_primary(struct ctl_be_lun *be_lun)
4976 {
4977 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4978 
4979 	mtx_lock(&lun->lun_lock);
4980 	lun->flags |= CTL_LUN_PRIMARY_SC;
4981 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4982 	mtx_unlock(&lun->lun_lock);
4983 	ctl_isc_announce_lun(lun);
4984 	return (0);
4985 }
4986 
4987 int
4988 ctl_lun_secondary(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_invalidate_lun(struct ctl_be_lun *be_lun)
5002 {
5003 	struct ctl_softc *softc;
5004 	struct ctl_lun *lun;
5005 
5006 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5007 	softc = lun->ctl_softc;
5008 
5009 	mtx_lock(&lun->lun_lock);
5010 
5011 	/*
5012 	 * The LUN needs to be disabled before it can be marked invalid.
5013 	 */
5014 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5015 		mtx_unlock(&lun->lun_lock);
5016 		return (-1);
5017 	}
5018 	/*
5019 	 * Mark the LUN invalid.
5020 	 */
5021 	lun->flags |= CTL_LUN_INVALID;
5022 
5023 	/*
5024 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5025 	 * If we have something in the OOA queue, we'll free it when the
5026 	 * last I/O completes.
5027 	 */
5028 	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5029 		mtx_unlock(&lun->lun_lock);
5030 		mtx_lock(&softc->ctl_lock);
5031 		ctl_free_lun(lun);
5032 		mtx_unlock(&softc->ctl_lock);
5033 	} else
5034 		mtx_unlock(&lun->lun_lock);
5035 
5036 	return (0);
5037 }
5038 
5039 void
5040 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5041 {
5042 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
5043 	union ctl_ha_msg msg;
5044 
5045 	mtx_lock(&lun->lun_lock);
5046 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
5047 	mtx_unlock(&lun->lun_lock);
5048 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
5049 		/* Send msg to other side. */
5050 		bzero(&msg.ua, sizeof(msg.ua));
5051 		msg.hdr.msg_type = CTL_MSG_UA;
5052 		msg.hdr.nexus.initid = -1;
5053 		msg.hdr.nexus.targ_port = -1;
5054 		msg.hdr.nexus.targ_lun = lun->lun;
5055 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
5056 		msg.ua.ua_all = 1;
5057 		msg.ua.ua_set = 1;
5058 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
5059 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
5060 		    M_WAITOK);
5061 	}
5062 }
5063 
5064 /*
5065  * Backend "memory move is complete" callback for requests that never
5066  * make it down to say RAIDCore's configuration code.
5067  */
5068 int
5069 ctl_config_move_done(union ctl_io *io)
5070 {
5071 	int retval;
5072 
5073 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5074 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
5075 	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
5076 
5077 	if ((io->io_hdr.port_status != 0) &&
5078 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5079 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5080 		ctl_set_internal_failure(&io->scsiio, /*sks_valid*/ 1,
5081 		    /*retry_count*/ io->io_hdr.port_status);
5082 	} else if (io->scsiio.kern_data_resid != 0 &&
5083 	    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT &&
5084 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5085 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5086 		ctl_set_invalid_field_ciu(&io->scsiio);
5087 	}
5088 
5089 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
5090 		ctl_data_print(io);
5091 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
5092 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5093 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
5094 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5095 		/*
5096 		 * XXX KDM just assuming a single pointer here, and not a
5097 		 * S/G list.  If we start using S/G lists for config data,
5098 		 * we'll need to know how to clean them up here as well.
5099 		 */
5100 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5101 			free(io->scsiio.kern_data_ptr, M_CTL);
5102 		ctl_done(io);
5103 		retval = CTL_RETVAL_COMPLETE;
5104 	} else {
5105 		/*
5106 		 * XXX KDM now we need to continue data movement.  Some
5107 		 * options:
5108 		 * - call ctl_scsiio() again?  We don't do this for data
5109 		 *   writes, because for those at least we know ahead of
5110 		 *   time where the write will go and how long it is.  For
5111 		 *   config writes, though, that information is largely
5112 		 *   contained within the write itself, thus we need to
5113 		 *   parse out the data again.
5114 		 *
5115 		 * - Call some other function once the data is in?
5116 		 */
5117 
5118 		/*
5119 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5120 		 * bits to see whether we're allocated or not.
5121 		 */
5122 		retval = ctl_scsiio(&io->scsiio);
5123 	}
5124 	return (retval);
5125 }
5126 
5127 /*
5128  * This gets called by a backend driver when it is done with a
5129  * data_submit method.
5130  */
5131 void
5132 ctl_data_submit_done(union ctl_io *io)
5133 {
5134 	/*
5135 	 * If the IO_CONT flag is set, we need to call the supplied
5136 	 * function to continue processing the I/O, instead of completing
5137 	 * the I/O just yet.
5138 	 *
5139 	 * If there is an error, though, we don't want to keep processing.
5140 	 * Instead, just send status back to the initiator.
5141 	 */
5142 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5143 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5144 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5145 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5146 		io->scsiio.io_cont(io);
5147 		return;
5148 	}
5149 	ctl_done(io);
5150 }
5151 
5152 /*
5153  * This gets called by a backend driver when it is done with a
5154  * configuration write.
5155  */
5156 void
5157 ctl_config_write_done(union ctl_io *io)
5158 {
5159 	uint8_t *buf;
5160 
5161 	/*
5162 	 * If the IO_CONT flag is set, we need to call the supplied
5163 	 * function to continue processing the I/O, instead of completing
5164 	 * the I/O just yet.
5165 	 *
5166 	 * If there is an error, though, we don't want to keep processing.
5167 	 * Instead, just send status back to the initiator.
5168 	 */
5169 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5170 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5171 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5172 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5173 		io->scsiio.io_cont(io);
5174 		return;
5175 	}
5176 	/*
5177 	 * Since a configuration write can be done for commands that actually
5178 	 * have data allocated, like write buffer, and commands that have
5179 	 * no data, like start/stop unit, we need to check here.
5180 	 */
5181 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5182 		buf = io->scsiio.kern_data_ptr;
5183 	else
5184 		buf = NULL;
5185 	ctl_done(io);
5186 	if (buf)
5187 		free(buf, M_CTL);
5188 }
5189 
5190 void
5191 ctl_config_read_done(union ctl_io *io)
5192 {
5193 	uint8_t *buf;
5194 
5195 	/*
5196 	 * If there is some error -- we are done, skip data transfer.
5197 	 */
5198 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5199 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5200 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5201 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5202 			buf = io->scsiio.kern_data_ptr;
5203 		else
5204 			buf = NULL;
5205 		ctl_done(io);
5206 		if (buf)
5207 			free(buf, M_CTL);
5208 		return;
5209 	}
5210 
5211 	/*
5212 	 * If the IO_CONT flag is set, we need to call the supplied
5213 	 * function to continue processing the I/O, instead of completing
5214 	 * the I/O just yet.
5215 	 */
5216 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5217 		io->scsiio.io_cont(io);
5218 		return;
5219 	}
5220 
5221 	ctl_datamove(io);
5222 }
5223 
5224 /*
5225  * SCSI release command.
5226  */
5227 int
5228 ctl_scsi_release(struct ctl_scsiio *ctsio)
5229 {
5230 	struct ctl_lun *lun = CTL_LUN(ctsio);
5231 	uint32_t residx;
5232 
5233 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5234 
5235 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5236 
5237 	/*
5238 	 * XXX KDM right now, we only support LUN reservation.  We don't
5239 	 * support 3rd party reservations, or extent reservations, which
5240 	 * might actually need the parameter list.  If we've gotten this
5241 	 * far, we've got a LUN reservation.  Anything else got kicked out
5242 	 * above.  So, according to SPC, ignore the length.
5243 	 */
5244 
5245 	mtx_lock(&lun->lun_lock);
5246 
5247 	/*
5248 	 * According to SPC, it is not an error for an intiator to attempt
5249 	 * to release a reservation on a LUN that isn't reserved, or that
5250 	 * is reserved by another initiator.  The reservation can only be
5251 	 * released, though, by the initiator who made it or by one of
5252 	 * several reset type events.
5253 	 */
5254 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5255 			lun->flags &= ~CTL_LUN_RESERVED;
5256 
5257 	mtx_unlock(&lun->lun_lock);
5258 
5259 	ctl_set_success(ctsio);
5260 	ctl_done((union ctl_io *)ctsio);
5261 	return (CTL_RETVAL_COMPLETE);
5262 }
5263 
5264 int
5265 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5266 {
5267 	struct ctl_lun *lun = CTL_LUN(ctsio);
5268 	uint32_t residx;
5269 
5270 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5271 
5272 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5273 
5274 	/*
5275 	 * XXX KDM right now, we only support LUN reservation.  We don't
5276 	 * support 3rd party reservations, or extent reservations, which
5277 	 * might actually need the parameter list.  If we've gotten this
5278 	 * far, we've got a LUN reservation.  Anything else got kicked out
5279 	 * above.  So, according to SPC, ignore the length.
5280 	 */
5281 
5282 	mtx_lock(&lun->lun_lock);
5283 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5284 		ctl_set_reservation_conflict(ctsio);
5285 		goto bailout;
5286 	}
5287 
5288 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5289 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5290 		ctl_set_success(ctsio);
5291 		goto bailout;
5292 	}
5293 
5294 	lun->flags |= CTL_LUN_RESERVED;
5295 	lun->res_idx = residx;
5296 	ctl_set_success(ctsio);
5297 
5298 bailout:
5299 	mtx_unlock(&lun->lun_lock);
5300 	ctl_done((union ctl_io *)ctsio);
5301 	return (CTL_RETVAL_COMPLETE);
5302 }
5303 
5304 int
5305 ctl_start_stop(struct ctl_scsiio *ctsio)
5306 {
5307 	struct ctl_lun *lun = CTL_LUN(ctsio);
5308 	struct scsi_start_stop_unit *cdb;
5309 	int retval;
5310 
5311 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5312 
5313 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5314 
5315 	if ((cdb->how & SSS_PC_MASK) == 0) {
5316 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5317 		    (cdb->how & SSS_START) == 0) {
5318 			uint32_t residx;
5319 
5320 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5321 			if (ctl_get_prkey(lun, residx) == 0 ||
5322 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5323 
5324 				ctl_set_reservation_conflict(ctsio);
5325 				ctl_done((union ctl_io *)ctsio);
5326 				return (CTL_RETVAL_COMPLETE);
5327 			}
5328 		}
5329 
5330 		if ((cdb->how & SSS_LOEJ) &&
5331 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5332 			ctl_set_invalid_field(ctsio,
5333 					      /*sks_valid*/ 1,
5334 					      /*command*/ 1,
5335 					      /*field*/ 4,
5336 					      /*bit_valid*/ 1,
5337 					      /*bit*/ 1);
5338 			ctl_done((union ctl_io *)ctsio);
5339 			return (CTL_RETVAL_COMPLETE);
5340 		}
5341 
5342 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5343 		    lun->prevent_count > 0) {
5344 			/* "Medium removal prevented" */
5345 			ctl_set_sense(ctsio, /*current_error*/ 1,
5346 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5347 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5348 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5349 			ctl_done((union ctl_io *)ctsio);
5350 			return (CTL_RETVAL_COMPLETE);
5351 		}
5352 	}
5353 
5354 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5355 	return (retval);
5356 }
5357 
5358 int
5359 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5360 {
5361 	struct ctl_lun *lun = CTL_LUN(ctsio);
5362 	struct scsi_prevent *cdb;
5363 	int retval;
5364 	uint32_t initidx;
5365 
5366 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5367 
5368 	cdb = (struct scsi_prevent *)ctsio->cdb;
5369 
5370 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0 || lun->prevent == NULL) {
5371 		ctl_set_invalid_opcode(ctsio);
5372 		ctl_done((union ctl_io *)ctsio);
5373 		return (CTL_RETVAL_COMPLETE);
5374 	}
5375 
5376 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5377 	mtx_lock(&lun->lun_lock);
5378 	if ((cdb->how & PR_PREVENT) &&
5379 	    ctl_is_set(lun->prevent, initidx) == 0) {
5380 		ctl_set_mask(lun->prevent, initidx);
5381 		lun->prevent_count++;
5382 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5383 	    ctl_is_set(lun->prevent, initidx)) {
5384 		ctl_clear_mask(lun->prevent, initidx);
5385 		lun->prevent_count--;
5386 	}
5387 	mtx_unlock(&lun->lun_lock);
5388 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5389 	return (retval);
5390 }
5391 
5392 /*
5393  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5394  * we don't really do anything with the LBA and length fields if the user
5395  * passes them in.  Instead we'll just flush out the cache for the entire
5396  * LUN.
5397  */
5398 int
5399 ctl_sync_cache(struct ctl_scsiio *ctsio)
5400 {
5401 	struct ctl_lun *lun = CTL_LUN(ctsio);
5402 	struct ctl_lba_len_flags *lbalen;
5403 	uint64_t starting_lba;
5404 	uint32_t block_count;
5405 	int retval;
5406 	uint8_t byte2;
5407 
5408 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5409 
5410 	retval = 0;
5411 
5412 	switch (ctsio->cdb[0]) {
5413 	case SYNCHRONIZE_CACHE: {
5414 		struct scsi_sync_cache *cdb;
5415 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5416 
5417 		starting_lba = scsi_4btoul(cdb->begin_lba);
5418 		block_count = scsi_2btoul(cdb->lb_count);
5419 		byte2 = cdb->byte2;
5420 		break;
5421 	}
5422 	case SYNCHRONIZE_CACHE_16: {
5423 		struct scsi_sync_cache_16 *cdb;
5424 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5425 
5426 		starting_lba = scsi_8btou64(cdb->begin_lba);
5427 		block_count = scsi_4btoul(cdb->lb_count);
5428 		byte2 = cdb->byte2;
5429 		break;
5430 	}
5431 	default:
5432 		ctl_set_invalid_opcode(ctsio);
5433 		ctl_done((union ctl_io *)ctsio);
5434 		goto bailout;
5435 		break; /* NOTREACHED */
5436 	}
5437 
5438 	/*
5439 	 * We check the LBA and length, but don't do anything with them.
5440 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5441 	 * get flushed.  This check will just help satisfy anyone who wants
5442 	 * to see an error for an out of range LBA.
5443 	 */
5444 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5445 		ctl_set_lba_out_of_range(ctsio,
5446 		    MAX(starting_lba, lun->be_lun->maxlba + 1));
5447 		ctl_done((union ctl_io *)ctsio);
5448 		goto bailout;
5449 	}
5450 
5451 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5452 	lbalen->lba = starting_lba;
5453 	lbalen->len = block_count;
5454 	lbalen->flags = byte2;
5455 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5456 
5457 bailout:
5458 	return (retval);
5459 }
5460 
5461 int
5462 ctl_format(struct ctl_scsiio *ctsio)
5463 {
5464 	struct scsi_format *cdb;
5465 	int length, defect_list_len;
5466 
5467 	CTL_DEBUG_PRINT(("ctl_format\n"));
5468 
5469 	cdb = (struct scsi_format *)ctsio->cdb;
5470 
5471 	length = 0;
5472 	if (cdb->byte2 & SF_FMTDATA) {
5473 		if (cdb->byte2 & SF_LONGLIST)
5474 			length = sizeof(struct scsi_format_header_long);
5475 		else
5476 			length = sizeof(struct scsi_format_header_short);
5477 	}
5478 
5479 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5480 	 && (length > 0)) {
5481 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5482 		ctsio->kern_data_len = length;
5483 		ctsio->kern_total_len = length;
5484 		ctsio->kern_rel_offset = 0;
5485 		ctsio->kern_sg_entries = 0;
5486 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5487 		ctsio->be_move_done = ctl_config_move_done;
5488 		ctl_datamove((union ctl_io *)ctsio);
5489 
5490 		return (CTL_RETVAL_COMPLETE);
5491 	}
5492 
5493 	defect_list_len = 0;
5494 
5495 	if (cdb->byte2 & SF_FMTDATA) {
5496 		if (cdb->byte2 & SF_LONGLIST) {
5497 			struct scsi_format_header_long *header;
5498 
5499 			header = (struct scsi_format_header_long *)
5500 				ctsio->kern_data_ptr;
5501 
5502 			defect_list_len = scsi_4btoul(header->defect_list_len);
5503 			if (defect_list_len != 0) {
5504 				ctl_set_invalid_field(ctsio,
5505 						      /*sks_valid*/ 1,
5506 						      /*command*/ 0,
5507 						      /*field*/ 2,
5508 						      /*bit_valid*/ 0,
5509 						      /*bit*/ 0);
5510 				goto bailout;
5511 			}
5512 		} else {
5513 			struct scsi_format_header_short *header;
5514 
5515 			header = (struct scsi_format_header_short *)
5516 				ctsio->kern_data_ptr;
5517 
5518 			defect_list_len = scsi_2btoul(header->defect_list_len);
5519 			if (defect_list_len != 0) {
5520 				ctl_set_invalid_field(ctsio,
5521 						      /*sks_valid*/ 1,
5522 						      /*command*/ 0,
5523 						      /*field*/ 2,
5524 						      /*bit_valid*/ 0,
5525 						      /*bit*/ 0);
5526 				goto bailout;
5527 			}
5528 		}
5529 	}
5530 
5531 	ctl_set_success(ctsio);
5532 bailout:
5533 
5534 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5535 		free(ctsio->kern_data_ptr, M_CTL);
5536 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5537 	}
5538 
5539 	ctl_done((union ctl_io *)ctsio);
5540 	return (CTL_RETVAL_COMPLETE);
5541 }
5542 
5543 int
5544 ctl_read_buffer(struct ctl_scsiio *ctsio)
5545 {
5546 	struct ctl_lun *lun = CTL_LUN(ctsio);
5547 	uint64_t buffer_offset;
5548 	uint32_t len;
5549 	uint8_t byte2;
5550 	static uint8_t descr[4];
5551 	static uint8_t echo_descr[4] = { 0 };
5552 
5553 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5554 
5555 	switch (ctsio->cdb[0]) {
5556 	case READ_BUFFER: {
5557 		struct scsi_read_buffer *cdb;
5558 
5559 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5560 		buffer_offset = scsi_3btoul(cdb->offset);
5561 		len = scsi_3btoul(cdb->length);
5562 		byte2 = cdb->byte2;
5563 		break;
5564 	}
5565 	case READ_BUFFER_16: {
5566 		struct scsi_read_buffer_16 *cdb;
5567 
5568 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5569 		buffer_offset = scsi_8btou64(cdb->offset);
5570 		len = scsi_4btoul(cdb->length);
5571 		byte2 = cdb->byte2;
5572 		break;
5573 	}
5574 	default: /* This shouldn't happen. */
5575 		ctl_set_invalid_opcode(ctsio);
5576 		ctl_done((union ctl_io *)ctsio);
5577 		return (CTL_RETVAL_COMPLETE);
5578 	}
5579 
5580 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5581 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5582 		ctl_set_invalid_field(ctsio,
5583 				      /*sks_valid*/ 1,
5584 				      /*command*/ 1,
5585 				      /*field*/ 6,
5586 				      /*bit_valid*/ 0,
5587 				      /*bit*/ 0);
5588 		ctl_done((union ctl_io *)ctsio);
5589 		return (CTL_RETVAL_COMPLETE);
5590 	}
5591 
5592 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5593 		descr[0] = 0;
5594 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5595 		ctsio->kern_data_ptr = descr;
5596 		len = min(len, sizeof(descr));
5597 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5598 		ctsio->kern_data_ptr = echo_descr;
5599 		len = min(len, sizeof(echo_descr));
5600 	} else {
5601 		if (lun->write_buffer == NULL) {
5602 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5603 			    M_CTL, M_WAITOK);
5604 		}
5605 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5606 	}
5607 	ctsio->kern_data_len = len;
5608 	ctsio->kern_total_len = len;
5609 	ctsio->kern_rel_offset = 0;
5610 	ctsio->kern_sg_entries = 0;
5611 	ctl_set_success(ctsio);
5612 	ctsio->be_move_done = ctl_config_move_done;
5613 	ctl_datamove((union ctl_io *)ctsio);
5614 	return (CTL_RETVAL_COMPLETE);
5615 }
5616 
5617 int
5618 ctl_write_buffer(struct ctl_scsiio *ctsio)
5619 {
5620 	struct ctl_lun *lun = CTL_LUN(ctsio);
5621 	struct scsi_write_buffer *cdb;
5622 	int buffer_offset, len;
5623 
5624 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5625 
5626 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5627 
5628 	len = scsi_3btoul(cdb->length);
5629 	buffer_offset = scsi_3btoul(cdb->offset);
5630 
5631 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5632 		ctl_set_invalid_field(ctsio,
5633 				      /*sks_valid*/ 1,
5634 				      /*command*/ 1,
5635 				      /*field*/ 6,
5636 				      /*bit_valid*/ 0,
5637 				      /*bit*/ 0);
5638 		ctl_done((union ctl_io *)ctsio);
5639 		return (CTL_RETVAL_COMPLETE);
5640 	}
5641 
5642 	/*
5643 	 * If we've got a kernel request that hasn't been malloced yet,
5644 	 * malloc it and tell the caller the data buffer is here.
5645 	 */
5646 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5647 		if (lun->write_buffer == NULL) {
5648 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5649 			    M_CTL, M_WAITOK);
5650 		}
5651 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5652 		ctsio->kern_data_len = len;
5653 		ctsio->kern_total_len = len;
5654 		ctsio->kern_rel_offset = 0;
5655 		ctsio->kern_sg_entries = 0;
5656 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5657 		ctsio->be_move_done = ctl_config_move_done;
5658 		ctl_datamove((union ctl_io *)ctsio);
5659 
5660 		return (CTL_RETVAL_COMPLETE);
5661 	}
5662 
5663 	ctl_set_success(ctsio);
5664 	ctl_done((union ctl_io *)ctsio);
5665 	return (CTL_RETVAL_COMPLETE);
5666 }
5667 
5668 int
5669 ctl_write_same(struct ctl_scsiio *ctsio)
5670 {
5671 	struct ctl_lun *lun = CTL_LUN(ctsio);
5672 	struct ctl_lba_len_flags *lbalen;
5673 	uint64_t lba;
5674 	uint32_t num_blocks;
5675 	int len, retval;
5676 	uint8_t byte2;
5677 
5678 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5679 
5680 	switch (ctsio->cdb[0]) {
5681 	case WRITE_SAME_10: {
5682 		struct scsi_write_same_10 *cdb;
5683 
5684 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5685 
5686 		lba = scsi_4btoul(cdb->addr);
5687 		num_blocks = scsi_2btoul(cdb->length);
5688 		byte2 = cdb->byte2;
5689 		break;
5690 	}
5691 	case WRITE_SAME_16: {
5692 		struct scsi_write_same_16 *cdb;
5693 
5694 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5695 
5696 		lba = scsi_8btou64(cdb->addr);
5697 		num_blocks = scsi_4btoul(cdb->length);
5698 		byte2 = cdb->byte2;
5699 		break;
5700 	}
5701 	default:
5702 		/*
5703 		 * We got a command we don't support.  This shouldn't
5704 		 * happen, commands should be filtered out above us.
5705 		 */
5706 		ctl_set_invalid_opcode(ctsio);
5707 		ctl_done((union ctl_io *)ctsio);
5708 
5709 		return (CTL_RETVAL_COMPLETE);
5710 		break; /* NOTREACHED */
5711 	}
5712 
5713 	/* ANCHOR flag can be used only together with UNMAP */
5714 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5715 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5716 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5717 		ctl_done((union ctl_io *)ctsio);
5718 		return (CTL_RETVAL_COMPLETE);
5719 	}
5720 
5721 	/*
5722 	 * The first check is to make sure we're in bounds, the second
5723 	 * check is to catch wrap-around problems.  If the lba + num blocks
5724 	 * is less than the lba, then we've wrapped around and the block
5725 	 * range is invalid anyway.
5726 	 */
5727 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5728 	 || ((lba + num_blocks) < lba)) {
5729 		ctl_set_lba_out_of_range(ctsio,
5730 		    MAX(lba, lun->be_lun->maxlba + 1));
5731 		ctl_done((union ctl_io *)ctsio);
5732 		return (CTL_RETVAL_COMPLETE);
5733 	}
5734 
5735 	/* Zero number of blocks means "to the last logical block" */
5736 	if (num_blocks == 0) {
5737 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5738 			ctl_set_invalid_field(ctsio,
5739 					      /*sks_valid*/ 0,
5740 					      /*command*/ 1,
5741 					      /*field*/ 0,
5742 					      /*bit_valid*/ 0,
5743 					      /*bit*/ 0);
5744 			ctl_done((union ctl_io *)ctsio);
5745 			return (CTL_RETVAL_COMPLETE);
5746 		}
5747 		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5748 	}
5749 
5750 	len = lun->be_lun->blocksize;
5751 
5752 	/*
5753 	 * If we've got a kernel request that hasn't been malloced yet,
5754 	 * malloc it and tell the caller the data buffer is here.
5755 	 */
5756 	if ((byte2 & SWS_NDOB) == 0 &&
5757 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5758 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5759 		ctsio->kern_data_len = len;
5760 		ctsio->kern_total_len = len;
5761 		ctsio->kern_rel_offset = 0;
5762 		ctsio->kern_sg_entries = 0;
5763 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5764 		ctsio->be_move_done = ctl_config_move_done;
5765 		ctl_datamove((union ctl_io *)ctsio);
5766 
5767 		return (CTL_RETVAL_COMPLETE);
5768 	}
5769 
5770 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5771 	lbalen->lba = lba;
5772 	lbalen->len = num_blocks;
5773 	lbalen->flags = byte2;
5774 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5775 
5776 	return (retval);
5777 }
5778 
5779 int
5780 ctl_unmap(struct ctl_scsiio *ctsio)
5781 {
5782 	struct ctl_lun *lun = CTL_LUN(ctsio);
5783 	struct scsi_unmap *cdb;
5784 	struct ctl_ptr_len_flags *ptrlen;
5785 	struct scsi_unmap_header *hdr;
5786 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5787 	uint64_t lba;
5788 	uint32_t num_blocks;
5789 	int len, retval;
5790 	uint8_t byte2;
5791 
5792 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5793 
5794 	cdb = (struct scsi_unmap *)ctsio->cdb;
5795 	len = scsi_2btoul(cdb->length);
5796 	byte2 = cdb->byte2;
5797 
5798 	/*
5799 	 * If we've got a kernel request that hasn't been malloced yet,
5800 	 * malloc it and tell the caller the data buffer is here.
5801 	 */
5802 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5803 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);
5804 		ctsio->kern_data_len = len;
5805 		ctsio->kern_total_len = len;
5806 		ctsio->kern_rel_offset = 0;
5807 		ctsio->kern_sg_entries = 0;
5808 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5809 		ctsio->be_move_done = ctl_config_move_done;
5810 		ctl_datamove((union ctl_io *)ctsio);
5811 
5812 		return (CTL_RETVAL_COMPLETE);
5813 	}
5814 
5815 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5816 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5817 	if (len < sizeof (*hdr) ||
5818 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5819 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5820 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5821 		ctl_set_invalid_field(ctsio,
5822 				      /*sks_valid*/ 0,
5823 				      /*command*/ 0,
5824 				      /*field*/ 0,
5825 				      /*bit_valid*/ 0,
5826 				      /*bit*/ 0);
5827 		goto done;
5828 	}
5829 	len = scsi_2btoul(hdr->desc_length);
5830 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5831 	end = buf + len / sizeof(*buf);
5832 
5833 	endnz = buf;
5834 	for (range = buf; range < end; range++) {
5835 		lba = scsi_8btou64(range->lba);
5836 		num_blocks = scsi_4btoul(range->length);
5837 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5838 		 || ((lba + num_blocks) < lba)) {
5839 			ctl_set_lba_out_of_range(ctsio,
5840 			    MAX(lba, lun->be_lun->maxlba + 1));
5841 			ctl_done((union ctl_io *)ctsio);
5842 			return (CTL_RETVAL_COMPLETE);
5843 		}
5844 		if (num_blocks != 0)
5845 			endnz = range + 1;
5846 	}
5847 
5848 	/*
5849 	 * Block backend can not handle zero last range.
5850 	 * Filter it out and return if there is nothing left.
5851 	 */
5852 	len = (uint8_t *)endnz - (uint8_t *)buf;
5853 	if (len == 0) {
5854 		ctl_set_success(ctsio);
5855 		goto done;
5856 	}
5857 
5858 	mtx_lock(&lun->lun_lock);
5859 	ptrlen = (struct ctl_ptr_len_flags *)
5860 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5861 	ptrlen->ptr = (void *)buf;
5862 	ptrlen->len = len;
5863 	ptrlen->flags = byte2;
5864 	ctl_check_blocked(lun);
5865 	mtx_unlock(&lun->lun_lock);
5866 
5867 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5868 	return (retval);
5869 
5870 done:
5871 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5872 		free(ctsio->kern_data_ptr, M_CTL);
5873 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5874 	}
5875 	ctl_done((union ctl_io *)ctsio);
5876 	return (CTL_RETVAL_COMPLETE);
5877 }
5878 
5879 int
5880 ctl_default_page_handler(struct ctl_scsiio *ctsio,
5881 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5882 {
5883 	struct ctl_lun *lun = CTL_LUN(ctsio);
5884 	uint8_t *current_cp;
5885 	int set_ua;
5886 	uint32_t initidx;
5887 
5888 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5889 	set_ua = 0;
5890 
5891 	current_cp = (page_index->page_data + (page_index->page_len *
5892 	    CTL_PAGE_CURRENT));
5893 
5894 	mtx_lock(&lun->lun_lock);
5895 	if (memcmp(current_cp, page_ptr, page_index->page_len)) {
5896 		memcpy(current_cp, page_ptr, page_index->page_len);
5897 		set_ua = 1;
5898 	}
5899 	if (set_ua != 0)
5900 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5901 	mtx_unlock(&lun->lun_lock);
5902 	if (set_ua) {
5903 		ctl_isc_announce_mode(lun,
5904 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5905 		    page_index->page_code, page_index->subpage);
5906 	}
5907 	return (CTL_RETVAL_COMPLETE);
5908 }
5909 
5910 static void
5911 ctl_ie_timer(void *arg)
5912 {
5913 	struct ctl_lun *lun = arg;
5914 	uint64_t t;
5915 
5916 	if (lun->ie_asc == 0)
5917 		return;
5918 
5919 	if (lun->MODE_IE.mrie == SIEP_MRIE_UA)
5920 		ctl_est_ua_all(lun, -1, CTL_UA_IE);
5921 	else
5922 		lun->ie_reported = 0;
5923 
5924 	if (lun->ie_reportcnt < scsi_4btoul(lun->MODE_IE.report_count)) {
5925 		lun->ie_reportcnt++;
5926 		t = scsi_4btoul(lun->MODE_IE.interval_timer);
5927 		if (t == 0 || t == UINT32_MAX)
5928 			t = 3000;  /* 5 min */
5929 		callout_schedule(&lun->ie_callout, t * hz / 10);
5930 	}
5931 }
5932 
5933 int
5934 ctl_ie_page_handler(struct ctl_scsiio *ctsio,
5935 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5936 {
5937 	struct ctl_lun *lun = CTL_LUN(ctsio);
5938 	struct scsi_info_exceptions_page *pg;
5939 	uint64_t t;
5940 
5941 	(void)ctl_default_page_handler(ctsio, page_index, page_ptr);
5942 
5943 	pg = (struct scsi_info_exceptions_page *)page_ptr;
5944 	mtx_lock(&lun->lun_lock);
5945 	if (pg->info_flags & SIEP_FLAGS_TEST) {
5946 		lun->ie_asc = 0x5d;
5947 		lun->ie_ascq = 0xff;
5948 		if (pg->mrie == SIEP_MRIE_UA) {
5949 			ctl_est_ua_all(lun, -1, CTL_UA_IE);
5950 			lun->ie_reported = 1;
5951 		} else {
5952 			ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5953 			lun->ie_reported = -1;
5954 		}
5955 		lun->ie_reportcnt = 1;
5956 		if (lun->ie_reportcnt < scsi_4btoul(pg->report_count)) {
5957 			lun->ie_reportcnt++;
5958 			t = scsi_4btoul(pg->interval_timer);
5959 			if (t == 0 || t == UINT32_MAX)
5960 				t = 3000;  /* 5 min */
5961 			callout_reset(&lun->ie_callout, t * hz / 10,
5962 			    ctl_ie_timer, lun);
5963 		}
5964 	} else {
5965 		lun->ie_asc = 0;
5966 		lun->ie_ascq = 0;
5967 		lun->ie_reported = 1;
5968 		ctl_clr_ua_all(lun, -1, CTL_UA_IE);
5969 		lun->ie_reportcnt = UINT32_MAX;
5970 		callout_stop(&lun->ie_callout);
5971 	}
5972 	mtx_unlock(&lun->lun_lock);
5973 	return (CTL_RETVAL_COMPLETE);
5974 }
5975 
5976 static int
5977 ctl_do_mode_select(union ctl_io *io)
5978 {
5979 	struct ctl_lun *lun = CTL_LUN(io);
5980 	struct scsi_mode_page_header *page_header;
5981 	struct ctl_page_index *page_index;
5982 	struct ctl_scsiio *ctsio;
5983 	int page_len, page_len_offset, page_len_size;
5984 	union ctl_modepage_info *modepage_info;
5985 	uint16_t *len_left, *len_used;
5986 	int retval, i;
5987 
5988 	ctsio = &io->scsiio;
5989 	page_index = NULL;
5990 	page_len = 0;
5991 
5992 	modepage_info = (union ctl_modepage_info *)
5993 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5994 	len_left = &modepage_info->header.len_left;
5995 	len_used = &modepage_info->header.len_used;
5996 
5997 do_next_page:
5998 
5999 	page_header = (struct scsi_mode_page_header *)
6000 		(ctsio->kern_data_ptr + *len_used);
6001 
6002 	if (*len_left == 0) {
6003 		free(ctsio->kern_data_ptr, M_CTL);
6004 		ctl_set_success(ctsio);
6005 		ctl_done((union ctl_io *)ctsio);
6006 		return (CTL_RETVAL_COMPLETE);
6007 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6008 
6009 		free(ctsio->kern_data_ptr, M_CTL);
6010 		ctl_set_param_len_error(ctsio);
6011 		ctl_done((union ctl_io *)ctsio);
6012 		return (CTL_RETVAL_COMPLETE);
6013 
6014 	} else if ((page_header->page_code & SMPH_SPF)
6015 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6016 
6017 		free(ctsio->kern_data_ptr, M_CTL);
6018 		ctl_set_param_len_error(ctsio);
6019 		ctl_done((union ctl_io *)ctsio);
6020 		return (CTL_RETVAL_COMPLETE);
6021 	}
6022 
6023 
6024 	/*
6025 	 * XXX KDM should we do something with the block descriptor?
6026 	 */
6027 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6028 		page_index = &lun->mode_pages.index[i];
6029 		if (lun->be_lun->lun_type == T_DIRECT &&
6030 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6031 			continue;
6032 		if (lun->be_lun->lun_type == T_PROCESSOR &&
6033 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6034 			continue;
6035 		if (lun->be_lun->lun_type == T_CDROM &&
6036 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6037 			continue;
6038 
6039 		if ((page_index->page_code & SMPH_PC_MASK) !=
6040 		    (page_header->page_code & SMPH_PC_MASK))
6041 			continue;
6042 
6043 		/*
6044 		 * If neither page has a subpage code, then we've got a
6045 		 * match.
6046 		 */
6047 		if (((page_index->page_code & SMPH_SPF) == 0)
6048 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6049 			page_len = page_header->page_length;
6050 			break;
6051 		}
6052 
6053 		/*
6054 		 * If both pages have subpages, then the subpage numbers
6055 		 * have to match.
6056 		 */
6057 		if ((page_index->page_code & SMPH_SPF)
6058 		  && (page_header->page_code & SMPH_SPF)) {
6059 			struct scsi_mode_page_header_sp *sph;
6060 
6061 			sph = (struct scsi_mode_page_header_sp *)page_header;
6062 			if (page_index->subpage == sph->subpage) {
6063 				page_len = scsi_2btoul(sph->page_length);
6064 				break;
6065 			}
6066 		}
6067 	}
6068 
6069 	/*
6070 	 * If we couldn't find the page, or if we don't have a mode select
6071 	 * handler for it, send back an error to the user.
6072 	 */
6073 	if ((i >= CTL_NUM_MODE_PAGES)
6074 	 || (page_index->select_handler == NULL)) {
6075 		ctl_set_invalid_field(ctsio,
6076 				      /*sks_valid*/ 1,
6077 				      /*command*/ 0,
6078 				      /*field*/ *len_used,
6079 				      /*bit_valid*/ 0,
6080 				      /*bit*/ 0);
6081 		free(ctsio->kern_data_ptr, M_CTL);
6082 		ctl_done((union ctl_io *)ctsio);
6083 		return (CTL_RETVAL_COMPLETE);
6084 	}
6085 
6086 	if (page_index->page_code & SMPH_SPF) {
6087 		page_len_offset = 2;
6088 		page_len_size = 2;
6089 	} else {
6090 		page_len_size = 1;
6091 		page_len_offset = 1;
6092 	}
6093 
6094 	/*
6095 	 * If the length the initiator gives us isn't the one we specify in
6096 	 * the mode page header, or if they didn't specify enough data in
6097 	 * the CDB to avoid truncating this page, kick out the request.
6098 	 */
6099 	if (page_len != page_index->page_len - page_len_offset - page_len_size) {
6100 		ctl_set_invalid_field(ctsio,
6101 				      /*sks_valid*/ 1,
6102 				      /*command*/ 0,
6103 				      /*field*/ *len_used + page_len_offset,
6104 				      /*bit_valid*/ 0,
6105 				      /*bit*/ 0);
6106 		free(ctsio->kern_data_ptr, M_CTL);
6107 		ctl_done((union ctl_io *)ctsio);
6108 		return (CTL_RETVAL_COMPLETE);
6109 	}
6110 	if (*len_left < page_index->page_len) {
6111 		free(ctsio->kern_data_ptr, M_CTL);
6112 		ctl_set_param_len_error(ctsio);
6113 		ctl_done((union ctl_io *)ctsio);
6114 		return (CTL_RETVAL_COMPLETE);
6115 	}
6116 
6117 	/*
6118 	 * Run through the mode page, checking to make sure that the bits
6119 	 * the user changed are actually legal for him to change.
6120 	 */
6121 	for (i = 0; i < page_index->page_len; i++) {
6122 		uint8_t *user_byte, *change_mask, *current_byte;
6123 		int bad_bit;
6124 		int j;
6125 
6126 		user_byte = (uint8_t *)page_header + i;
6127 		change_mask = page_index->page_data +
6128 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6129 		current_byte = page_index->page_data +
6130 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6131 
6132 		/*
6133 		 * Check to see whether the user set any bits in this byte
6134 		 * that he is not allowed to set.
6135 		 */
6136 		if ((*user_byte & ~(*change_mask)) ==
6137 		    (*current_byte & ~(*change_mask)))
6138 			continue;
6139 
6140 		/*
6141 		 * Go through bit by bit to determine which one is illegal.
6142 		 */
6143 		bad_bit = 0;
6144 		for (j = 7; j >= 0; j--) {
6145 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6146 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6147 				bad_bit = i;
6148 				break;
6149 			}
6150 		}
6151 		ctl_set_invalid_field(ctsio,
6152 				      /*sks_valid*/ 1,
6153 				      /*command*/ 0,
6154 				      /*field*/ *len_used + i,
6155 				      /*bit_valid*/ 1,
6156 				      /*bit*/ bad_bit);
6157 		free(ctsio->kern_data_ptr, M_CTL);
6158 		ctl_done((union ctl_io *)ctsio);
6159 		return (CTL_RETVAL_COMPLETE);
6160 	}
6161 
6162 	/*
6163 	 * Decrement these before we call the page handler, since we may
6164 	 * end up getting called back one way or another before the handler
6165 	 * returns to this context.
6166 	 */
6167 	*len_left -= page_index->page_len;
6168 	*len_used += page_index->page_len;
6169 
6170 	retval = page_index->select_handler(ctsio, page_index,
6171 					    (uint8_t *)page_header);
6172 
6173 	/*
6174 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6175 	 * wait until this queued command completes to finish processing
6176 	 * the mode page.  If it returns anything other than
6177 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6178 	 * already set the sense information, freed the data pointer, and
6179 	 * completed the io for us.
6180 	 */
6181 	if (retval != CTL_RETVAL_COMPLETE)
6182 		goto bailout_no_done;
6183 
6184 	/*
6185 	 * If the initiator sent us more than one page, parse the next one.
6186 	 */
6187 	if (*len_left > 0)
6188 		goto do_next_page;
6189 
6190 	ctl_set_success(ctsio);
6191 	free(ctsio->kern_data_ptr, M_CTL);
6192 	ctl_done((union ctl_io *)ctsio);
6193 
6194 bailout_no_done:
6195 
6196 	return (CTL_RETVAL_COMPLETE);
6197 
6198 }
6199 
6200 int
6201 ctl_mode_select(struct ctl_scsiio *ctsio)
6202 {
6203 	struct ctl_lun *lun = CTL_LUN(ctsio);
6204 	union ctl_modepage_info *modepage_info;
6205 	int bd_len, i, header_size, param_len, pf, rtd, sp;
6206 	uint32_t initidx;
6207 
6208 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6209 	switch (ctsio->cdb[0]) {
6210 	case MODE_SELECT_6: {
6211 		struct scsi_mode_select_6 *cdb;
6212 
6213 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6214 
6215 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6216 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6217 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6218 		param_len = cdb->length;
6219 		header_size = sizeof(struct scsi_mode_header_6);
6220 		break;
6221 	}
6222 	case MODE_SELECT_10: {
6223 		struct scsi_mode_select_10 *cdb;
6224 
6225 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6226 
6227 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6228 		rtd = (cdb->byte2 & SMS_RTD) ? 1 : 0;
6229 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6230 		param_len = scsi_2btoul(cdb->length);
6231 		header_size = sizeof(struct scsi_mode_header_10);
6232 		break;
6233 	}
6234 	default:
6235 		ctl_set_invalid_opcode(ctsio);
6236 		ctl_done((union ctl_io *)ctsio);
6237 		return (CTL_RETVAL_COMPLETE);
6238 	}
6239 
6240 	if (rtd) {
6241 		if (param_len != 0) {
6242 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 0,
6243 			    /*command*/ 1, /*field*/ 0,
6244 			    /*bit_valid*/ 0, /*bit*/ 0);
6245 			ctl_done((union ctl_io *)ctsio);
6246 			return (CTL_RETVAL_COMPLETE);
6247 		}
6248 
6249 		/* Revert to defaults. */
6250 		ctl_init_page_index(lun);
6251 		mtx_lock(&lun->lun_lock);
6252 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
6253 		mtx_unlock(&lun->lun_lock);
6254 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6255 			ctl_isc_announce_mode(lun, -1,
6256 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
6257 			    lun->mode_pages.index[i].subpage);
6258 		}
6259 		ctl_set_success(ctsio);
6260 		ctl_done((union ctl_io *)ctsio);
6261 		return (CTL_RETVAL_COMPLETE);
6262 	}
6263 
6264 	/*
6265 	 * From SPC-3:
6266 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6267 	 * shall be empty. This condition shall not be considered as an error."
6268 	 */
6269 	if (param_len == 0) {
6270 		ctl_set_success(ctsio);
6271 		ctl_done((union ctl_io *)ctsio);
6272 		return (CTL_RETVAL_COMPLETE);
6273 	}
6274 
6275 	/*
6276 	 * Since we'll hit this the first time through, prior to
6277 	 * allocation, we don't need to free a data buffer here.
6278 	 */
6279 	if (param_len < header_size) {
6280 		ctl_set_param_len_error(ctsio);
6281 		ctl_done((union ctl_io *)ctsio);
6282 		return (CTL_RETVAL_COMPLETE);
6283 	}
6284 
6285 	/*
6286 	 * Allocate the data buffer and grab the user's data.  In theory,
6287 	 * we shouldn't have to sanity check the parameter list length here
6288 	 * because the maximum size is 64K.  We should be able to malloc
6289 	 * that much without too many problems.
6290 	 */
6291 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6292 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6293 		ctsio->kern_data_len = param_len;
6294 		ctsio->kern_total_len = param_len;
6295 		ctsio->kern_rel_offset = 0;
6296 		ctsio->kern_sg_entries = 0;
6297 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6298 		ctsio->be_move_done = ctl_config_move_done;
6299 		ctl_datamove((union ctl_io *)ctsio);
6300 
6301 		return (CTL_RETVAL_COMPLETE);
6302 	}
6303 
6304 	switch (ctsio->cdb[0]) {
6305 	case MODE_SELECT_6: {
6306 		struct scsi_mode_header_6 *mh6;
6307 
6308 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6309 		bd_len = mh6->blk_desc_len;
6310 		break;
6311 	}
6312 	case MODE_SELECT_10: {
6313 		struct scsi_mode_header_10 *mh10;
6314 
6315 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6316 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6317 		break;
6318 	}
6319 	default:
6320 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6321 	}
6322 
6323 	if (param_len < (header_size + bd_len)) {
6324 		free(ctsio->kern_data_ptr, M_CTL);
6325 		ctl_set_param_len_error(ctsio);
6326 		ctl_done((union ctl_io *)ctsio);
6327 		return (CTL_RETVAL_COMPLETE);
6328 	}
6329 
6330 	/*
6331 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6332 	 * ctl_config_write_done(), it'll get passed back to
6333 	 * ctl_do_mode_select() for further processing, or completion if
6334 	 * we're all done.
6335 	 */
6336 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6337 	ctsio->io_cont = ctl_do_mode_select;
6338 
6339 	modepage_info = (union ctl_modepage_info *)
6340 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6341 	memset(modepage_info, 0, sizeof(*modepage_info));
6342 	modepage_info->header.len_left = param_len - header_size - bd_len;
6343 	modepage_info->header.len_used = header_size + bd_len;
6344 
6345 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6346 }
6347 
6348 int
6349 ctl_mode_sense(struct ctl_scsiio *ctsio)
6350 {
6351 	struct ctl_lun *lun = CTL_LUN(ctsio);
6352 	int pc, page_code, dbd, llba, subpage;
6353 	int alloc_len, page_len, header_len, total_len;
6354 	struct scsi_mode_block_descr *block_desc;
6355 	struct ctl_page_index *page_index;
6356 
6357 	dbd = 0;
6358 	llba = 0;
6359 	block_desc = NULL;
6360 
6361 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6362 
6363 	switch (ctsio->cdb[0]) {
6364 	case MODE_SENSE_6: {
6365 		struct scsi_mode_sense_6 *cdb;
6366 
6367 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6368 
6369 		header_len = sizeof(struct scsi_mode_hdr_6);
6370 		if (cdb->byte2 & SMS_DBD)
6371 			dbd = 1;
6372 		else
6373 			header_len += sizeof(struct scsi_mode_block_descr);
6374 
6375 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6376 		page_code = cdb->page & SMS_PAGE_CODE;
6377 		subpage = cdb->subpage;
6378 		alloc_len = cdb->length;
6379 		break;
6380 	}
6381 	case MODE_SENSE_10: {
6382 		struct scsi_mode_sense_10 *cdb;
6383 
6384 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6385 
6386 		header_len = sizeof(struct scsi_mode_hdr_10);
6387 
6388 		if (cdb->byte2 & SMS_DBD)
6389 			dbd = 1;
6390 		else
6391 			header_len += sizeof(struct scsi_mode_block_descr);
6392 		if (cdb->byte2 & SMS10_LLBAA)
6393 			llba = 1;
6394 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6395 		page_code = cdb->page & SMS_PAGE_CODE;
6396 		subpage = cdb->subpage;
6397 		alloc_len = scsi_2btoul(cdb->length);
6398 		break;
6399 	}
6400 	default:
6401 		ctl_set_invalid_opcode(ctsio);
6402 		ctl_done((union ctl_io *)ctsio);
6403 		return (CTL_RETVAL_COMPLETE);
6404 		break; /* NOTREACHED */
6405 	}
6406 
6407 	/*
6408 	 * We have to make a first pass through to calculate the size of
6409 	 * the pages that match the user's query.  Then we allocate enough
6410 	 * memory to hold it, and actually copy the data into the buffer.
6411 	 */
6412 	switch (page_code) {
6413 	case SMS_ALL_PAGES_PAGE: {
6414 		u_int i;
6415 
6416 		page_len = 0;
6417 
6418 		/*
6419 		 * At the moment, values other than 0 and 0xff here are
6420 		 * reserved according to SPC-3.
6421 		 */
6422 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6423 		 && (subpage != SMS_SUBPAGE_ALL)) {
6424 			ctl_set_invalid_field(ctsio,
6425 					      /*sks_valid*/ 1,
6426 					      /*command*/ 1,
6427 					      /*field*/ 3,
6428 					      /*bit_valid*/ 0,
6429 					      /*bit*/ 0);
6430 			ctl_done((union ctl_io *)ctsio);
6431 			return (CTL_RETVAL_COMPLETE);
6432 		}
6433 
6434 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6435 			page_index = &lun->mode_pages.index[i];
6436 
6437 			/* Make sure the page is supported for this dev type */
6438 			if (lun->be_lun->lun_type == T_DIRECT &&
6439 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6440 				continue;
6441 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6442 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6443 				continue;
6444 			if (lun->be_lun->lun_type == T_CDROM &&
6445 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6446 				continue;
6447 
6448 			/*
6449 			 * We don't use this subpage if the user didn't
6450 			 * request all subpages.
6451 			 */
6452 			if ((page_index->subpage != 0)
6453 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6454 				continue;
6455 
6456 #if 0
6457 			printf("found page %#x len %d\n",
6458 			       page_index->page_code & SMPH_PC_MASK,
6459 			       page_index->page_len);
6460 #endif
6461 			page_len += page_index->page_len;
6462 		}
6463 		break;
6464 	}
6465 	default: {
6466 		u_int i;
6467 
6468 		page_len = 0;
6469 
6470 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6471 			page_index = &lun->mode_pages.index[i];
6472 
6473 			/* Make sure the page is supported for this dev type */
6474 			if (lun->be_lun->lun_type == T_DIRECT &&
6475 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6476 				continue;
6477 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6478 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6479 				continue;
6480 			if (lun->be_lun->lun_type == T_CDROM &&
6481 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6482 				continue;
6483 
6484 			/* Look for the right page code */
6485 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6486 				continue;
6487 
6488 			/* Look for the right subpage or the subpage wildcard*/
6489 			if ((page_index->subpage != subpage)
6490 			 && (subpage != SMS_SUBPAGE_ALL))
6491 				continue;
6492 
6493 #if 0
6494 			printf("found page %#x len %d\n",
6495 			       page_index->page_code & SMPH_PC_MASK,
6496 			       page_index->page_len);
6497 #endif
6498 
6499 			page_len += page_index->page_len;
6500 		}
6501 
6502 		if (page_len == 0) {
6503 			ctl_set_invalid_field(ctsio,
6504 					      /*sks_valid*/ 1,
6505 					      /*command*/ 1,
6506 					      /*field*/ 2,
6507 					      /*bit_valid*/ 1,
6508 					      /*bit*/ 5);
6509 			ctl_done((union ctl_io *)ctsio);
6510 			return (CTL_RETVAL_COMPLETE);
6511 		}
6512 		break;
6513 	}
6514 	}
6515 
6516 	total_len = header_len + page_len;
6517 #if 0
6518 	printf("header_len = %d, page_len = %d, total_len = %d\n",
6519 	       header_len, page_len, total_len);
6520 #endif
6521 
6522 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6523 	ctsio->kern_sg_entries = 0;
6524 	ctsio->kern_rel_offset = 0;
6525 	ctsio->kern_data_len = min(total_len, alloc_len);
6526 	ctsio->kern_total_len = ctsio->kern_data_len;
6527 
6528 	switch (ctsio->cdb[0]) {
6529 	case MODE_SENSE_6: {
6530 		struct scsi_mode_hdr_6 *header;
6531 
6532 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6533 
6534 		header->datalen = MIN(total_len - 1, 254);
6535 		if (lun->be_lun->lun_type == T_DIRECT) {
6536 			header->dev_specific = 0x10; /* DPOFUA */
6537 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6538 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6539 				header->dev_specific |= 0x80; /* WP */
6540 		}
6541 		if (dbd)
6542 			header->block_descr_len = 0;
6543 		else
6544 			header->block_descr_len =
6545 				sizeof(struct scsi_mode_block_descr);
6546 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6547 		break;
6548 	}
6549 	case MODE_SENSE_10: {
6550 		struct scsi_mode_hdr_10 *header;
6551 		int datalen;
6552 
6553 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6554 
6555 		datalen = MIN(total_len - 2, 65533);
6556 		scsi_ulto2b(datalen, header->datalen);
6557 		if (lun->be_lun->lun_type == T_DIRECT) {
6558 			header->dev_specific = 0x10; /* DPOFUA */
6559 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6560 			    (lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0)
6561 				header->dev_specific |= 0x80; /* WP */
6562 		}
6563 		if (dbd)
6564 			scsi_ulto2b(0, header->block_descr_len);
6565 		else
6566 			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6567 				    header->block_descr_len);
6568 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6569 		break;
6570 	}
6571 	default:
6572 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6573 	}
6574 
6575 	/*
6576 	 * If we've got a disk, use its blocksize in the block
6577 	 * descriptor.  Otherwise, just set it to 0.
6578 	 */
6579 	if (dbd == 0) {
6580 		if (lun->be_lun->lun_type == T_DIRECT)
6581 			scsi_ulto3b(lun->be_lun->blocksize,
6582 				    block_desc->block_len);
6583 		else
6584 			scsi_ulto3b(0, block_desc->block_len);
6585 	}
6586 
6587 	switch (page_code) {
6588 	case SMS_ALL_PAGES_PAGE: {
6589 		int i, data_used;
6590 
6591 		data_used = header_len;
6592 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6593 			struct ctl_page_index *page_index;
6594 
6595 			page_index = &lun->mode_pages.index[i];
6596 			if (lun->be_lun->lun_type == T_DIRECT &&
6597 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6598 				continue;
6599 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6600 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6601 				continue;
6602 			if (lun->be_lun->lun_type == T_CDROM &&
6603 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6604 				continue;
6605 
6606 			/*
6607 			 * We don't use this subpage if the user didn't
6608 			 * request all subpages.  We already checked (above)
6609 			 * to make sure the user only specified a subpage
6610 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6611 			 */
6612 			if ((page_index->subpage != 0)
6613 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6614 				continue;
6615 
6616 			/*
6617 			 * Call the handler, if it exists, to update the
6618 			 * page to the latest values.
6619 			 */
6620 			if (page_index->sense_handler != NULL)
6621 				page_index->sense_handler(ctsio, page_index,pc);
6622 
6623 			memcpy(ctsio->kern_data_ptr + data_used,
6624 			       page_index->page_data +
6625 			       (page_index->page_len * pc),
6626 			       page_index->page_len);
6627 			data_used += page_index->page_len;
6628 		}
6629 		break;
6630 	}
6631 	default: {
6632 		int i, data_used;
6633 
6634 		data_used = header_len;
6635 
6636 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6637 			struct ctl_page_index *page_index;
6638 
6639 			page_index = &lun->mode_pages.index[i];
6640 
6641 			/* Look for the right page code */
6642 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6643 				continue;
6644 
6645 			/* Look for the right subpage or the subpage wildcard*/
6646 			if ((page_index->subpage != subpage)
6647 			 && (subpage != SMS_SUBPAGE_ALL))
6648 				continue;
6649 
6650 			/* Make sure the page is supported for this dev type */
6651 			if (lun->be_lun->lun_type == T_DIRECT &&
6652 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6653 				continue;
6654 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6655 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6656 				continue;
6657 			if (lun->be_lun->lun_type == T_CDROM &&
6658 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6659 				continue;
6660 
6661 			/*
6662 			 * Call the handler, if it exists, to update the
6663 			 * page to the latest values.
6664 			 */
6665 			if (page_index->sense_handler != NULL)
6666 				page_index->sense_handler(ctsio, page_index,pc);
6667 
6668 			memcpy(ctsio->kern_data_ptr + data_used,
6669 			       page_index->page_data +
6670 			       (page_index->page_len * pc),
6671 			       page_index->page_len);
6672 			data_used += page_index->page_len;
6673 		}
6674 		break;
6675 	}
6676 	}
6677 
6678 	ctl_set_success(ctsio);
6679 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6680 	ctsio->be_move_done = ctl_config_move_done;
6681 	ctl_datamove((union ctl_io *)ctsio);
6682 	return (CTL_RETVAL_COMPLETE);
6683 }
6684 
6685 int
6686 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6687 			       struct ctl_page_index *page_index,
6688 			       int pc)
6689 {
6690 	struct ctl_lun *lun = CTL_LUN(ctsio);
6691 	struct scsi_log_param_header *phdr;
6692 	uint8_t *data;
6693 	uint64_t val;
6694 
6695 	data = page_index->page_data;
6696 
6697 	if (lun->backend->lun_attr != NULL &&
6698 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6699 	     != UINT64_MAX) {
6700 		phdr = (struct scsi_log_param_header *)data;
6701 		scsi_ulto2b(0x0001, 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] = 0x02; /* per-pool */
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, "blocksused"))
6712 	     != UINT64_MAX) {
6713 		phdr = (struct scsi_log_param_header *)data;
6714 		scsi_ulto2b(0x0002, 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] = 0x01; /* per-LUN */
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, "poolblocksavail"))
6725 	     != UINT64_MAX) {
6726 		phdr = (struct scsi_log_param_header *)data;
6727 		scsi_ulto2b(0x00f1, 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 	if (lun->backend->lun_attr != NULL &&
6737 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6738 	     != UINT64_MAX) {
6739 		phdr = (struct scsi_log_param_header *)data;
6740 		scsi_ulto2b(0x00f2, phdr->param_code);
6741 		phdr->param_control = SLP_LBIN | SLP_LP;
6742 		phdr->param_len = 8;
6743 		data = (uint8_t *)(phdr + 1);
6744 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6745 		data[4] = 0x02; /* per-pool */
6746 		data += phdr->param_len;
6747 	}
6748 
6749 	page_index->page_len = data - page_index->page_data;
6750 	return (0);
6751 }
6752 
6753 int
6754 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6755 			       struct ctl_page_index *page_index,
6756 			       int pc)
6757 {
6758 	struct ctl_lun *lun = CTL_LUN(ctsio);
6759 	struct stat_page *data;
6760 	struct bintime *t;
6761 
6762 	data = (struct stat_page *)page_index->page_data;
6763 
6764 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6765 	data->sap.hdr.param_control = SLP_LBIN;
6766 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6767 	    sizeof(struct scsi_log_param_header);
6768 	scsi_u64to8b(lun->stats.operations[CTL_STATS_READ],
6769 	    data->sap.read_num);
6770 	scsi_u64to8b(lun->stats.operations[CTL_STATS_WRITE],
6771 	    data->sap.write_num);
6772 	if (lun->be_lun->blocksize > 0) {
6773 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_WRITE] /
6774 		    lun->be_lun->blocksize, data->sap.recvieved_lba);
6775 		scsi_u64to8b(lun->stats.bytes[CTL_STATS_READ] /
6776 		    lun->be_lun->blocksize, data->sap.transmitted_lba);
6777 	}
6778 	t = &lun->stats.time[CTL_STATS_READ];
6779 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6780 	    data->sap.read_int);
6781 	t = &lun->stats.time[CTL_STATS_WRITE];
6782 	scsi_u64to8b((uint64_t)t->sec * 1000 + t->frac / (UINT64_MAX / 1000),
6783 	    data->sap.write_int);
6784 	scsi_u64to8b(0, data->sap.weighted_num);
6785 	scsi_u64to8b(0, data->sap.weighted_int);
6786 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6787 	data->it.hdr.param_control = SLP_LBIN;
6788 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6789 	    sizeof(struct scsi_log_param_header);
6790 #ifdef CTL_TIME_IO
6791 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6792 #endif
6793 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6794 	data->it.hdr.param_control = SLP_LBIN;
6795 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6796 	    sizeof(struct scsi_log_param_header);
6797 	scsi_ulto4b(3, data->ti.exponent);
6798 	scsi_ulto4b(1, data->ti.integer);
6799 	return (0);
6800 }
6801 
6802 int
6803 ctl_ie_log_sense_handler(struct ctl_scsiio *ctsio,
6804 			       struct ctl_page_index *page_index,
6805 			       int pc)
6806 {
6807 	struct ctl_lun *lun = CTL_LUN(ctsio);
6808 	struct scsi_log_informational_exceptions *data;
6809 
6810 	data = (struct scsi_log_informational_exceptions *)page_index->page_data;
6811 
6812 	scsi_ulto2b(SLP_IE_GEN, data->hdr.param_code);
6813 	data->hdr.param_control = SLP_LBIN;
6814 	data->hdr.param_len = sizeof(struct scsi_log_informational_exceptions) -
6815 	    sizeof(struct scsi_log_param_header);
6816 	data->ie_asc = lun->ie_asc;
6817 	data->ie_ascq = lun->ie_ascq;
6818 	data->temperature = 0xff;
6819 	return (0);
6820 }
6821 
6822 int
6823 ctl_log_sense(struct ctl_scsiio *ctsio)
6824 {
6825 	struct ctl_lun *lun = CTL_LUN(ctsio);
6826 	int i, pc, page_code, subpage;
6827 	int alloc_len, total_len;
6828 	struct ctl_page_index *page_index;
6829 	struct scsi_log_sense *cdb;
6830 	struct scsi_log_header *header;
6831 
6832 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6833 
6834 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6835 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6836 	page_code = cdb->page & SLS_PAGE_CODE;
6837 	subpage = cdb->subpage;
6838 	alloc_len = scsi_2btoul(cdb->length);
6839 
6840 	page_index = NULL;
6841 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6842 		page_index = &lun->log_pages.index[i];
6843 
6844 		/* Look for the right page code */
6845 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6846 			continue;
6847 
6848 		/* Look for the right subpage or the subpage wildcard*/
6849 		if (page_index->subpage != subpage)
6850 			continue;
6851 
6852 		break;
6853 	}
6854 	if (i >= CTL_NUM_LOG_PAGES) {
6855 		ctl_set_invalid_field(ctsio,
6856 				      /*sks_valid*/ 1,
6857 				      /*command*/ 1,
6858 				      /*field*/ 2,
6859 				      /*bit_valid*/ 0,
6860 				      /*bit*/ 0);
6861 		ctl_done((union ctl_io *)ctsio);
6862 		return (CTL_RETVAL_COMPLETE);
6863 	}
6864 
6865 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6866 
6867 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6868 	ctsio->kern_sg_entries = 0;
6869 	ctsio->kern_rel_offset = 0;
6870 	ctsio->kern_data_len = min(total_len, alloc_len);
6871 	ctsio->kern_total_len = ctsio->kern_data_len;
6872 
6873 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6874 	header->page = page_index->page_code;
6875 	if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING)
6876 		header->page |= SL_DS;
6877 	if (page_index->subpage) {
6878 		header->page |= SL_SPF;
6879 		header->subpage = page_index->subpage;
6880 	}
6881 	scsi_ulto2b(page_index->page_len, header->datalen);
6882 
6883 	/*
6884 	 * Call the handler, if it exists, to update the
6885 	 * page to the latest values.
6886 	 */
6887 	if (page_index->sense_handler != NULL)
6888 		page_index->sense_handler(ctsio, page_index, pc);
6889 
6890 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6891 
6892 	ctl_set_success(ctsio);
6893 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6894 	ctsio->be_move_done = ctl_config_move_done;
6895 	ctl_datamove((union ctl_io *)ctsio);
6896 	return (CTL_RETVAL_COMPLETE);
6897 }
6898 
6899 int
6900 ctl_read_capacity(struct ctl_scsiio *ctsio)
6901 {
6902 	struct ctl_lun *lun = CTL_LUN(ctsio);
6903 	struct scsi_read_capacity *cdb;
6904 	struct scsi_read_capacity_data *data;
6905 	uint32_t lba;
6906 
6907 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6908 
6909 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6910 
6911 	lba = scsi_4btoul(cdb->addr);
6912 	if (((cdb->pmi & SRC_PMI) == 0)
6913 	 && (lba != 0)) {
6914 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6915 				      /*sks_valid*/ 1,
6916 				      /*command*/ 1,
6917 				      /*field*/ 2,
6918 				      /*bit_valid*/ 0,
6919 				      /*bit*/ 0);
6920 		ctl_done((union ctl_io *)ctsio);
6921 		return (CTL_RETVAL_COMPLETE);
6922 	}
6923 
6924 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6925 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6926 	ctsio->kern_data_len = sizeof(*data);
6927 	ctsio->kern_total_len = sizeof(*data);
6928 	ctsio->kern_rel_offset = 0;
6929 	ctsio->kern_sg_entries = 0;
6930 
6931 	/*
6932 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6933 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6934 	 * serivce action set.
6935 	 */
6936 	if (lun->be_lun->maxlba > 0xfffffffe)
6937 		scsi_ulto4b(0xffffffff, data->addr);
6938 	else
6939 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6940 
6941 	/*
6942 	 * XXX KDM this may not be 512 bytes...
6943 	 */
6944 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6945 
6946 	ctl_set_success(ctsio);
6947 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6948 	ctsio->be_move_done = ctl_config_move_done;
6949 	ctl_datamove((union ctl_io *)ctsio);
6950 	return (CTL_RETVAL_COMPLETE);
6951 }
6952 
6953 int
6954 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6955 {
6956 	struct ctl_lun *lun = CTL_LUN(ctsio);
6957 	struct scsi_read_capacity_16 *cdb;
6958 	struct scsi_read_capacity_data_long *data;
6959 	uint64_t lba;
6960 	uint32_t alloc_len;
6961 
6962 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6963 
6964 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6965 
6966 	alloc_len = scsi_4btoul(cdb->alloc_len);
6967 	lba = scsi_8btou64(cdb->addr);
6968 
6969 	if ((cdb->reladr & SRC16_PMI)
6970 	 && (lba != 0)) {
6971 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6972 				      /*sks_valid*/ 1,
6973 				      /*command*/ 1,
6974 				      /*field*/ 2,
6975 				      /*bit_valid*/ 0,
6976 				      /*bit*/ 0);
6977 		ctl_done((union ctl_io *)ctsio);
6978 		return (CTL_RETVAL_COMPLETE);
6979 	}
6980 
6981 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6982 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6983 	ctsio->kern_rel_offset = 0;
6984 	ctsio->kern_sg_entries = 0;
6985 	ctsio->kern_data_len = min(sizeof(*data), alloc_len);
6986 	ctsio->kern_total_len = ctsio->kern_data_len;
6987 
6988 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6989 	/* XXX KDM this may not be 512 bytes... */
6990 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6991 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6992 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6993 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6994 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6995 
6996 	ctl_set_success(ctsio);
6997 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6998 	ctsio->be_move_done = ctl_config_move_done;
6999 	ctl_datamove((union ctl_io *)ctsio);
7000 	return (CTL_RETVAL_COMPLETE);
7001 }
7002 
7003 int
7004 ctl_get_lba_status(struct ctl_scsiio *ctsio)
7005 {
7006 	struct ctl_lun *lun = CTL_LUN(ctsio);
7007 	struct scsi_get_lba_status *cdb;
7008 	struct scsi_get_lba_status_data *data;
7009 	struct ctl_lba_len_flags *lbalen;
7010 	uint64_t lba;
7011 	uint32_t alloc_len, total_len;
7012 	int retval;
7013 
7014 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
7015 
7016 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
7017 	lba = scsi_8btou64(cdb->addr);
7018 	alloc_len = scsi_4btoul(cdb->alloc_len);
7019 
7020 	if (lba > lun->be_lun->maxlba) {
7021 		ctl_set_lba_out_of_range(ctsio, lba);
7022 		ctl_done((union ctl_io *)ctsio);
7023 		return (CTL_RETVAL_COMPLETE);
7024 	}
7025 
7026 	total_len = sizeof(*data) + sizeof(data->descr[0]);
7027 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7028 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
7029 	ctsio->kern_rel_offset = 0;
7030 	ctsio->kern_sg_entries = 0;
7031 	ctsio->kern_data_len = min(total_len, alloc_len);
7032 	ctsio->kern_total_len = ctsio->kern_data_len;
7033 
7034 	/* Fill dummy data in case backend can't tell anything. */
7035 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
7036 	scsi_u64to8b(lba, data->descr[0].addr);
7037 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
7038 	    data->descr[0].length);
7039 	data->descr[0].status = 0; /* Mapped or unknown. */
7040 
7041 	ctl_set_success(ctsio);
7042 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7043 	ctsio->be_move_done = ctl_config_move_done;
7044 
7045 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
7046 	lbalen->lba = lba;
7047 	lbalen->len = total_len;
7048 	lbalen->flags = 0;
7049 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7050 	return (CTL_RETVAL_COMPLETE);
7051 }
7052 
7053 int
7054 ctl_read_defect(struct ctl_scsiio *ctsio)
7055 {
7056 	struct scsi_read_defect_data_10 *ccb10;
7057 	struct scsi_read_defect_data_12 *ccb12;
7058 	struct scsi_read_defect_data_hdr_10 *data10;
7059 	struct scsi_read_defect_data_hdr_12 *data12;
7060 	uint32_t alloc_len, data_len;
7061 	uint8_t format;
7062 
7063 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7064 
7065 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7066 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7067 		format = ccb10->format;
7068 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7069 		data_len = sizeof(*data10);
7070 	} else {
7071 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7072 		format = ccb12->format;
7073 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7074 		data_len = sizeof(*data12);
7075 	}
7076 	if (alloc_len == 0) {
7077 		ctl_set_success(ctsio);
7078 		ctl_done((union ctl_io *)ctsio);
7079 		return (CTL_RETVAL_COMPLETE);
7080 	}
7081 
7082 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7083 	ctsio->kern_rel_offset = 0;
7084 	ctsio->kern_sg_entries = 0;
7085 	ctsio->kern_data_len = min(data_len, alloc_len);
7086 	ctsio->kern_total_len = ctsio->kern_data_len;
7087 
7088 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7089 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7090 		    ctsio->kern_data_ptr;
7091 		data10->format = format;
7092 		scsi_ulto2b(0, data10->length);
7093 	} else {
7094 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7095 		    ctsio->kern_data_ptr;
7096 		data12->format = format;
7097 		scsi_ulto2b(0, data12->generation);
7098 		scsi_ulto4b(0, data12->length);
7099 	}
7100 
7101 	ctl_set_success(ctsio);
7102 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7103 	ctsio->be_move_done = ctl_config_move_done;
7104 	ctl_datamove((union ctl_io *)ctsio);
7105 	return (CTL_RETVAL_COMPLETE);
7106 }
7107 
7108 int
7109 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7110 {
7111 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7112 	struct ctl_lun *lun = CTL_LUN(ctsio);
7113 	struct scsi_maintenance_in *cdb;
7114 	int retval;
7115 	int alloc_len, ext, total_len = 0, g, pc, pg, ts, os;
7116 	int num_ha_groups, num_target_ports, shared_group;
7117 	struct ctl_port *port;
7118 	struct scsi_target_group_data *rtg_ptr;
7119 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7120 	struct scsi_target_port_group_descriptor *tpg_desc;
7121 
7122 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7123 
7124 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7125 	retval = CTL_RETVAL_COMPLETE;
7126 
7127 	switch (cdb->byte2 & STG_PDF_MASK) {
7128 	case STG_PDF_LENGTH:
7129 		ext = 0;
7130 		break;
7131 	case STG_PDF_EXTENDED:
7132 		ext = 1;
7133 		break;
7134 	default:
7135 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7136 				      /*sks_valid*/ 1,
7137 				      /*command*/ 1,
7138 				      /*field*/ 2,
7139 				      /*bit_valid*/ 1,
7140 				      /*bit*/ 5);
7141 		ctl_done((union ctl_io *)ctsio);
7142 		return(retval);
7143 	}
7144 
7145 	num_target_ports = 0;
7146 	shared_group = (softc->is_single != 0);
7147 	mtx_lock(&softc->ctl_lock);
7148 	STAILQ_FOREACH(port, &softc->port_list, links) {
7149 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7150 			continue;
7151 		if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7152 			continue;
7153 		num_target_ports++;
7154 		if (port->status & CTL_PORT_STATUS_HA_SHARED)
7155 			shared_group = 1;
7156 	}
7157 	mtx_unlock(&softc->ctl_lock);
7158 	num_ha_groups = (softc->is_single) ? 0 : NUM_HA_SHELVES;
7159 
7160 	if (ext)
7161 		total_len = sizeof(struct scsi_target_group_data_extended);
7162 	else
7163 		total_len = sizeof(struct scsi_target_group_data);
7164 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7165 		(shared_group + num_ha_groups) +
7166 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7167 
7168 	alloc_len = scsi_4btoul(cdb->length);
7169 
7170 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7171 	ctsio->kern_sg_entries = 0;
7172 	ctsio->kern_rel_offset = 0;
7173 	ctsio->kern_data_len = min(total_len, alloc_len);
7174 	ctsio->kern_total_len = ctsio->kern_data_len;
7175 
7176 	if (ext) {
7177 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7178 		    ctsio->kern_data_ptr;
7179 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7180 		rtg_ext_ptr->format_type = 0x10;
7181 		rtg_ext_ptr->implicit_transition_time = 0;
7182 		tpg_desc = &rtg_ext_ptr->groups[0];
7183 	} else {
7184 		rtg_ptr = (struct scsi_target_group_data *)
7185 		    ctsio->kern_data_ptr;
7186 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7187 		tpg_desc = &rtg_ptr->groups[0];
7188 	}
7189 
7190 	mtx_lock(&softc->ctl_lock);
7191 	pg = softc->port_min / softc->port_cnt;
7192 	if (lun->flags & (CTL_LUN_PRIMARY_SC | CTL_LUN_PEER_SC_PRIMARY)) {
7193 		/* Some shelf is known to be primary. */
7194 		if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7195 			os = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7196 		else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7197 			os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7198 		else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7199 			os = TPG_ASYMMETRIC_ACCESS_STANDBY;
7200 		else
7201 			os = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7202 		if (lun->flags & CTL_LUN_PRIMARY_SC) {
7203 			ts = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7204 		} else {
7205 			ts = os;
7206 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7207 		}
7208 	} else {
7209 		/* No known primary shelf. */
7210 		if (softc->ha_link == CTL_HA_LINK_OFFLINE) {
7211 			ts = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7212 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7213 		} else if (softc->ha_link == CTL_HA_LINK_UNKNOWN) {
7214 			ts = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7215 			os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7216 		} else {
7217 			ts = os = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7218 		}
7219 	}
7220 	if (shared_group) {
7221 		tpg_desc->pref_state = ts;
7222 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7223 		    TPG_U_SUP | TPG_T_SUP;
7224 		scsi_ulto2b(1, tpg_desc->target_port_group);
7225 		tpg_desc->status = TPG_IMPLICIT;
7226 		pc = 0;
7227 		STAILQ_FOREACH(port, &softc->port_list, links) {
7228 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7229 				continue;
7230 			if (!softc->is_single &&
7231 			    (port->status & CTL_PORT_STATUS_HA_SHARED) == 0)
7232 				continue;
7233 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7234 				continue;
7235 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7236 			    relative_target_port_identifier);
7237 			pc++;
7238 		}
7239 		tpg_desc->target_port_count = pc;
7240 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7241 		    &tpg_desc->descriptors[pc];
7242 	}
7243 	for (g = 0; g < num_ha_groups; g++) {
7244 		tpg_desc->pref_state = (g == pg) ? ts : os;
7245 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7246 		    TPG_U_SUP | TPG_T_SUP;
7247 		scsi_ulto2b(2 + g, tpg_desc->target_port_group);
7248 		tpg_desc->status = TPG_IMPLICIT;
7249 		pc = 0;
7250 		STAILQ_FOREACH(port, &softc->port_list, links) {
7251 			if (port->targ_port < g * softc->port_cnt ||
7252 			    port->targ_port >= (g + 1) * softc->port_cnt)
7253 				continue;
7254 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7255 				continue;
7256 			if (port->status & CTL_PORT_STATUS_HA_SHARED)
7257 				continue;
7258 			if (ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
7259 				continue;
7260 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7261 			    relative_target_port_identifier);
7262 			pc++;
7263 		}
7264 		tpg_desc->target_port_count = pc;
7265 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7266 		    &tpg_desc->descriptors[pc];
7267 	}
7268 	mtx_unlock(&softc->ctl_lock);
7269 
7270 	ctl_set_success(ctsio);
7271 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7272 	ctsio->be_move_done = ctl_config_move_done;
7273 	ctl_datamove((union ctl_io *)ctsio);
7274 	return(retval);
7275 }
7276 
7277 int
7278 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7279 {
7280 	struct ctl_lun *lun = CTL_LUN(ctsio);
7281 	struct scsi_report_supported_opcodes *cdb;
7282 	const struct ctl_cmd_entry *entry, *sentry;
7283 	struct scsi_report_supported_opcodes_all *all;
7284 	struct scsi_report_supported_opcodes_descr *descr;
7285 	struct scsi_report_supported_opcodes_one *one;
7286 	int retval;
7287 	int alloc_len, total_len;
7288 	int opcode, service_action, i, j, num;
7289 
7290 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7291 
7292 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7293 	retval = CTL_RETVAL_COMPLETE;
7294 
7295 	opcode = cdb->requested_opcode;
7296 	service_action = scsi_2btoul(cdb->requested_service_action);
7297 	switch (cdb->options & RSO_OPTIONS_MASK) {
7298 	case RSO_OPTIONS_ALL:
7299 		num = 0;
7300 		for (i = 0; i < 256; i++) {
7301 			entry = &ctl_cmd_table[i];
7302 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7303 				for (j = 0; j < 32; j++) {
7304 					sentry = &((const struct ctl_cmd_entry *)
7305 					    entry->execute)[j];
7306 					if (ctl_cmd_applicable(
7307 					    lun->be_lun->lun_type, sentry))
7308 						num++;
7309 				}
7310 			} else {
7311 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7312 				    entry))
7313 					num++;
7314 			}
7315 		}
7316 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7317 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7318 		break;
7319 	case RSO_OPTIONS_OC:
7320 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7321 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7322 					      /*sks_valid*/ 1,
7323 					      /*command*/ 1,
7324 					      /*field*/ 2,
7325 					      /*bit_valid*/ 1,
7326 					      /*bit*/ 2);
7327 			ctl_done((union ctl_io *)ctsio);
7328 			return (CTL_RETVAL_COMPLETE);
7329 		}
7330 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7331 		break;
7332 	case RSO_OPTIONS_OC_SA:
7333 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7334 		    service_action >= 32) {
7335 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7336 					      /*sks_valid*/ 1,
7337 					      /*command*/ 1,
7338 					      /*field*/ 2,
7339 					      /*bit_valid*/ 1,
7340 					      /*bit*/ 2);
7341 			ctl_done((union ctl_io *)ctsio);
7342 			return (CTL_RETVAL_COMPLETE);
7343 		}
7344 		/* FALLTHROUGH */
7345 	case RSO_OPTIONS_OC_ASA:
7346 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7347 		break;
7348 	default:
7349 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7350 				      /*sks_valid*/ 1,
7351 				      /*command*/ 1,
7352 				      /*field*/ 2,
7353 				      /*bit_valid*/ 1,
7354 				      /*bit*/ 2);
7355 		ctl_done((union ctl_io *)ctsio);
7356 		return (CTL_RETVAL_COMPLETE);
7357 	}
7358 
7359 	alloc_len = scsi_4btoul(cdb->length);
7360 
7361 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7362 	ctsio->kern_sg_entries = 0;
7363 	ctsio->kern_rel_offset = 0;
7364 	ctsio->kern_data_len = min(total_len, alloc_len);
7365 	ctsio->kern_total_len = ctsio->kern_data_len;
7366 
7367 	switch (cdb->options & RSO_OPTIONS_MASK) {
7368 	case RSO_OPTIONS_ALL:
7369 		all = (struct scsi_report_supported_opcodes_all *)
7370 		    ctsio->kern_data_ptr;
7371 		num = 0;
7372 		for (i = 0; i < 256; i++) {
7373 			entry = &ctl_cmd_table[i];
7374 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7375 				for (j = 0; j < 32; j++) {
7376 					sentry = &((const struct ctl_cmd_entry *)
7377 					    entry->execute)[j];
7378 					if (!ctl_cmd_applicable(
7379 					    lun->be_lun->lun_type, sentry))
7380 						continue;
7381 					descr = &all->descr[num++];
7382 					descr->opcode = i;
7383 					scsi_ulto2b(j, descr->service_action);
7384 					descr->flags = RSO_SERVACTV;
7385 					scsi_ulto2b(sentry->length,
7386 					    descr->cdb_length);
7387 				}
7388 			} else {
7389 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7390 				    entry))
7391 					continue;
7392 				descr = &all->descr[num++];
7393 				descr->opcode = i;
7394 				scsi_ulto2b(0, descr->service_action);
7395 				descr->flags = 0;
7396 				scsi_ulto2b(entry->length, descr->cdb_length);
7397 			}
7398 		}
7399 		scsi_ulto4b(
7400 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7401 		    all->length);
7402 		break;
7403 	case RSO_OPTIONS_OC:
7404 		one = (struct scsi_report_supported_opcodes_one *)
7405 		    ctsio->kern_data_ptr;
7406 		entry = &ctl_cmd_table[opcode];
7407 		goto fill_one;
7408 	case RSO_OPTIONS_OC_SA:
7409 		one = (struct scsi_report_supported_opcodes_one *)
7410 		    ctsio->kern_data_ptr;
7411 		entry = &ctl_cmd_table[opcode];
7412 		entry = &((const struct ctl_cmd_entry *)
7413 		    entry->execute)[service_action];
7414 fill_one:
7415 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7416 			one->support = 3;
7417 			scsi_ulto2b(entry->length, one->cdb_length);
7418 			one->cdb_usage[0] = opcode;
7419 			memcpy(&one->cdb_usage[1], entry->usage,
7420 			    entry->length - 1);
7421 		} else
7422 			one->support = 1;
7423 		break;
7424 	case RSO_OPTIONS_OC_ASA:
7425 		one = (struct scsi_report_supported_opcodes_one *)
7426 		    ctsio->kern_data_ptr;
7427 		entry = &ctl_cmd_table[opcode];
7428 		if (entry->flags & CTL_CMD_FLAG_SA5) {
7429 			entry = &((const struct ctl_cmd_entry *)
7430 			    entry->execute)[service_action];
7431 		} else if (service_action != 0) {
7432 			one->support = 1;
7433 			break;
7434 		}
7435 		goto fill_one;
7436 	}
7437 
7438 	ctl_set_success(ctsio);
7439 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7440 	ctsio->be_move_done = ctl_config_move_done;
7441 	ctl_datamove((union ctl_io *)ctsio);
7442 	return(retval);
7443 }
7444 
7445 int
7446 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7447 {
7448 	struct scsi_report_supported_tmf *cdb;
7449 	struct scsi_report_supported_tmf_ext_data *data;
7450 	int retval;
7451 	int alloc_len, total_len;
7452 
7453 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7454 
7455 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7456 
7457 	retval = CTL_RETVAL_COMPLETE;
7458 
7459 	if (cdb->options & RST_REPD)
7460 		total_len = sizeof(struct scsi_report_supported_tmf_ext_data);
7461 	else
7462 		total_len = sizeof(struct scsi_report_supported_tmf_data);
7463 	alloc_len = scsi_4btoul(cdb->length);
7464 
7465 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7466 	ctsio->kern_sg_entries = 0;
7467 	ctsio->kern_rel_offset = 0;
7468 	ctsio->kern_data_len = min(total_len, alloc_len);
7469 	ctsio->kern_total_len = ctsio->kern_data_len;
7470 
7471 	data = (struct scsi_report_supported_tmf_ext_data *)ctsio->kern_data_ptr;
7472 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7473 	    RST_TRS;
7474 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7475 	data->length = total_len - 4;
7476 
7477 	ctl_set_success(ctsio);
7478 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7479 	ctsio->be_move_done = ctl_config_move_done;
7480 	ctl_datamove((union ctl_io *)ctsio);
7481 	return (retval);
7482 }
7483 
7484 int
7485 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7486 {
7487 	struct scsi_report_timestamp *cdb;
7488 	struct scsi_report_timestamp_data *data;
7489 	struct timeval tv;
7490 	int64_t timestamp;
7491 	int retval;
7492 	int alloc_len, total_len;
7493 
7494 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7495 
7496 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7497 
7498 	retval = CTL_RETVAL_COMPLETE;
7499 
7500 	total_len = sizeof(struct scsi_report_timestamp_data);
7501 	alloc_len = scsi_4btoul(cdb->length);
7502 
7503 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7504 	ctsio->kern_sg_entries = 0;
7505 	ctsio->kern_rel_offset = 0;
7506 	ctsio->kern_data_len = min(total_len, alloc_len);
7507 	ctsio->kern_total_len = ctsio->kern_data_len;
7508 
7509 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7510 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7511 	data->origin = RTS_ORIG_OUTSIDE;
7512 	getmicrotime(&tv);
7513 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7514 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7515 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7516 
7517 	ctl_set_success(ctsio);
7518 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7519 	ctsio->be_move_done = ctl_config_move_done;
7520 	ctl_datamove((union ctl_io *)ctsio);
7521 	return (retval);
7522 }
7523 
7524 int
7525 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7526 {
7527 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
7528 	struct ctl_lun *lun = CTL_LUN(ctsio);
7529 	struct scsi_per_res_in *cdb;
7530 	int alloc_len, total_len = 0;
7531 	/* struct scsi_per_res_in_rsrv in_data; */
7532 	uint64_t key;
7533 
7534 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7535 
7536 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7537 
7538 	alloc_len = scsi_2btoul(cdb->length);
7539 
7540 retry:
7541 	mtx_lock(&lun->lun_lock);
7542 	switch (cdb->action) {
7543 	case SPRI_RK: /* read keys */
7544 		total_len = sizeof(struct scsi_per_res_in_keys) +
7545 			lun->pr_key_count *
7546 			sizeof(struct scsi_per_res_key);
7547 		break;
7548 	case SPRI_RR: /* read reservation */
7549 		if (lun->flags & CTL_LUN_PR_RESERVED)
7550 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7551 		else
7552 			total_len = sizeof(struct scsi_per_res_in_header);
7553 		break;
7554 	case SPRI_RC: /* report capabilities */
7555 		total_len = sizeof(struct scsi_per_res_cap);
7556 		break;
7557 	case SPRI_RS: /* read full status */
7558 		total_len = sizeof(struct scsi_per_res_in_header) +
7559 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7560 		    lun->pr_key_count;
7561 		break;
7562 	default:
7563 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7564 	}
7565 	mtx_unlock(&lun->lun_lock);
7566 
7567 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7568 	ctsio->kern_rel_offset = 0;
7569 	ctsio->kern_sg_entries = 0;
7570 	ctsio->kern_data_len = min(total_len, alloc_len);
7571 	ctsio->kern_total_len = ctsio->kern_data_len;
7572 
7573 	mtx_lock(&lun->lun_lock);
7574 	switch (cdb->action) {
7575 	case SPRI_RK: { // read keys
7576         struct scsi_per_res_in_keys *res_keys;
7577 		int i, key_count;
7578 
7579 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7580 
7581 		/*
7582 		 * We had to drop the lock to allocate our buffer, which
7583 		 * leaves time for someone to come in with another
7584 		 * persistent reservation.  (That is unlikely, though,
7585 		 * since this should be the only persistent reservation
7586 		 * command active right now.)
7587 		 */
7588 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7589 		    (lun->pr_key_count *
7590 		     sizeof(struct scsi_per_res_key)))){
7591 			mtx_unlock(&lun->lun_lock);
7592 			free(ctsio->kern_data_ptr, M_CTL);
7593 			printf("%s: reservation length changed, retrying\n",
7594 			       __func__);
7595 			goto retry;
7596 		}
7597 
7598 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7599 
7600 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7601 			     lun->pr_key_count, res_keys->header.length);
7602 
7603 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7604 			if ((key = ctl_get_prkey(lun, i)) == 0)
7605 				continue;
7606 
7607 			/*
7608 			 * We used lun->pr_key_count to calculate the
7609 			 * size to allocate.  If it turns out the number of
7610 			 * initiators with the registered flag set is
7611 			 * larger than that (i.e. they haven't been kept in
7612 			 * sync), we've got a problem.
7613 			 */
7614 			if (key_count >= lun->pr_key_count) {
7615 				key_count++;
7616 				continue;
7617 			}
7618 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7619 			key_count++;
7620 		}
7621 		break;
7622 	}
7623 	case SPRI_RR: { // read reservation
7624 		struct scsi_per_res_in_rsrv *res;
7625 		int tmp_len, header_only;
7626 
7627 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7628 
7629 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7630 
7631 		if (lun->flags & CTL_LUN_PR_RESERVED)
7632 		{
7633 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7634 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7635 				    res->header.length);
7636 			header_only = 0;
7637 		} else {
7638 			tmp_len = sizeof(struct scsi_per_res_in_header);
7639 			scsi_ulto4b(0, res->header.length);
7640 			header_only = 1;
7641 		}
7642 
7643 		/*
7644 		 * We had to drop the lock to allocate our buffer, which
7645 		 * leaves time for someone to come in with another
7646 		 * persistent reservation.  (That is unlikely, though,
7647 		 * since this should be the only persistent reservation
7648 		 * command active right now.)
7649 		 */
7650 		if (tmp_len != total_len) {
7651 			mtx_unlock(&lun->lun_lock);
7652 			free(ctsio->kern_data_ptr, M_CTL);
7653 			printf("%s: reservation status changed, retrying\n",
7654 			       __func__);
7655 			goto retry;
7656 		}
7657 
7658 		/*
7659 		 * No reservation held, so we're done.
7660 		 */
7661 		if (header_only != 0)
7662 			break;
7663 
7664 		/*
7665 		 * If the registration is an All Registrants type, the key
7666 		 * is 0, since it doesn't really matter.
7667 		 */
7668 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7669 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7670 			    res->data.reservation);
7671 		}
7672 		res->data.scopetype = lun->pr_res_type;
7673 		break;
7674 	}
7675 	case SPRI_RC:     //report capabilities
7676 	{
7677 		struct scsi_per_res_cap *res_cap;
7678 		uint16_t type_mask;
7679 
7680 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7681 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7682 		res_cap->flags1 = SPRI_CRH;
7683 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7684 		type_mask = SPRI_TM_WR_EX_AR |
7685 			    SPRI_TM_EX_AC_RO |
7686 			    SPRI_TM_WR_EX_RO |
7687 			    SPRI_TM_EX_AC |
7688 			    SPRI_TM_WR_EX |
7689 			    SPRI_TM_EX_AC_AR;
7690 		scsi_ulto2b(type_mask, res_cap->type_mask);
7691 		break;
7692 	}
7693 	case SPRI_RS: { // read full status
7694 		struct scsi_per_res_in_full *res_status;
7695 		struct scsi_per_res_in_full_desc *res_desc;
7696 		struct ctl_port *port;
7697 		int i, len;
7698 
7699 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7700 
7701 		/*
7702 		 * We had to drop the lock to allocate our buffer, which
7703 		 * leaves time for someone to come in with another
7704 		 * persistent reservation.  (That is unlikely, though,
7705 		 * since this should be the only persistent reservation
7706 		 * command active right now.)
7707 		 */
7708 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7709 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7710 		     lun->pr_key_count)){
7711 			mtx_unlock(&lun->lun_lock);
7712 			free(ctsio->kern_data_ptr, M_CTL);
7713 			printf("%s: reservation length changed, retrying\n",
7714 			       __func__);
7715 			goto retry;
7716 		}
7717 
7718 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7719 
7720 		res_desc = &res_status->desc[0];
7721 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7722 			if ((key = ctl_get_prkey(lun, i)) == 0)
7723 				continue;
7724 
7725 			scsi_u64to8b(key, res_desc->res_key.key);
7726 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7727 			    (lun->pr_res_idx == i ||
7728 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7729 				res_desc->flags = SPRI_FULL_R_HOLDER;
7730 				res_desc->scopetype = lun->pr_res_type;
7731 			}
7732 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7733 			    res_desc->rel_trgt_port_id);
7734 			len = 0;
7735 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7736 			if (port != NULL)
7737 				len = ctl_create_iid(port,
7738 				    i % CTL_MAX_INIT_PER_PORT,
7739 				    res_desc->transport_id);
7740 			scsi_ulto4b(len, res_desc->additional_length);
7741 			res_desc = (struct scsi_per_res_in_full_desc *)
7742 			    &res_desc->transport_id[len];
7743 		}
7744 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7745 		    res_status->header.length);
7746 		break;
7747 	}
7748 	default:
7749 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7750 	}
7751 	mtx_unlock(&lun->lun_lock);
7752 
7753 	ctl_set_success(ctsio);
7754 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7755 	ctsio->be_move_done = ctl_config_move_done;
7756 	ctl_datamove((union ctl_io *)ctsio);
7757 	return (CTL_RETVAL_COMPLETE);
7758 }
7759 
7760 /*
7761  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7762  * it should return.
7763  */
7764 static int
7765 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7766 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7767 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7768 		struct scsi_per_res_out_parms* param)
7769 {
7770 	union ctl_ha_msg persis_io;
7771 	int i;
7772 
7773 	mtx_lock(&lun->lun_lock);
7774 	if (sa_res_key == 0) {
7775 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7776 			/* validate scope and type */
7777 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7778 			     SPR_LU_SCOPE) {
7779 				mtx_unlock(&lun->lun_lock);
7780 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7781 						      /*sks_valid*/ 1,
7782 						      /*command*/ 1,
7783 						      /*field*/ 2,
7784 						      /*bit_valid*/ 1,
7785 						      /*bit*/ 4);
7786 				ctl_done((union ctl_io *)ctsio);
7787 				return (1);
7788 			}
7789 
7790 		        if (type>8 || type==2 || type==4 || type==0) {
7791 				mtx_unlock(&lun->lun_lock);
7792 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7793        	           				      /*sks_valid*/ 1,
7794 						      /*command*/ 1,
7795 						      /*field*/ 2,
7796 						      /*bit_valid*/ 1,
7797 						      /*bit*/ 0);
7798 				ctl_done((union ctl_io *)ctsio);
7799 				return (1);
7800 		        }
7801 
7802 			/*
7803 			 * Unregister everybody else and build UA for
7804 			 * them
7805 			 */
7806 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7807 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7808 					continue;
7809 
7810 				ctl_clr_prkey(lun, i);
7811 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7812 			}
7813 			lun->pr_key_count = 1;
7814 			lun->pr_res_type = type;
7815 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7816 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7817 				lun->pr_res_idx = residx;
7818 			lun->pr_generation++;
7819 			mtx_unlock(&lun->lun_lock);
7820 
7821 			/* send msg to other side */
7822 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7823 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7824 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7825 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7826 			persis_io.pr.pr_info.res_type = type;
7827 			memcpy(persis_io.pr.pr_info.sa_res_key,
7828 			       param->serv_act_res_key,
7829 			       sizeof(param->serv_act_res_key));
7830 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7831 			    sizeof(persis_io.pr), M_WAITOK);
7832 		} else {
7833 			/* not all registrants */
7834 			mtx_unlock(&lun->lun_lock);
7835 			free(ctsio->kern_data_ptr, M_CTL);
7836 			ctl_set_invalid_field(ctsio,
7837 					      /*sks_valid*/ 1,
7838 					      /*command*/ 0,
7839 					      /*field*/ 8,
7840 					      /*bit_valid*/ 0,
7841 					      /*bit*/ 0);
7842 			ctl_done((union ctl_io *)ctsio);
7843 			return (1);
7844 		}
7845 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7846 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7847 		int found = 0;
7848 
7849 		if (res_key == sa_res_key) {
7850 			/* special case */
7851 			/*
7852 			 * The spec implies this is not good but doesn't
7853 			 * say what to do. There are two choices either
7854 			 * generate a res conflict or check condition
7855 			 * with illegal field in parameter data. Since
7856 			 * that is what is done when the sa_res_key is
7857 			 * zero I'll take that approach since this has
7858 			 * to do with the sa_res_key.
7859 			 */
7860 			mtx_unlock(&lun->lun_lock);
7861 			free(ctsio->kern_data_ptr, M_CTL);
7862 			ctl_set_invalid_field(ctsio,
7863 					      /*sks_valid*/ 1,
7864 					      /*command*/ 0,
7865 					      /*field*/ 8,
7866 					      /*bit_valid*/ 0,
7867 					      /*bit*/ 0);
7868 			ctl_done((union ctl_io *)ctsio);
7869 			return (1);
7870 		}
7871 
7872 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7873 			if (ctl_get_prkey(lun, i) != sa_res_key)
7874 				continue;
7875 
7876 			found = 1;
7877 			ctl_clr_prkey(lun, i);
7878 			lun->pr_key_count--;
7879 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7880 		}
7881 		if (!found) {
7882 			mtx_unlock(&lun->lun_lock);
7883 			free(ctsio->kern_data_ptr, M_CTL);
7884 			ctl_set_reservation_conflict(ctsio);
7885 			ctl_done((union ctl_io *)ctsio);
7886 			return (CTL_RETVAL_COMPLETE);
7887 		}
7888 		lun->pr_generation++;
7889 		mtx_unlock(&lun->lun_lock);
7890 
7891 		/* send msg to other side */
7892 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7893 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7894 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7895 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7896 		persis_io.pr.pr_info.res_type = type;
7897 		memcpy(persis_io.pr.pr_info.sa_res_key,
7898 		       param->serv_act_res_key,
7899 		       sizeof(param->serv_act_res_key));
7900 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7901 		    sizeof(persis_io.pr), M_WAITOK);
7902 	} else {
7903 		/* Reserved but not all registrants */
7904 		/* sa_res_key is res holder */
7905 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7906 			/* validate scope and type */
7907 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7908 			     SPR_LU_SCOPE) {
7909 				mtx_unlock(&lun->lun_lock);
7910 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7911 						      /*sks_valid*/ 1,
7912 						      /*command*/ 1,
7913 						      /*field*/ 2,
7914 						      /*bit_valid*/ 1,
7915 						      /*bit*/ 4);
7916 				ctl_done((union ctl_io *)ctsio);
7917 				return (1);
7918 			}
7919 
7920 			if (type>8 || type==2 || type==4 || type==0) {
7921 				mtx_unlock(&lun->lun_lock);
7922 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7923 						      /*sks_valid*/ 1,
7924 						      /*command*/ 1,
7925 						      /*field*/ 2,
7926 						      /*bit_valid*/ 1,
7927 						      /*bit*/ 0);
7928 				ctl_done((union ctl_io *)ctsio);
7929 				return (1);
7930 			}
7931 
7932 			/*
7933 			 * Do the following:
7934 			 * if sa_res_key != res_key remove all
7935 			 * registrants w/sa_res_key and generate UA
7936 			 * for these registrants(Registrations
7937 			 * Preempted) if it wasn't an exclusive
7938 			 * reservation generate UA(Reservations
7939 			 * Preempted) for all other registered nexuses
7940 			 * if the type has changed. Establish the new
7941 			 * reservation and holder. If res_key and
7942 			 * sa_res_key are the same do the above
7943 			 * except don't unregister the res holder.
7944 			 */
7945 
7946 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7947 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7948 					continue;
7949 
7950 				if (sa_res_key == ctl_get_prkey(lun, i)) {
7951 					ctl_clr_prkey(lun, i);
7952 					lun->pr_key_count--;
7953 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7954 				} else if (type != lun->pr_res_type &&
7955 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7956 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7957 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7958 				}
7959 			}
7960 			lun->pr_res_type = type;
7961 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7962 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7963 				lun->pr_res_idx = residx;
7964 			else
7965 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7966 			lun->pr_generation++;
7967 			mtx_unlock(&lun->lun_lock);
7968 
7969 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7970 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7971 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7972 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7973 			persis_io.pr.pr_info.res_type = type;
7974 			memcpy(persis_io.pr.pr_info.sa_res_key,
7975 			       param->serv_act_res_key,
7976 			       sizeof(param->serv_act_res_key));
7977 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7978 			    sizeof(persis_io.pr), M_WAITOK);
7979 		} else {
7980 			/*
7981 			 * sa_res_key is not the res holder just
7982 			 * remove registrants
7983 			 */
7984 			int found=0;
7985 
7986 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7987 				if (sa_res_key != ctl_get_prkey(lun, i))
7988 					continue;
7989 
7990 				found = 1;
7991 				ctl_clr_prkey(lun, i);
7992 				lun->pr_key_count--;
7993 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7994 			}
7995 
7996 			if (!found) {
7997 				mtx_unlock(&lun->lun_lock);
7998 				free(ctsio->kern_data_ptr, M_CTL);
7999 				ctl_set_reservation_conflict(ctsio);
8000 				ctl_done((union ctl_io *)ctsio);
8001 		        	return (1);
8002 			}
8003 			lun->pr_generation++;
8004 			mtx_unlock(&lun->lun_lock);
8005 
8006 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8007 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8008 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8009 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8010 			persis_io.pr.pr_info.res_type = type;
8011 			memcpy(persis_io.pr.pr_info.sa_res_key,
8012 			       param->serv_act_res_key,
8013 			       sizeof(param->serv_act_res_key));
8014 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8015 			    sizeof(persis_io.pr), M_WAITOK);
8016 		}
8017 	}
8018 	return (0);
8019 }
8020 
8021 static void
8022 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8023 {
8024 	uint64_t sa_res_key;
8025 	int i;
8026 
8027 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8028 
8029 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8030 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8031 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
8032 		if (sa_res_key == 0) {
8033 			/*
8034 			 * Unregister everybody else and build UA for
8035 			 * them
8036 			 */
8037 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
8038 				if (i == msg->pr.pr_info.residx ||
8039 				    ctl_get_prkey(lun, i) == 0)
8040 					continue;
8041 
8042 				ctl_clr_prkey(lun, i);
8043 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8044 			}
8045 
8046 			lun->pr_key_count = 1;
8047 			lun->pr_res_type = msg->pr.pr_info.res_type;
8048 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8049 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8050 				lun->pr_res_idx = msg->pr.pr_info.residx;
8051 		} else {
8052 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8053 				if (sa_res_key == ctl_get_prkey(lun, i))
8054 					continue;
8055 
8056 				ctl_clr_prkey(lun, i);
8057 				lun->pr_key_count--;
8058 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8059 			}
8060 		}
8061 	} else {
8062 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8063 			if (i == msg->pr.pr_info.residx ||
8064 			    ctl_get_prkey(lun, i) == 0)
8065 				continue;
8066 
8067 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8068 				ctl_clr_prkey(lun, i);
8069 				lun->pr_key_count--;
8070 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8071 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8072 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8073 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8074 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8075 			}
8076 		}
8077 		lun->pr_res_type = msg->pr.pr_info.res_type;
8078 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8079 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8080 			lun->pr_res_idx = msg->pr.pr_info.residx;
8081 		else
8082 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8083 	}
8084 	lun->pr_generation++;
8085 
8086 }
8087 
8088 
8089 int
8090 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8091 {
8092 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
8093 	struct ctl_lun *lun = CTL_LUN(ctsio);
8094 	int retval;
8095 	u_int32_t param_len;
8096 	struct scsi_per_res_out *cdb;
8097 	struct scsi_per_res_out_parms* param;
8098 	uint32_t residx;
8099 	uint64_t res_key, sa_res_key, key;
8100 	uint8_t type;
8101 	union ctl_ha_msg persis_io;
8102 	int    i;
8103 
8104 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8105 
8106 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8107 	retval = CTL_RETVAL_COMPLETE;
8108 
8109 	/*
8110 	 * We only support whole-LUN scope.  The scope & type are ignored for
8111 	 * register, register and ignore existing key and clear.
8112 	 * We sometimes ignore scope and type on preempts too!!
8113 	 * Verify reservation type here as well.
8114 	 */
8115 	type = cdb->scope_type & SPR_TYPE_MASK;
8116 	if ((cdb->action == SPRO_RESERVE)
8117 	 || (cdb->action == SPRO_RELEASE)) {
8118 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8119 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8120 					      /*sks_valid*/ 1,
8121 					      /*command*/ 1,
8122 					      /*field*/ 2,
8123 					      /*bit_valid*/ 1,
8124 					      /*bit*/ 4);
8125 			ctl_done((union ctl_io *)ctsio);
8126 			return (CTL_RETVAL_COMPLETE);
8127 		}
8128 
8129 		if (type>8 || type==2 || type==4 || type==0) {
8130 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8131 					      /*sks_valid*/ 1,
8132 					      /*command*/ 1,
8133 					      /*field*/ 2,
8134 					      /*bit_valid*/ 1,
8135 					      /*bit*/ 0);
8136 			ctl_done((union ctl_io *)ctsio);
8137 			return (CTL_RETVAL_COMPLETE);
8138 		}
8139 	}
8140 
8141 	param_len = scsi_4btoul(cdb->length);
8142 
8143 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8144 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8145 		ctsio->kern_data_len = param_len;
8146 		ctsio->kern_total_len = param_len;
8147 		ctsio->kern_rel_offset = 0;
8148 		ctsio->kern_sg_entries = 0;
8149 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8150 		ctsio->be_move_done = ctl_config_move_done;
8151 		ctl_datamove((union ctl_io *)ctsio);
8152 
8153 		return (CTL_RETVAL_COMPLETE);
8154 	}
8155 
8156 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8157 
8158 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8159 	res_key = scsi_8btou64(param->res_key.key);
8160 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8161 
8162 	/*
8163 	 * Validate the reservation key here except for SPRO_REG_IGNO
8164 	 * This must be done for all other service actions
8165 	 */
8166 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8167 		mtx_lock(&lun->lun_lock);
8168 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8169 			if (res_key != key) {
8170 				/*
8171 				 * The current key passed in doesn't match
8172 				 * the one the initiator previously
8173 				 * registered.
8174 				 */
8175 				mtx_unlock(&lun->lun_lock);
8176 				free(ctsio->kern_data_ptr, M_CTL);
8177 				ctl_set_reservation_conflict(ctsio);
8178 				ctl_done((union ctl_io *)ctsio);
8179 				return (CTL_RETVAL_COMPLETE);
8180 			}
8181 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8182 			/*
8183 			 * We are not registered
8184 			 */
8185 			mtx_unlock(&lun->lun_lock);
8186 			free(ctsio->kern_data_ptr, M_CTL);
8187 			ctl_set_reservation_conflict(ctsio);
8188 			ctl_done((union ctl_io *)ctsio);
8189 			return (CTL_RETVAL_COMPLETE);
8190 		} else if (res_key != 0) {
8191 			/*
8192 			 * We are not registered and trying to register but
8193 			 * the register key isn't zero.
8194 			 */
8195 			mtx_unlock(&lun->lun_lock);
8196 			free(ctsio->kern_data_ptr, M_CTL);
8197 			ctl_set_reservation_conflict(ctsio);
8198 			ctl_done((union ctl_io *)ctsio);
8199 			return (CTL_RETVAL_COMPLETE);
8200 		}
8201 		mtx_unlock(&lun->lun_lock);
8202 	}
8203 
8204 	switch (cdb->action & SPRO_ACTION_MASK) {
8205 	case SPRO_REGISTER:
8206 	case SPRO_REG_IGNO: {
8207 
8208 #if 0
8209 		printf("Registration received\n");
8210 #endif
8211 
8212 		/*
8213 		 * We don't support any of these options, as we report in
8214 		 * the read capabilities request (see
8215 		 * ctl_persistent_reserve_in(), above).
8216 		 */
8217 		if ((param->flags & SPR_SPEC_I_PT)
8218 		 || (param->flags & SPR_ALL_TG_PT)
8219 		 || (param->flags & SPR_APTPL)) {
8220 			int bit_ptr;
8221 
8222 			if (param->flags & SPR_APTPL)
8223 				bit_ptr = 0;
8224 			else if (param->flags & SPR_ALL_TG_PT)
8225 				bit_ptr = 2;
8226 			else /* SPR_SPEC_I_PT */
8227 				bit_ptr = 3;
8228 
8229 			free(ctsio->kern_data_ptr, M_CTL);
8230 			ctl_set_invalid_field(ctsio,
8231 					      /*sks_valid*/ 1,
8232 					      /*command*/ 0,
8233 					      /*field*/ 20,
8234 					      /*bit_valid*/ 1,
8235 					      /*bit*/ bit_ptr);
8236 			ctl_done((union ctl_io *)ctsio);
8237 			return (CTL_RETVAL_COMPLETE);
8238 		}
8239 
8240 		mtx_lock(&lun->lun_lock);
8241 
8242 		/*
8243 		 * The initiator wants to clear the
8244 		 * key/unregister.
8245 		 */
8246 		if (sa_res_key == 0) {
8247 			if ((res_key == 0
8248 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8249 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8250 			  && ctl_get_prkey(lun, residx) == 0)) {
8251 				mtx_unlock(&lun->lun_lock);
8252 				goto done;
8253 			}
8254 
8255 			ctl_clr_prkey(lun, residx);
8256 			lun->pr_key_count--;
8257 
8258 			if (residx == lun->pr_res_idx) {
8259 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8260 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8261 
8262 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8263 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8264 				    lun->pr_key_count) {
8265 					/*
8266 					 * If the reservation is a registrants
8267 					 * only type we need to generate a UA
8268 					 * for other registered inits.  The
8269 					 * sense code should be RESERVATIONS
8270 					 * RELEASED
8271 					 */
8272 
8273 					for (i = softc->init_min; i < softc->init_max; i++){
8274 						if (ctl_get_prkey(lun, i) == 0)
8275 							continue;
8276 						ctl_est_ua(lun, i,
8277 						    CTL_UA_RES_RELEASE);
8278 					}
8279 				}
8280 				lun->pr_res_type = 0;
8281 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8282 				if (lun->pr_key_count==0) {
8283 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8284 					lun->pr_res_type = 0;
8285 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8286 				}
8287 			}
8288 			lun->pr_generation++;
8289 			mtx_unlock(&lun->lun_lock);
8290 
8291 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8292 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8293 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8294 			persis_io.pr.pr_info.residx = residx;
8295 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8296 			    sizeof(persis_io.pr), M_WAITOK);
8297 		} else /* sa_res_key != 0 */ {
8298 
8299 			/*
8300 			 * If we aren't registered currently then increment
8301 			 * the key count and set the registered flag.
8302 			 */
8303 			ctl_alloc_prkey(lun, residx);
8304 			if (ctl_get_prkey(lun, residx) == 0)
8305 				lun->pr_key_count++;
8306 			ctl_set_prkey(lun, residx, sa_res_key);
8307 			lun->pr_generation++;
8308 			mtx_unlock(&lun->lun_lock);
8309 
8310 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8311 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8312 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8313 			persis_io.pr.pr_info.residx = residx;
8314 			memcpy(persis_io.pr.pr_info.sa_res_key,
8315 			       param->serv_act_res_key,
8316 			       sizeof(param->serv_act_res_key));
8317 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8318 			    sizeof(persis_io.pr), M_WAITOK);
8319 		}
8320 
8321 		break;
8322 	}
8323 	case SPRO_RESERVE:
8324 #if 0
8325                 printf("Reserve executed type %d\n", type);
8326 #endif
8327 		mtx_lock(&lun->lun_lock);
8328 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8329 			/*
8330 			 * if this isn't the reservation holder and it's
8331 			 * not a "all registrants" type or if the type is
8332 			 * different then we have a conflict
8333 			 */
8334 			if ((lun->pr_res_idx != residx
8335 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8336 			 || lun->pr_res_type != type) {
8337 				mtx_unlock(&lun->lun_lock);
8338 				free(ctsio->kern_data_ptr, M_CTL);
8339 				ctl_set_reservation_conflict(ctsio);
8340 				ctl_done((union ctl_io *)ctsio);
8341 				return (CTL_RETVAL_COMPLETE);
8342 			}
8343 			mtx_unlock(&lun->lun_lock);
8344 		} else /* create a reservation */ {
8345 			/*
8346 			 * If it's not an "all registrants" type record
8347 			 * reservation holder
8348 			 */
8349 			if (type != SPR_TYPE_WR_EX_AR
8350 			 && type != SPR_TYPE_EX_AC_AR)
8351 				lun->pr_res_idx = residx; /* Res holder */
8352 			else
8353 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8354 
8355 			lun->flags |= CTL_LUN_PR_RESERVED;
8356 			lun->pr_res_type = type;
8357 
8358 			mtx_unlock(&lun->lun_lock);
8359 
8360 			/* send msg to other side */
8361 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8362 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8363 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8364 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8365 			persis_io.pr.pr_info.res_type = type;
8366 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8367 			    sizeof(persis_io.pr), M_WAITOK);
8368 		}
8369 		break;
8370 
8371 	case SPRO_RELEASE:
8372 		mtx_lock(&lun->lun_lock);
8373 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8374 			/* No reservation exists return good status */
8375 			mtx_unlock(&lun->lun_lock);
8376 			goto done;
8377 		}
8378 		/*
8379 		 * Is this nexus a reservation holder?
8380 		 */
8381 		if (lun->pr_res_idx != residx
8382 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8383 			/*
8384 			 * not a res holder return good status but
8385 			 * do nothing
8386 			 */
8387 			mtx_unlock(&lun->lun_lock);
8388 			goto done;
8389 		}
8390 
8391 		if (lun->pr_res_type != type) {
8392 			mtx_unlock(&lun->lun_lock);
8393 			free(ctsio->kern_data_ptr, M_CTL);
8394 			ctl_set_illegal_pr_release(ctsio);
8395 			ctl_done((union ctl_io *)ctsio);
8396 			return (CTL_RETVAL_COMPLETE);
8397 		}
8398 
8399 		/* okay to release */
8400 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8401 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8402 		lun->pr_res_type = 0;
8403 
8404 		/*
8405 		 * If this isn't an exclusive access reservation and NUAR
8406 		 * is not set, generate UA for all other registrants.
8407 		 */
8408 		if (type != SPR_TYPE_EX_AC && type != SPR_TYPE_WR_EX &&
8409 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8410 			for (i = softc->init_min; i < softc->init_max; i++) {
8411 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8412 					continue;
8413 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8414 			}
8415 		}
8416 		mtx_unlock(&lun->lun_lock);
8417 
8418 		/* Send msg to other side */
8419 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8420 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8421 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8422 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8423 		     sizeof(persis_io.pr), M_WAITOK);
8424 		break;
8425 
8426 	case SPRO_CLEAR:
8427 		/* send msg to other side */
8428 
8429 		mtx_lock(&lun->lun_lock);
8430 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8431 		lun->pr_res_type = 0;
8432 		lun->pr_key_count = 0;
8433 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8434 
8435 		ctl_clr_prkey(lun, residx);
8436 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8437 			if (ctl_get_prkey(lun, i) != 0) {
8438 				ctl_clr_prkey(lun, i);
8439 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8440 			}
8441 		lun->pr_generation++;
8442 		mtx_unlock(&lun->lun_lock);
8443 
8444 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8445 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8446 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8447 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8448 		     sizeof(persis_io.pr), M_WAITOK);
8449 		break;
8450 
8451 	case SPRO_PREEMPT:
8452 	case SPRO_PRE_ABO: {
8453 		int nretval;
8454 
8455 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8456 					  residx, ctsio, cdb, param);
8457 		if (nretval != 0)
8458 			return (CTL_RETVAL_COMPLETE);
8459 		break;
8460 	}
8461 	default:
8462 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8463 	}
8464 
8465 done:
8466 	free(ctsio->kern_data_ptr, M_CTL);
8467 	ctl_set_success(ctsio);
8468 	ctl_done((union ctl_io *)ctsio);
8469 
8470 	return (retval);
8471 }
8472 
8473 /*
8474  * This routine is for handling a message from the other SC pertaining to
8475  * persistent reserve out. All the error checking will have been done
8476  * so only perorming the action need be done here to keep the two
8477  * in sync.
8478  */
8479 static void
8480 ctl_hndl_per_res_out_on_other_sc(union ctl_io *io)
8481 {
8482 	struct ctl_softc *softc = CTL_SOFTC(io);
8483 	union ctl_ha_msg *msg = (union ctl_ha_msg *)&io->presio.pr_msg;
8484 	struct ctl_lun *lun;
8485 	int i;
8486 	uint32_t residx, targ_lun;
8487 
8488 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8489 	mtx_lock(&softc->ctl_lock);
8490 	if (targ_lun >= CTL_MAX_LUNS ||
8491 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
8492 		mtx_unlock(&softc->ctl_lock);
8493 		return;
8494 	}
8495 	mtx_lock(&lun->lun_lock);
8496 	mtx_unlock(&softc->ctl_lock);
8497 	if (lun->flags & CTL_LUN_DISABLED) {
8498 		mtx_unlock(&lun->lun_lock);
8499 		return;
8500 	}
8501 	residx = ctl_get_initindex(&msg->hdr.nexus);
8502 	switch(msg->pr.pr_info.action) {
8503 	case CTL_PR_REG_KEY:
8504 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8505 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8506 			lun->pr_key_count++;
8507 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8508 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8509 		lun->pr_generation++;
8510 		break;
8511 
8512 	case CTL_PR_UNREG_KEY:
8513 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8514 		lun->pr_key_count--;
8515 
8516 		/* XXX Need to see if the reservation has been released */
8517 		/* if so do we need to generate UA? */
8518 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8519 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8520 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8521 
8522 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8523 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8524 			    lun->pr_key_count) {
8525 				/*
8526 				 * If the reservation is a registrants
8527 				 * only type we need to generate a UA
8528 				 * for other registered inits.  The
8529 				 * sense code should be RESERVATIONS
8530 				 * RELEASED
8531 				 */
8532 
8533 				for (i = softc->init_min; i < softc->init_max; i++) {
8534 					if (ctl_get_prkey(lun, i) == 0)
8535 						continue;
8536 
8537 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8538 				}
8539 			}
8540 			lun->pr_res_type = 0;
8541 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8542 			if (lun->pr_key_count==0) {
8543 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8544 				lun->pr_res_type = 0;
8545 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8546 			}
8547 		}
8548 		lun->pr_generation++;
8549 		break;
8550 
8551 	case CTL_PR_RESERVE:
8552 		lun->flags |= CTL_LUN_PR_RESERVED;
8553 		lun->pr_res_type = msg->pr.pr_info.res_type;
8554 		lun->pr_res_idx = msg->pr.pr_info.residx;
8555 
8556 		break;
8557 
8558 	case CTL_PR_RELEASE:
8559 		/*
8560 		 * If this isn't an exclusive access reservation and NUAR
8561 		 * is not set, generate UA for all other registrants.
8562 		 */
8563 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8564 		    lun->pr_res_type != SPR_TYPE_WR_EX &&
8565 		    (lun->MODE_CTRL.queue_flags & SCP_NUAR) == 0) {
8566 			for (i = softc->init_min; i < softc->init_max; i++)
8567 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8568 					continue;
8569 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8570 		}
8571 
8572 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8573 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8574 		lun->pr_res_type = 0;
8575 		break;
8576 
8577 	case CTL_PR_PREEMPT:
8578 		ctl_pro_preempt_other(lun, msg);
8579 		break;
8580 	case CTL_PR_CLEAR:
8581 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8582 		lun->pr_res_type = 0;
8583 		lun->pr_key_count = 0;
8584 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8585 
8586 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8587 			if (ctl_get_prkey(lun, i) == 0)
8588 				continue;
8589 			ctl_clr_prkey(lun, i);
8590 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8591 		}
8592 		lun->pr_generation++;
8593 		break;
8594 	}
8595 
8596 	mtx_unlock(&lun->lun_lock);
8597 }
8598 
8599 int
8600 ctl_read_write(struct ctl_scsiio *ctsio)
8601 {
8602 	struct ctl_lun *lun = CTL_LUN(ctsio);
8603 	struct ctl_lba_len_flags *lbalen;
8604 	uint64_t lba;
8605 	uint32_t num_blocks;
8606 	int flags, retval;
8607 	int isread;
8608 
8609 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8610 
8611 	flags = 0;
8612 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8613 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8614 	switch (ctsio->cdb[0]) {
8615 	case READ_6:
8616 	case WRITE_6: {
8617 		struct scsi_rw_6 *cdb;
8618 
8619 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8620 
8621 		lba = scsi_3btoul(cdb->addr);
8622 		/* only 5 bits are valid in the most significant address byte */
8623 		lba &= 0x1fffff;
8624 		num_blocks = cdb->length;
8625 		/*
8626 		 * This is correct according to SBC-2.
8627 		 */
8628 		if (num_blocks == 0)
8629 			num_blocks = 256;
8630 		break;
8631 	}
8632 	case READ_10:
8633 	case WRITE_10: {
8634 		struct scsi_rw_10 *cdb;
8635 
8636 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8637 		if (cdb->byte2 & SRW10_FUA)
8638 			flags |= CTL_LLF_FUA;
8639 		if (cdb->byte2 & SRW10_DPO)
8640 			flags |= CTL_LLF_DPO;
8641 		lba = scsi_4btoul(cdb->addr);
8642 		num_blocks = scsi_2btoul(cdb->length);
8643 		break;
8644 	}
8645 	case WRITE_VERIFY_10: {
8646 		struct scsi_write_verify_10 *cdb;
8647 
8648 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8649 		flags |= CTL_LLF_FUA;
8650 		if (cdb->byte2 & SWV_DPO)
8651 			flags |= CTL_LLF_DPO;
8652 		lba = scsi_4btoul(cdb->addr);
8653 		num_blocks = scsi_2btoul(cdb->length);
8654 		break;
8655 	}
8656 	case READ_12:
8657 	case WRITE_12: {
8658 		struct scsi_rw_12 *cdb;
8659 
8660 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8661 		if (cdb->byte2 & SRW12_FUA)
8662 			flags |= CTL_LLF_FUA;
8663 		if (cdb->byte2 & SRW12_DPO)
8664 			flags |= CTL_LLF_DPO;
8665 		lba = scsi_4btoul(cdb->addr);
8666 		num_blocks = scsi_4btoul(cdb->length);
8667 		break;
8668 	}
8669 	case WRITE_VERIFY_12: {
8670 		struct scsi_write_verify_12 *cdb;
8671 
8672 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8673 		flags |= CTL_LLF_FUA;
8674 		if (cdb->byte2 & SWV_DPO)
8675 			flags |= CTL_LLF_DPO;
8676 		lba = scsi_4btoul(cdb->addr);
8677 		num_blocks = scsi_4btoul(cdb->length);
8678 		break;
8679 	}
8680 	case READ_16:
8681 	case WRITE_16: {
8682 		struct scsi_rw_16 *cdb;
8683 
8684 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8685 		if (cdb->byte2 & SRW12_FUA)
8686 			flags |= CTL_LLF_FUA;
8687 		if (cdb->byte2 & SRW12_DPO)
8688 			flags |= CTL_LLF_DPO;
8689 		lba = scsi_8btou64(cdb->addr);
8690 		num_blocks = scsi_4btoul(cdb->length);
8691 		break;
8692 	}
8693 	case WRITE_ATOMIC_16: {
8694 		struct scsi_write_atomic_16 *cdb;
8695 
8696 		if (lun->be_lun->atomicblock == 0) {
8697 			ctl_set_invalid_opcode(ctsio);
8698 			ctl_done((union ctl_io *)ctsio);
8699 			return (CTL_RETVAL_COMPLETE);
8700 		}
8701 
8702 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8703 		if (cdb->byte2 & SRW12_FUA)
8704 			flags |= CTL_LLF_FUA;
8705 		if (cdb->byte2 & SRW12_DPO)
8706 			flags |= CTL_LLF_DPO;
8707 		lba = scsi_8btou64(cdb->addr);
8708 		num_blocks = scsi_2btoul(cdb->length);
8709 		if (num_blocks > lun->be_lun->atomicblock) {
8710 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8711 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8712 			    /*bit*/ 0);
8713 			ctl_done((union ctl_io *)ctsio);
8714 			return (CTL_RETVAL_COMPLETE);
8715 		}
8716 		break;
8717 	}
8718 	case WRITE_VERIFY_16: {
8719 		struct scsi_write_verify_16 *cdb;
8720 
8721 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8722 		flags |= CTL_LLF_FUA;
8723 		if (cdb->byte2 & SWV_DPO)
8724 			flags |= CTL_LLF_DPO;
8725 		lba = scsi_8btou64(cdb->addr);
8726 		num_blocks = scsi_4btoul(cdb->length);
8727 		break;
8728 	}
8729 	default:
8730 		/*
8731 		 * We got a command we don't support.  This shouldn't
8732 		 * happen, commands should be filtered out above us.
8733 		 */
8734 		ctl_set_invalid_opcode(ctsio);
8735 		ctl_done((union ctl_io *)ctsio);
8736 
8737 		return (CTL_RETVAL_COMPLETE);
8738 		break; /* NOTREACHED */
8739 	}
8740 
8741 	/*
8742 	 * The first check is to make sure we're in bounds, the second
8743 	 * check is to catch wrap-around problems.  If the lba + num blocks
8744 	 * is less than the lba, then we've wrapped around and the block
8745 	 * range is invalid anyway.
8746 	 */
8747 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8748 	 || ((lba + num_blocks) < lba)) {
8749 		ctl_set_lba_out_of_range(ctsio,
8750 		    MAX(lba, lun->be_lun->maxlba + 1));
8751 		ctl_done((union ctl_io *)ctsio);
8752 		return (CTL_RETVAL_COMPLETE);
8753 	}
8754 
8755 	/*
8756 	 * According to SBC-3, a transfer length of 0 is not an error.
8757 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8758 	 * translates to 256 blocks for those commands.
8759 	 */
8760 	if (num_blocks == 0) {
8761 		ctl_set_success(ctsio);
8762 		ctl_done((union ctl_io *)ctsio);
8763 		return (CTL_RETVAL_COMPLETE);
8764 	}
8765 
8766 	/* Set FUA and/or DPO if caches are disabled. */
8767 	if (isread) {
8768 		if ((lun->MODE_CACHING.flags1 & SCP_RCD) != 0)
8769 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8770 	} else {
8771 		if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8772 			flags |= CTL_LLF_FUA;
8773 	}
8774 
8775 	lbalen = (struct ctl_lba_len_flags *)
8776 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8777 	lbalen->lba = lba;
8778 	lbalen->len = num_blocks;
8779 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8780 
8781 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8782 	ctsio->kern_rel_offset = 0;
8783 
8784 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8785 
8786 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8787 	return (retval);
8788 }
8789 
8790 static int
8791 ctl_cnw_cont(union ctl_io *io)
8792 {
8793 	struct ctl_lun *lun = CTL_LUN(io);
8794 	struct ctl_scsiio *ctsio;
8795 	struct ctl_lba_len_flags *lbalen;
8796 	int retval;
8797 
8798 	ctsio = &io->scsiio;
8799 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8800 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8801 	lbalen = (struct ctl_lba_len_flags *)
8802 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8803 	lbalen->flags &= ~CTL_LLF_COMPARE;
8804 	lbalen->flags |= CTL_LLF_WRITE;
8805 
8806 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8807 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8808 	return (retval);
8809 }
8810 
8811 int
8812 ctl_cnw(struct ctl_scsiio *ctsio)
8813 {
8814 	struct ctl_lun *lun = CTL_LUN(ctsio);
8815 	struct ctl_lba_len_flags *lbalen;
8816 	uint64_t lba;
8817 	uint32_t num_blocks;
8818 	int flags, retval;
8819 
8820 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8821 
8822 	flags = 0;
8823 	switch (ctsio->cdb[0]) {
8824 	case COMPARE_AND_WRITE: {
8825 		struct scsi_compare_and_write *cdb;
8826 
8827 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8828 		if (cdb->byte2 & SRW10_FUA)
8829 			flags |= CTL_LLF_FUA;
8830 		if (cdb->byte2 & SRW10_DPO)
8831 			flags |= CTL_LLF_DPO;
8832 		lba = scsi_8btou64(cdb->addr);
8833 		num_blocks = cdb->length;
8834 		break;
8835 	}
8836 	default:
8837 		/*
8838 		 * We got a command we don't support.  This shouldn't
8839 		 * happen, commands should be filtered out above us.
8840 		 */
8841 		ctl_set_invalid_opcode(ctsio);
8842 		ctl_done((union ctl_io *)ctsio);
8843 
8844 		return (CTL_RETVAL_COMPLETE);
8845 		break; /* NOTREACHED */
8846 	}
8847 
8848 	/*
8849 	 * The first check is to make sure we're in bounds, the second
8850 	 * check is to catch wrap-around problems.  If the lba + num blocks
8851 	 * is less than the lba, then we've wrapped around and the block
8852 	 * range is invalid anyway.
8853 	 */
8854 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8855 	 || ((lba + num_blocks) < lba)) {
8856 		ctl_set_lba_out_of_range(ctsio,
8857 		    MAX(lba, lun->be_lun->maxlba + 1));
8858 		ctl_done((union ctl_io *)ctsio);
8859 		return (CTL_RETVAL_COMPLETE);
8860 	}
8861 
8862 	/*
8863 	 * According to SBC-3, a transfer length of 0 is not an error.
8864 	 */
8865 	if (num_blocks == 0) {
8866 		ctl_set_success(ctsio);
8867 		ctl_done((union ctl_io *)ctsio);
8868 		return (CTL_RETVAL_COMPLETE);
8869 	}
8870 
8871 	/* Set FUA if write cache is disabled. */
8872 	if ((lun->MODE_CACHING.flags1 & SCP_WCE) == 0)
8873 		flags |= CTL_LLF_FUA;
8874 
8875 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8876 	ctsio->kern_rel_offset = 0;
8877 
8878 	/*
8879 	 * Set the IO_CONT flag, so that if this I/O gets passed to
8880 	 * ctl_data_submit_done(), it'll get passed back to
8881 	 * ctl_ctl_cnw_cont() for further processing.
8882 	 */
8883 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8884 	ctsio->io_cont = ctl_cnw_cont;
8885 
8886 	lbalen = (struct ctl_lba_len_flags *)
8887 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8888 	lbalen->lba = lba;
8889 	lbalen->len = num_blocks;
8890 	lbalen->flags = CTL_LLF_COMPARE | flags;
8891 
8892 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8893 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8894 	return (retval);
8895 }
8896 
8897 int
8898 ctl_verify(struct ctl_scsiio *ctsio)
8899 {
8900 	struct ctl_lun *lun = CTL_LUN(ctsio);
8901 	struct ctl_lba_len_flags *lbalen;
8902 	uint64_t lba;
8903 	uint32_t num_blocks;
8904 	int bytchk, flags;
8905 	int retval;
8906 
8907 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8908 
8909 	bytchk = 0;
8910 	flags = CTL_LLF_FUA;
8911 	switch (ctsio->cdb[0]) {
8912 	case VERIFY_10: {
8913 		struct scsi_verify_10 *cdb;
8914 
8915 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8916 		if (cdb->byte2 & SVFY_BYTCHK)
8917 			bytchk = 1;
8918 		if (cdb->byte2 & SVFY_DPO)
8919 			flags |= CTL_LLF_DPO;
8920 		lba = scsi_4btoul(cdb->addr);
8921 		num_blocks = scsi_2btoul(cdb->length);
8922 		break;
8923 	}
8924 	case VERIFY_12: {
8925 		struct scsi_verify_12 *cdb;
8926 
8927 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8928 		if (cdb->byte2 & SVFY_BYTCHK)
8929 			bytchk = 1;
8930 		if (cdb->byte2 & SVFY_DPO)
8931 			flags |= CTL_LLF_DPO;
8932 		lba = scsi_4btoul(cdb->addr);
8933 		num_blocks = scsi_4btoul(cdb->length);
8934 		break;
8935 	}
8936 	case VERIFY_16: {
8937 		struct scsi_rw_16 *cdb;
8938 
8939 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8940 		if (cdb->byte2 & SVFY_BYTCHK)
8941 			bytchk = 1;
8942 		if (cdb->byte2 & SVFY_DPO)
8943 			flags |= CTL_LLF_DPO;
8944 		lba = scsi_8btou64(cdb->addr);
8945 		num_blocks = scsi_4btoul(cdb->length);
8946 		break;
8947 	}
8948 	default:
8949 		/*
8950 		 * We got a command we don't support.  This shouldn't
8951 		 * happen, commands should be filtered out above us.
8952 		 */
8953 		ctl_set_invalid_opcode(ctsio);
8954 		ctl_done((union ctl_io *)ctsio);
8955 		return (CTL_RETVAL_COMPLETE);
8956 	}
8957 
8958 	/*
8959 	 * The first check is to make sure we're in bounds, the second
8960 	 * check is to catch wrap-around problems.  If the lba + num blocks
8961 	 * is less than the lba, then we've wrapped around and the block
8962 	 * range is invalid anyway.
8963 	 */
8964 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8965 	 || ((lba + num_blocks) < lba)) {
8966 		ctl_set_lba_out_of_range(ctsio,
8967 		    MAX(lba, lun->be_lun->maxlba + 1));
8968 		ctl_done((union ctl_io *)ctsio);
8969 		return (CTL_RETVAL_COMPLETE);
8970 	}
8971 
8972 	/*
8973 	 * According to SBC-3, a transfer length of 0 is not an error.
8974 	 */
8975 	if (num_blocks == 0) {
8976 		ctl_set_success(ctsio);
8977 		ctl_done((union ctl_io *)ctsio);
8978 		return (CTL_RETVAL_COMPLETE);
8979 	}
8980 
8981 	lbalen = (struct ctl_lba_len_flags *)
8982 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8983 	lbalen->lba = lba;
8984 	lbalen->len = num_blocks;
8985 	if (bytchk) {
8986 		lbalen->flags = CTL_LLF_COMPARE | flags;
8987 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8988 	} else {
8989 		lbalen->flags = CTL_LLF_VERIFY | flags;
8990 		ctsio->kern_total_len = 0;
8991 	}
8992 	ctsio->kern_rel_offset = 0;
8993 
8994 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8995 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8996 	return (retval);
8997 }
8998 
8999 int
9000 ctl_report_luns(struct ctl_scsiio *ctsio)
9001 {
9002 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9003 	struct ctl_port *port = CTL_PORT(ctsio);
9004 	struct ctl_lun *lun, *request_lun = CTL_LUN(ctsio);
9005 	struct scsi_report_luns *cdb;
9006 	struct scsi_report_luns_data *lun_data;
9007 	int num_filled, num_luns, num_port_luns, retval;
9008 	uint32_t alloc_len, lun_datalen;
9009 	uint32_t initidx, targ_lun_id, lun_id;
9010 
9011 	retval = CTL_RETVAL_COMPLETE;
9012 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9013 
9014 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9015 
9016 	num_luns = 0;
9017 	num_port_luns = port->lun_map ? port->lun_map_size : CTL_MAX_LUNS;
9018 	mtx_lock(&softc->ctl_lock);
9019 	for (targ_lun_id = 0; targ_lun_id < num_port_luns; targ_lun_id++) {
9020 		if (ctl_lun_map_from_port(port, targ_lun_id) != UINT32_MAX)
9021 			num_luns++;
9022 	}
9023 	mtx_unlock(&softc->ctl_lock);
9024 
9025 	switch (cdb->select_report) {
9026 	case RPL_REPORT_DEFAULT:
9027 	case RPL_REPORT_ALL:
9028 	case RPL_REPORT_NONSUBSID:
9029 		break;
9030 	case RPL_REPORT_WELLKNOWN:
9031 	case RPL_REPORT_ADMIN:
9032 	case RPL_REPORT_CONGLOM:
9033 		num_luns = 0;
9034 		break;
9035 	default:
9036 		ctl_set_invalid_field(ctsio,
9037 				      /*sks_valid*/ 1,
9038 				      /*command*/ 1,
9039 				      /*field*/ 2,
9040 				      /*bit_valid*/ 0,
9041 				      /*bit*/ 0);
9042 		ctl_done((union ctl_io *)ctsio);
9043 		return (retval);
9044 		break; /* NOTREACHED */
9045 	}
9046 
9047 	alloc_len = scsi_4btoul(cdb->length);
9048 	/*
9049 	 * The initiator has to allocate at least 16 bytes for this request,
9050 	 * so he can at least get the header and the first LUN.  Otherwise
9051 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9052 	 */
9053 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9054 	    sizeof(struct scsi_report_luns_lundata))) {
9055 		ctl_set_invalid_field(ctsio,
9056 				      /*sks_valid*/ 1,
9057 				      /*command*/ 1,
9058 				      /*field*/ 6,
9059 				      /*bit_valid*/ 0,
9060 				      /*bit*/ 0);
9061 		ctl_done((union ctl_io *)ctsio);
9062 		return (retval);
9063 	}
9064 
9065 	lun_datalen = sizeof(*lun_data) +
9066 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9067 
9068 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9069 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9070 	ctsio->kern_sg_entries = 0;
9071 
9072 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9073 
9074 	mtx_lock(&softc->ctl_lock);
9075 	for (targ_lun_id = 0, num_filled = 0;
9076 	    targ_lun_id < num_port_luns && num_filled < num_luns;
9077 	    targ_lun_id++) {
9078 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9079 		if (lun_id == UINT32_MAX)
9080 			continue;
9081 		lun = softc->ctl_luns[lun_id];
9082 		if (lun == NULL)
9083 			continue;
9084 
9085 		be64enc(lun_data->luns[num_filled++].lundata,
9086 		    ctl_encode_lun(targ_lun_id));
9087 
9088 		/*
9089 		 * According to SPC-3, rev 14 section 6.21:
9090 		 *
9091 		 * "The execution of a REPORT LUNS command to any valid and
9092 		 * installed logical unit shall clear the REPORTED LUNS DATA
9093 		 * HAS CHANGED unit attention condition for all logical
9094 		 * units of that target with respect to the requesting
9095 		 * initiator. A valid and installed logical unit is one
9096 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9097 		 * INQUIRY data (see 6.4.2)."
9098 		 *
9099 		 * If request_lun is NULL, the LUN this report luns command
9100 		 * was issued to is either disabled or doesn't exist. In that
9101 		 * case, we shouldn't clear any pending lun change unit
9102 		 * attention.
9103 		 */
9104 		if (request_lun != NULL) {
9105 			mtx_lock(&lun->lun_lock);
9106 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9107 			mtx_unlock(&lun->lun_lock);
9108 		}
9109 	}
9110 	mtx_unlock(&softc->ctl_lock);
9111 
9112 	/*
9113 	 * It's quite possible that we've returned fewer LUNs than we allocated
9114 	 * space for.  Trim it.
9115 	 */
9116 	lun_datalen = sizeof(*lun_data) +
9117 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9118 	ctsio->kern_rel_offset = 0;
9119 	ctsio->kern_sg_entries = 0;
9120 	ctsio->kern_data_len = min(lun_datalen, alloc_len);
9121 	ctsio->kern_total_len = ctsio->kern_data_len;
9122 
9123 	/*
9124 	 * We set this to the actual data length, regardless of how much
9125 	 * space we actually have to return results.  If the user looks at
9126 	 * this value, he'll know whether or not he allocated enough space
9127 	 * and reissue the command if necessary.  We don't support well
9128 	 * known logical units, so if the user asks for that, return none.
9129 	 */
9130 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9131 
9132 	/*
9133 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9134 	 * this request.
9135 	 */
9136 	ctl_set_success(ctsio);
9137 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9138 	ctsio->be_move_done = ctl_config_move_done;
9139 	ctl_datamove((union ctl_io *)ctsio);
9140 	return (retval);
9141 }
9142 
9143 int
9144 ctl_request_sense(struct ctl_scsiio *ctsio)
9145 {
9146 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9147 	struct ctl_lun *lun = CTL_LUN(ctsio);
9148 	struct scsi_request_sense *cdb;
9149 	struct scsi_sense_data *sense_ptr, *ps;
9150 	uint32_t initidx;
9151 	int have_error;
9152 	u_int sense_len = SSD_FULL_SIZE;
9153 	scsi_sense_data_type sense_format;
9154 	ctl_ua_type ua_type;
9155 	uint8_t asc = 0, ascq = 0;
9156 
9157 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9158 
9159 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9160 
9161 	/*
9162 	 * Determine which sense format the user wants.
9163 	 */
9164 	if (cdb->byte2 & SRS_DESC)
9165 		sense_format = SSD_TYPE_DESC;
9166 	else
9167 		sense_format = SSD_TYPE_FIXED;
9168 
9169 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9170 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9171 	ctsio->kern_sg_entries = 0;
9172 	ctsio->kern_rel_offset = 0;
9173 
9174 	/*
9175 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9176 	 * larger than the largest allowed value for the length field in the
9177 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9178 	 */
9179 	ctsio->kern_data_len = cdb->length;
9180 	ctsio->kern_total_len = cdb->length;
9181 
9182 	/*
9183 	 * If we don't have a LUN, we don't have any pending sense.
9184 	 */
9185 	if (lun == NULL ||
9186 	    ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
9187 	     softc->ha_link < CTL_HA_LINK_UNKNOWN)) {
9188 		/* "Logical unit not supported" */
9189 		ctl_set_sense_data(sense_ptr, &sense_len, NULL, sense_format,
9190 		    /*current_error*/ 1,
9191 		    /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
9192 		    /*asc*/ 0x25,
9193 		    /*ascq*/ 0x00,
9194 		    SSD_ELEM_NONE);
9195 		goto send;
9196 	}
9197 
9198 	have_error = 0;
9199 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9200 	/*
9201 	 * Check for pending sense, and then for pending unit attentions.
9202 	 * Pending sense gets returned first, then pending unit attentions.
9203 	 */
9204 	mtx_lock(&lun->lun_lock);
9205 	ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
9206 	if (ps != NULL)
9207 		ps += initidx % CTL_MAX_INIT_PER_PORT;
9208 	if (ps != NULL && ps->error_code != 0) {
9209 		scsi_sense_data_type stored_format;
9210 
9211 		/*
9212 		 * Check to see which sense format was used for the stored
9213 		 * sense data.
9214 		 */
9215 		stored_format = scsi_sense_type(ps);
9216 
9217 		/*
9218 		 * If the user requested a different sense format than the
9219 		 * one we stored, then we need to convert it to the other
9220 		 * format.  If we're going from descriptor to fixed format
9221 		 * sense data, we may lose things in translation, depending
9222 		 * on what options were used.
9223 		 *
9224 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9225 		 * for some reason we'll just copy it out as-is.
9226 		 */
9227 		if ((stored_format == SSD_TYPE_FIXED)
9228 		 && (sense_format == SSD_TYPE_DESC))
9229 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9230 			    ps, (struct scsi_sense_data_desc *)sense_ptr);
9231 		else if ((stored_format == SSD_TYPE_DESC)
9232 		      && (sense_format == SSD_TYPE_FIXED))
9233 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9234 			    ps, (struct scsi_sense_data_fixed *)sense_ptr);
9235 		else
9236 			memcpy(sense_ptr, ps, sizeof(*sense_ptr));
9237 
9238 		ps->error_code = 0;
9239 		have_error = 1;
9240 	} else {
9241 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, &sense_len,
9242 		    sense_format);
9243 		if (ua_type != CTL_UA_NONE)
9244 			have_error = 1;
9245 	}
9246 	if (have_error == 0) {
9247 		/*
9248 		 * Report informational exception if have one and allowed.
9249 		 */
9250 		if (lun->MODE_IE.mrie != SIEP_MRIE_NO) {
9251 			asc = lun->ie_asc;
9252 			ascq = lun->ie_ascq;
9253 		}
9254 		ctl_set_sense_data(sense_ptr, &sense_len, lun, sense_format,
9255 		    /*current_error*/ 1,
9256 		    /*sense_key*/ SSD_KEY_NO_SENSE,
9257 		    /*asc*/ asc,
9258 		    /*ascq*/ ascq,
9259 		    SSD_ELEM_NONE);
9260 	}
9261 	mtx_unlock(&lun->lun_lock);
9262 
9263 send:
9264 	/*
9265 	 * We report the SCSI status as OK, since the status of the command
9266 	 * itself is OK.  We're reporting sense as parameter data.
9267 	 */
9268 	ctl_set_success(ctsio);
9269 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9270 	ctsio->be_move_done = ctl_config_move_done;
9271 	ctl_datamove((union ctl_io *)ctsio);
9272 	return (CTL_RETVAL_COMPLETE);
9273 }
9274 
9275 int
9276 ctl_tur(struct ctl_scsiio *ctsio)
9277 {
9278 
9279 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9280 
9281 	ctl_set_success(ctsio);
9282 	ctl_done((union ctl_io *)ctsio);
9283 
9284 	return (CTL_RETVAL_COMPLETE);
9285 }
9286 
9287 /*
9288  * SCSI VPD page 0x00, the Supported VPD Pages page.
9289  */
9290 static int
9291 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9292 {
9293 	struct ctl_lun *lun = CTL_LUN(ctsio);
9294 	struct scsi_vpd_supported_pages *pages;
9295 	int sup_page_size;
9296 	int p;
9297 
9298 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9299 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9300 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9301 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9302 	ctsio->kern_rel_offset = 0;
9303 	ctsio->kern_sg_entries = 0;
9304 	ctsio->kern_data_len = min(sup_page_size, alloc_len);
9305 	ctsio->kern_total_len = ctsio->kern_data_len;
9306 
9307 	/*
9308 	 * The control device is always connected.  The disk device, on the
9309 	 * other hand, may not be online all the time.  Need to change this
9310 	 * to figure out whether the disk device is actually online or not.
9311 	 */
9312 	if (lun != NULL)
9313 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9314 				lun->be_lun->lun_type;
9315 	else
9316 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9317 
9318 	p = 0;
9319 	/* Supported VPD pages */
9320 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9321 	/* Serial Number */
9322 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9323 	/* Device Identification */
9324 	pages->page_list[p++] = SVPD_DEVICE_ID;
9325 	/* Extended INQUIRY Data */
9326 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9327 	/* Mode Page Policy */
9328 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9329 	/* SCSI Ports */
9330 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9331 	/* Third-party Copy */
9332 	pages->page_list[p++] = SVPD_SCSI_TPC;
9333 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9334 		/* Block limits */
9335 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9336 		/* Block Device Characteristics */
9337 		pages->page_list[p++] = SVPD_BDC;
9338 		/* Logical Block Provisioning */
9339 		pages->page_list[p++] = SVPD_LBP;
9340 	}
9341 	pages->length = p;
9342 
9343 	ctl_set_success(ctsio);
9344 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9345 	ctsio->be_move_done = ctl_config_move_done;
9346 	ctl_datamove((union ctl_io *)ctsio);
9347 	return (CTL_RETVAL_COMPLETE);
9348 }
9349 
9350 /*
9351  * SCSI VPD page 0x80, the Unit Serial Number page.
9352  */
9353 static int
9354 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9355 {
9356 	struct ctl_lun *lun = CTL_LUN(ctsio);
9357 	struct scsi_vpd_unit_serial_number *sn_ptr;
9358 	int data_len;
9359 
9360 	data_len = 4 + CTL_SN_LEN;
9361 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9362 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9363 	ctsio->kern_rel_offset = 0;
9364 	ctsio->kern_sg_entries = 0;
9365 	ctsio->kern_data_len = min(data_len, alloc_len);
9366 	ctsio->kern_total_len = ctsio->kern_data_len;
9367 
9368 	/*
9369 	 * The control device is always connected.  The disk device, on the
9370 	 * other hand, may not be online all the time.  Need to change this
9371 	 * to figure out whether the disk device is actually online or not.
9372 	 */
9373 	if (lun != NULL)
9374 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9375 				  lun->be_lun->lun_type;
9376 	else
9377 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9378 
9379 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9380 	sn_ptr->length = CTL_SN_LEN;
9381 	/*
9382 	 * If we don't have a LUN, we just leave the serial number as
9383 	 * all spaces.
9384 	 */
9385 	if (lun != NULL) {
9386 		strncpy((char *)sn_ptr->serial_num,
9387 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9388 	} else
9389 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9390 
9391 	ctl_set_success(ctsio);
9392 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9393 	ctsio->be_move_done = ctl_config_move_done;
9394 	ctl_datamove((union ctl_io *)ctsio);
9395 	return (CTL_RETVAL_COMPLETE);
9396 }
9397 
9398 
9399 /*
9400  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9401  */
9402 static int
9403 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9404 {
9405 	struct ctl_lun *lun = CTL_LUN(ctsio);
9406 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9407 	int data_len;
9408 
9409 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9410 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9411 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9412 	ctsio->kern_sg_entries = 0;
9413 	ctsio->kern_rel_offset = 0;
9414 	ctsio->kern_data_len = min(data_len, alloc_len);
9415 	ctsio->kern_total_len = ctsio->kern_data_len;
9416 
9417 	/*
9418 	 * The control device is always connected.  The disk device, on the
9419 	 * other hand, may not be online all the time.
9420 	 */
9421 	if (lun != NULL)
9422 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9423 				     lun->be_lun->lun_type;
9424 	else
9425 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9426 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9427 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9428 	/*
9429 	 * We support head of queue, ordered and simple tags.
9430 	 */
9431 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9432 	/*
9433 	 * Volatile cache supported.
9434 	 */
9435 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9436 
9437 	/*
9438 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9439 	 * attention for a particular IT nexus on all LUNs once we report
9440 	 * it to that nexus once.  This bit is required as of SPC-4.
9441 	 */
9442 	eid_ptr->flags4 = SVPD_EID_LUICLR;
9443 
9444 	/*
9445 	 * We support revert to defaults (RTD) bit in MODE SELECT.
9446 	 */
9447 	eid_ptr->flags5 = SVPD_EID_RTD_SUP;
9448 
9449 	/*
9450 	 * XXX KDM in order to correctly answer this, we would need
9451 	 * information from the SIM to determine how much sense data it
9452 	 * can send.  So this would really be a path inquiry field, most
9453 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9454 	 * but the hardware may or may not be able to support that much.
9455 	 * 0 just means that the maximum sense data length is not reported.
9456 	 */
9457 	eid_ptr->max_sense_length = 0;
9458 
9459 	ctl_set_success(ctsio);
9460 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9461 	ctsio->be_move_done = ctl_config_move_done;
9462 	ctl_datamove((union ctl_io *)ctsio);
9463 	return (CTL_RETVAL_COMPLETE);
9464 }
9465 
9466 static int
9467 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9468 {
9469 	struct ctl_lun *lun = CTL_LUN(ctsio);
9470 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9471 	int data_len;
9472 
9473 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9474 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9475 
9476 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9477 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9478 	ctsio->kern_rel_offset = 0;
9479 	ctsio->kern_sg_entries = 0;
9480 	ctsio->kern_data_len = min(data_len, alloc_len);
9481 	ctsio->kern_total_len = ctsio->kern_data_len;
9482 
9483 	/*
9484 	 * The control device is always connected.  The disk device, on the
9485 	 * other hand, may not be online all the time.
9486 	 */
9487 	if (lun != NULL)
9488 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9489 				     lun->be_lun->lun_type;
9490 	else
9491 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9492 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9493 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9494 	mpp_ptr->descr[0].page_code = 0x3f;
9495 	mpp_ptr->descr[0].subpage_code = 0xff;
9496 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9497 
9498 	ctl_set_success(ctsio);
9499 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9500 	ctsio->be_move_done = ctl_config_move_done;
9501 	ctl_datamove((union ctl_io *)ctsio);
9502 	return (CTL_RETVAL_COMPLETE);
9503 }
9504 
9505 /*
9506  * SCSI VPD page 0x83, the Device Identification page.
9507  */
9508 static int
9509 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9510 {
9511 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9512 	struct ctl_port *port = CTL_PORT(ctsio);
9513 	struct ctl_lun *lun = CTL_LUN(ctsio);
9514 	struct scsi_vpd_device_id *devid_ptr;
9515 	struct scsi_vpd_id_descriptor *desc;
9516 	int data_len, g;
9517 	uint8_t proto;
9518 
9519 	data_len = sizeof(struct scsi_vpd_device_id) +
9520 	    sizeof(struct scsi_vpd_id_descriptor) +
9521 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9522 	    sizeof(struct scsi_vpd_id_descriptor) +
9523 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9524 	if (lun && lun->lun_devid)
9525 		data_len += lun->lun_devid->len;
9526 	if (port && port->port_devid)
9527 		data_len += port->port_devid->len;
9528 	if (port && port->target_devid)
9529 		data_len += port->target_devid->len;
9530 
9531 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9532 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9533 	ctsio->kern_sg_entries = 0;
9534 	ctsio->kern_rel_offset = 0;
9535 	ctsio->kern_sg_entries = 0;
9536 	ctsio->kern_data_len = min(data_len, alloc_len);
9537 	ctsio->kern_total_len = ctsio->kern_data_len;
9538 
9539 	/*
9540 	 * The control device is always connected.  The disk device, on the
9541 	 * other hand, may not be online all the time.
9542 	 */
9543 	if (lun != NULL)
9544 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9545 				     lun->be_lun->lun_type;
9546 	else
9547 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9548 	devid_ptr->page_code = SVPD_DEVICE_ID;
9549 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9550 
9551 	if (port && port->port_type == CTL_PORT_FC)
9552 		proto = SCSI_PROTO_FC << 4;
9553 	else if (port && port->port_type == CTL_PORT_SAS)
9554 		proto = SCSI_PROTO_SAS << 4;
9555 	else if (port && port->port_type == CTL_PORT_ISCSI)
9556 		proto = SCSI_PROTO_ISCSI << 4;
9557 	else
9558 		proto = SCSI_PROTO_SPI << 4;
9559 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9560 
9561 	/*
9562 	 * We're using a LUN association here.  i.e., this device ID is a
9563 	 * per-LUN identifier.
9564 	 */
9565 	if (lun && lun->lun_devid) {
9566 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9567 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9568 		    lun->lun_devid->len);
9569 	}
9570 
9571 	/*
9572 	 * This is for the WWPN which is a port association.
9573 	 */
9574 	if (port && port->port_devid) {
9575 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9576 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9577 		    port->port_devid->len);
9578 	}
9579 
9580 	/*
9581 	 * This is for the Relative Target Port(type 4h) identifier
9582 	 */
9583 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9584 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9585 	    SVPD_ID_TYPE_RELTARG;
9586 	desc->length = 4;
9587 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9588 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9589 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9590 
9591 	/*
9592 	 * This is for the Target Port Group(type 5h) identifier
9593 	 */
9594 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9595 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9596 	    SVPD_ID_TYPE_TPORTGRP;
9597 	desc->length = 4;
9598 	if (softc->is_single ||
9599 	    (port && port->status & CTL_PORT_STATUS_HA_SHARED))
9600 		g = 1;
9601 	else
9602 		g = 2 + ctsio->io_hdr.nexus.targ_port / softc->port_cnt;
9603 	scsi_ulto2b(g, &desc->identifier[2]);
9604 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9605 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9606 
9607 	/*
9608 	 * This is for the Target identifier
9609 	 */
9610 	if (port && port->target_devid) {
9611 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9612 	}
9613 
9614 	ctl_set_success(ctsio);
9615 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9616 	ctsio->be_move_done = ctl_config_move_done;
9617 	ctl_datamove((union ctl_io *)ctsio);
9618 	return (CTL_RETVAL_COMPLETE);
9619 }
9620 
9621 static int
9622 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9623 {
9624 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9625 	struct ctl_lun *lun = CTL_LUN(ctsio);
9626 	struct scsi_vpd_scsi_ports *sp;
9627 	struct scsi_vpd_port_designation *pd;
9628 	struct scsi_vpd_port_designation_cont *pdc;
9629 	struct ctl_port *port;
9630 	int data_len, num_target_ports, iid_len, id_len;
9631 
9632 	num_target_ports = 0;
9633 	iid_len = 0;
9634 	id_len = 0;
9635 	mtx_lock(&softc->ctl_lock);
9636 	STAILQ_FOREACH(port, &softc->port_list, links) {
9637 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9638 			continue;
9639 		if (lun != NULL &&
9640 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9641 			continue;
9642 		num_target_ports++;
9643 		if (port->init_devid)
9644 			iid_len += port->init_devid->len;
9645 		if (port->port_devid)
9646 			id_len += port->port_devid->len;
9647 	}
9648 	mtx_unlock(&softc->ctl_lock);
9649 
9650 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9651 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9652 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9653 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9654 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9655 	ctsio->kern_sg_entries = 0;
9656 	ctsio->kern_rel_offset = 0;
9657 	ctsio->kern_sg_entries = 0;
9658 	ctsio->kern_data_len = min(data_len, alloc_len);
9659 	ctsio->kern_total_len = ctsio->kern_data_len;
9660 
9661 	/*
9662 	 * The control device is always connected.  The disk device, on the
9663 	 * other hand, may not be online all the time.  Need to change this
9664 	 * to figure out whether the disk device is actually online or not.
9665 	 */
9666 	if (lun != NULL)
9667 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9668 				  lun->be_lun->lun_type;
9669 	else
9670 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9671 
9672 	sp->page_code = SVPD_SCSI_PORTS;
9673 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9674 	    sp->page_length);
9675 	pd = &sp->design[0];
9676 
9677 	mtx_lock(&softc->ctl_lock);
9678 	STAILQ_FOREACH(port, &softc->port_list, links) {
9679 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9680 			continue;
9681 		if (lun != NULL &&
9682 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
9683 			continue;
9684 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9685 		if (port->init_devid) {
9686 			iid_len = port->init_devid->len;
9687 			memcpy(pd->initiator_transportid,
9688 			    port->init_devid->data, port->init_devid->len);
9689 		} else
9690 			iid_len = 0;
9691 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9692 		pdc = (struct scsi_vpd_port_designation_cont *)
9693 		    (&pd->initiator_transportid[iid_len]);
9694 		if (port->port_devid) {
9695 			id_len = port->port_devid->len;
9696 			memcpy(pdc->target_port_descriptors,
9697 			    port->port_devid->data, port->port_devid->len);
9698 		} else
9699 			id_len = 0;
9700 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9701 		pd = (struct scsi_vpd_port_designation *)
9702 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9703 	}
9704 	mtx_unlock(&softc->ctl_lock);
9705 
9706 	ctl_set_success(ctsio);
9707 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9708 	ctsio->be_move_done = ctl_config_move_done;
9709 	ctl_datamove((union ctl_io *)ctsio);
9710 	return (CTL_RETVAL_COMPLETE);
9711 }
9712 
9713 static int
9714 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9715 {
9716 	struct ctl_lun *lun = CTL_LUN(ctsio);
9717 	struct scsi_vpd_block_limits *bl_ptr;
9718 	uint64_t ival;
9719 
9720 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9721 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9722 	ctsio->kern_sg_entries = 0;
9723 	ctsio->kern_rel_offset = 0;
9724 	ctsio->kern_sg_entries = 0;
9725 	ctsio->kern_data_len = min(sizeof(*bl_ptr), alloc_len);
9726 	ctsio->kern_total_len = ctsio->kern_data_len;
9727 
9728 	/*
9729 	 * The control device is always connected.  The disk device, on the
9730 	 * other hand, may not be online all the time.  Need to change this
9731 	 * to figure out whether the disk device is actually online or not.
9732 	 */
9733 	if (lun != NULL)
9734 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9735 				  lun->be_lun->lun_type;
9736 	else
9737 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9738 
9739 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9740 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9741 	bl_ptr->max_cmp_write_len = 0xff;
9742 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9743 	if (lun != NULL) {
9744 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9745 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9746 			ival = 0xffffffff;
9747 			ctl_get_opt_number(&lun->be_lun->options,
9748 			    "unmap_max_lba", &ival);
9749 			scsi_ulto4b(ival, bl_ptr->max_unmap_lba_cnt);
9750 			ival = 0xffffffff;
9751 			ctl_get_opt_number(&lun->be_lun->options,
9752 			    "unmap_max_descr", &ival);
9753 			scsi_ulto4b(ival, bl_ptr->max_unmap_blk_cnt);
9754 			if (lun->be_lun->ublockexp != 0) {
9755 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9756 				    bl_ptr->opt_unmap_grain);
9757 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9758 				    bl_ptr->unmap_grain_align);
9759 			}
9760 		}
9761 		scsi_ulto4b(lun->be_lun->atomicblock,
9762 		    bl_ptr->max_atomic_transfer_length);
9763 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9764 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9765 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9766 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9767 		ival = UINT64_MAX;
9768 		ctl_get_opt_number(&lun->be_lun->options, "write_same_max_lba", &ival);
9769 		scsi_u64to8b(ival, bl_ptr->max_write_same_length);
9770 	}
9771 
9772 	ctl_set_success(ctsio);
9773 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9774 	ctsio->be_move_done = ctl_config_move_done;
9775 	ctl_datamove((union ctl_io *)ctsio);
9776 	return (CTL_RETVAL_COMPLETE);
9777 }
9778 
9779 static int
9780 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9781 {
9782 	struct ctl_lun *lun = CTL_LUN(ctsio);
9783 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9784 	const char *value;
9785 	u_int i;
9786 
9787 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9788 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9789 	ctsio->kern_sg_entries = 0;
9790 	ctsio->kern_rel_offset = 0;
9791 	ctsio->kern_data_len = min(sizeof(*bdc_ptr), alloc_len);
9792 	ctsio->kern_total_len = ctsio->kern_data_len;
9793 
9794 	/*
9795 	 * The control device is always connected.  The disk device, on the
9796 	 * other hand, may not be online all the time.  Need to change this
9797 	 * to figure out whether the disk device is actually online or not.
9798 	 */
9799 	if (lun != NULL)
9800 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9801 				  lun->be_lun->lun_type;
9802 	else
9803 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9804 	bdc_ptr->page_code = SVPD_BDC;
9805 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9806 	if (lun != NULL &&
9807 	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9808 		i = strtol(value, NULL, 0);
9809 	else
9810 		i = CTL_DEFAULT_ROTATION_RATE;
9811 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9812 	if (lun != NULL &&
9813 	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9814 		i = strtol(value, NULL, 0);
9815 	else
9816 		i = 0;
9817 	bdc_ptr->wab_wac_ff = (i & 0x0f);
9818 	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9819 
9820 	ctl_set_success(ctsio);
9821 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9822 	ctsio->be_move_done = ctl_config_move_done;
9823 	ctl_datamove((union ctl_io *)ctsio);
9824 	return (CTL_RETVAL_COMPLETE);
9825 }
9826 
9827 static int
9828 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9829 {
9830 	struct ctl_lun *lun = CTL_LUN(ctsio);
9831 	struct scsi_vpd_logical_block_prov *lbp_ptr;
9832 	const char *value;
9833 
9834 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9835 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9836 	ctsio->kern_sg_entries = 0;
9837 	ctsio->kern_rel_offset = 0;
9838 	ctsio->kern_data_len = min(sizeof(*lbp_ptr), alloc_len);
9839 	ctsio->kern_total_len = ctsio->kern_data_len;
9840 
9841 	/*
9842 	 * The control device is always connected.  The disk device, on the
9843 	 * other hand, may not be online all the time.  Need to change this
9844 	 * to figure out whether the disk device is actually online or not.
9845 	 */
9846 	if (lun != NULL)
9847 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9848 				  lun->be_lun->lun_type;
9849 	else
9850 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9851 
9852 	lbp_ptr->page_code = SVPD_LBP;
9853 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9854 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9855 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9856 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9857 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9858 		value = ctl_get_opt(&lun->be_lun->options, "provisioning_type");
9859 		if (value != NULL) {
9860 			if (strcmp(value, "resource") == 0)
9861 				lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
9862 			else if (strcmp(value, "thin") == 0)
9863 				lbp_ptr->prov_type = SVPD_LBP_THIN;
9864 		} else
9865 			lbp_ptr->prov_type = SVPD_LBP_THIN;
9866 	}
9867 
9868 	ctl_set_success(ctsio);
9869 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9870 	ctsio->be_move_done = ctl_config_move_done;
9871 	ctl_datamove((union ctl_io *)ctsio);
9872 	return (CTL_RETVAL_COMPLETE);
9873 }
9874 
9875 /*
9876  * INQUIRY with the EVPD bit set.
9877  */
9878 static int
9879 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9880 {
9881 	struct ctl_lun *lun = CTL_LUN(ctsio);
9882 	struct scsi_inquiry *cdb;
9883 	int alloc_len, retval;
9884 
9885 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9886 	alloc_len = scsi_2btoul(cdb->length);
9887 
9888 	switch (cdb->page_code) {
9889 	case SVPD_SUPPORTED_PAGES:
9890 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
9891 		break;
9892 	case SVPD_UNIT_SERIAL_NUMBER:
9893 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
9894 		break;
9895 	case SVPD_DEVICE_ID:
9896 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
9897 		break;
9898 	case SVPD_EXTENDED_INQUIRY_DATA:
9899 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
9900 		break;
9901 	case SVPD_MODE_PAGE_POLICY:
9902 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
9903 		break;
9904 	case SVPD_SCSI_PORTS:
9905 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
9906 		break;
9907 	case SVPD_SCSI_TPC:
9908 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
9909 		break;
9910 	case SVPD_BLOCK_LIMITS:
9911 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9912 			goto err;
9913 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
9914 		break;
9915 	case SVPD_BDC:
9916 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9917 			goto err;
9918 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
9919 		break;
9920 	case SVPD_LBP:
9921 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
9922 			goto err;
9923 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
9924 		break;
9925 	default:
9926 err:
9927 		ctl_set_invalid_field(ctsio,
9928 				      /*sks_valid*/ 1,
9929 				      /*command*/ 1,
9930 				      /*field*/ 2,
9931 				      /*bit_valid*/ 0,
9932 				      /*bit*/ 0);
9933 		ctl_done((union ctl_io *)ctsio);
9934 		retval = CTL_RETVAL_COMPLETE;
9935 		break;
9936 	}
9937 
9938 	return (retval);
9939 }
9940 
9941 /*
9942  * Standard INQUIRY data.
9943  */
9944 static int
9945 ctl_inquiry_std(struct ctl_scsiio *ctsio)
9946 {
9947 	struct ctl_softc *softc = CTL_SOFTC(ctsio);
9948 	struct ctl_port *port = CTL_PORT(ctsio);
9949 	struct ctl_lun *lun = CTL_LUN(ctsio);
9950 	struct scsi_inquiry_data *inq_ptr;
9951 	struct scsi_inquiry *cdb;
9952 	char *val;
9953 	uint32_t alloc_len, data_len;
9954 	ctl_port_type port_type;
9955 
9956 	port_type = port->port_type;
9957 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
9958 		port_type = CTL_PORT_SCSI;
9959 
9960 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9961 	alloc_len = scsi_2btoul(cdb->length);
9962 
9963 	/*
9964 	 * We malloc the full inquiry data size here and fill it
9965 	 * in.  If the user only asks for less, we'll give him
9966 	 * that much.
9967 	 */
9968 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
9969 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9970 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
9971 	ctsio->kern_sg_entries = 0;
9972 	ctsio->kern_rel_offset = 0;
9973 	ctsio->kern_data_len = min(data_len, alloc_len);
9974 	ctsio->kern_total_len = ctsio->kern_data_len;
9975 
9976 	if (lun != NULL) {
9977 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
9978 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
9979 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9980 			    lun->be_lun->lun_type;
9981 		} else {
9982 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
9983 			    lun->be_lun->lun_type;
9984 		}
9985 		if (lun->flags & CTL_LUN_REMOVABLE)
9986 			inq_ptr->dev_qual2 |= SID_RMB;
9987 	} else
9988 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
9989 
9990 	/* RMB in byte 2 is 0 */
9991 	inq_ptr->version = SCSI_REV_SPC5;
9992 
9993 	/*
9994 	 * According to SAM-3, even if a device only supports a single
9995 	 * level of LUN addressing, it should still set the HISUP bit:
9996 	 *
9997 	 * 4.9.1 Logical unit numbers overview
9998 	 *
9999 	 * All logical unit number formats described in this standard are
10000 	 * hierarchical in structure even when only a single level in that
10001 	 * hierarchy is used. The HISUP bit shall be set to one in the
10002 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10003 	 * format described in this standard is used.  Non-hierarchical
10004 	 * formats are outside the scope of this standard.
10005 	 *
10006 	 * Therefore we set the HiSup bit here.
10007 	 *
10008 	 * The response format is 2, per SPC-3.
10009 	 */
10010 	inq_ptr->response_format = SID_HiSup | 2;
10011 
10012 	inq_ptr->additional_length = data_len -
10013 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10014 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10015 			 inq_ptr->additional_length));
10016 
10017 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10018 	if (port_type == CTL_PORT_SCSI)
10019 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10020 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10021 	inq_ptr->flags = SID_CmdQue;
10022 	if (port_type == CTL_PORT_SCSI)
10023 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10024 
10025 	/*
10026 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10027 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10028 	 * name and 4 bytes for the revision.
10029 	 */
10030 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10031 	    "vendor")) == NULL) {
10032 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10033 	} else {
10034 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10035 		strncpy(inq_ptr->vendor, val,
10036 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10037 	}
10038 	if (lun == NULL) {
10039 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10040 		    sizeof(inq_ptr->product));
10041 	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10042 		switch (lun->be_lun->lun_type) {
10043 		case T_DIRECT:
10044 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10045 			    sizeof(inq_ptr->product));
10046 			break;
10047 		case T_PROCESSOR:
10048 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10049 			    sizeof(inq_ptr->product));
10050 			break;
10051 		case T_CDROM:
10052 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10053 			    sizeof(inq_ptr->product));
10054 			break;
10055 		default:
10056 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10057 			    sizeof(inq_ptr->product));
10058 			break;
10059 		}
10060 	} else {
10061 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10062 		strncpy(inq_ptr->product, val,
10063 		    min(sizeof(inq_ptr->product), strlen(val)));
10064 	}
10065 
10066 	/*
10067 	 * XXX make this a macro somewhere so it automatically gets
10068 	 * incremented when we make changes.
10069 	 */
10070 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10071 	    "revision")) == NULL) {
10072 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10073 	} else {
10074 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10075 		strncpy(inq_ptr->revision, val,
10076 		    min(sizeof(inq_ptr->revision), strlen(val)));
10077 	}
10078 
10079 	/*
10080 	 * For parallel SCSI, we support double transition and single
10081 	 * transition clocking.  We also support QAS (Quick Arbitration
10082 	 * and Selection) and Information Unit transfers on both the
10083 	 * control and array devices.
10084 	 */
10085 	if (port_type == CTL_PORT_SCSI)
10086 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10087 				    SID_SPI_IUS;
10088 
10089 	/* SAM-6 (no version claimed) */
10090 	scsi_ulto2b(0x00C0, inq_ptr->version1);
10091 	/* SPC-5 (no version claimed) */
10092 	scsi_ulto2b(0x05C0, inq_ptr->version2);
10093 	if (port_type == CTL_PORT_FC) {
10094 		/* FCP-2 ANSI INCITS.350:2003 */
10095 		scsi_ulto2b(0x0917, inq_ptr->version3);
10096 	} else if (port_type == CTL_PORT_SCSI) {
10097 		/* SPI-4 ANSI INCITS.362:200x */
10098 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10099 	} else if (port_type == CTL_PORT_ISCSI) {
10100 		/* iSCSI (no version claimed) */
10101 		scsi_ulto2b(0x0960, inq_ptr->version3);
10102 	} else if (port_type == CTL_PORT_SAS) {
10103 		/* SAS (no version claimed) */
10104 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10105 	} else if (port_type == CTL_PORT_UMASS) {
10106 		/* USB Mass Storage Class Bulk-Only Transport, Revision 1.0 */
10107 		scsi_ulto2b(0x1730, inq_ptr->version3);
10108 	}
10109 
10110 	if (lun == NULL) {
10111 		/* SBC-4 (no version claimed) */
10112 		scsi_ulto2b(0x0600, inq_ptr->version4);
10113 	} else {
10114 		switch (lun->be_lun->lun_type) {
10115 		case T_DIRECT:
10116 			/* SBC-4 (no version claimed) */
10117 			scsi_ulto2b(0x0600, inq_ptr->version4);
10118 			break;
10119 		case T_PROCESSOR:
10120 			break;
10121 		case T_CDROM:
10122 			/* MMC-6 (no version claimed) */
10123 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10124 			break;
10125 		default:
10126 			break;
10127 		}
10128 	}
10129 
10130 	ctl_set_success(ctsio);
10131 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10132 	ctsio->be_move_done = ctl_config_move_done;
10133 	ctl_datamove((union ctl_io *)ctsio);
10134 	return (CTL_RETVAL_COMPLETE);
10135 }
10136 
10137 int
10138 ctl_inquiry(struct ctl_scsiio *ctsio)
10139 {
10140 	struct scsi_inquiry *cdb;
10141 	int retval;
10142 
10143 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10144 
10145 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10146 	if (cdb->byte2 & SI_EVPD)
10147 		retval = ctl_inquiry_evpd(ctsio);
10148 	else if (cdb->page_code == 0)
10149 		retval = ctl_inquiry_std(ctsio);
10150 	else {
10151 		ctl_set_invalid_field(ctsio,
10152 				      /*sks_valid*/ 1,
10153 				      /*command*/ 1,
10154 				      /*field*/ 2,
10155 				      /*bit_valid*/ 0,
10156 				      /*bit*/ 0);
10157 		ctl_done((union ctl_io *)ctsio);
10158 		return (CTL_RETVAL_COMPLETE);
10159 	}
10160 
10161 	return (retval);
10162 }
10163 
10164 int
10165 ctl_get_config(struct ctl_scsiio *ctsio)
10166 {
10167 	struct ctl_lun *lun = CTL_LUN(ctsio);
10168 	struct scsi_get_config_header *hdr;
10169 	struct scsi_get_config_feature *feature;
10170 	struct scsi_get_config *cdb;
10171 	uint32_t alloc_len, data_len;
10172 	int rt, starting;
10173 
10174 	cdb = (struct scsi_get_config *)ctsio->cdb;
10175 	rt = (cdb->rt & SGC_RT_MASK);
10176 	starting = scsi_2btoul(cdb->starting_feature);
10177 	alloc_len = scsi_2btoul(cdb->length);
10178 
10179 	data_len = sizeof(struct scsi_get_config_header) +
10180 	    sizeof(struct scsi_get_config_feature) + 8 +
10181 	    sizeof(struct scsi_get_config_feature) + 8 +
10182 	    sizeof(struct scsi_get_config_feature) + 4 +
10183 	    sizeof(struct scsi_get_config_feature) + 4 +
10184 	    sizeof(struct scsi_get_config_feature) + 8 +
10185 	    sizeof(struct scsi_get_config_feature) +
10186 	    sizeof(struct scsi_get_config_feature) + 4 +
10187 	    sizeof(struct scsi_get_config_feature) + 4 +
10188 	    sizeof(struct scsi_get_config_feature) + 4 +
10189 	    sizeof(struct scsi_get_config_feature) + 4 +
10190 	    sizeof(struct scsi_get_config_feature) + 4 +
10191 	    sizeof(struct scsi_get_config_feature) + 4;
10192 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10193 	ctsio->kern_sg_entries = 0;
10194 	ctsio->kern_rel_offset = 0;
10195 
10196 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10197 	if (lun->flags & CTL_LUN_NO_MEDIA)
10198 		scsi_ulto2b(0x0000, hdr->current_profile);
10199 	else
10200 		scsi_ulto2b(0x0010, hdr->current_profile);
10201 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10202 
10203 	if (starting > 0x003b)
10204 		goto done;
10205 	if (starting > 0x003a)
10206 		goto f3b;
10207 	if (starting > 0x002b)
10208 		goto f3a;
10209 	if (starting > 0x002a)
10210 		goto f2b;
10211 	if (starting > 0x001f)
10212 		goto f2a;
10213 	if (starting > 0x001e)
10214 		goto f1f;
10215 	if (starting > 0x001d)
10216 		goto f1e;
10217 	if (starting > 0x0010)
10218 		goto f1d;
10219 	if (starting > 0x0003)
10220 		goto f10;
10221 	if (starting > 0x0002)
10222 		goto f3;
10223 	if (starting > 0x0001)
10224 		goto f2;
10225 	if (starting > 0x0000)
10226 		goto f1;
10227 
10228 	/* Profile List */
10229 	scsi_ulto2b(0x0000, feature->feature_code);
10230 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10231 	feature->add_length = 8;
10232 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10233 	feature->feature_data[2] = 0x00;
10234 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10235 	feature->feature_data[6] = 0x01;
10236 	feature = (struct scsi_get_config_feature *)
10237 	    &feature->feature_data[feature->add_length];
10238 
10239 f1:	/* Core */
10240 	scsi_ulto2b(0x0001, feature->feature_code);
10241 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10242 	feature->add_length = 8;
10243 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10244 	feature->feature_data[4] = 0x03;
10245 	feature = (struct scsi_get_config_feature *)
10246 	    &feature->feature_data[feature->add_length];
10247 
10248 f2:	/* Morphing */
10249 	scsi_ulto2b(0x0002, feature->feature_code);
10250 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10251 	feature->add_length = 4;
10252 	feature->feature_data[0] = 0x02;
10253 	feature = (struct scsi_get_config_feature *)
10254 	    &feature->feature_data[feature->add_length];
10255 
10256 f3:	/* Removable Medium */
10257 	scsi_ulto2b(0x0003, feature->feature_code);
10258 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10259 	feature->add_length = 4;
10260 	feature->feature_data[0] = 0x39;
10261 	feature = (struct scsi_get_config_feature *)
10262 	    &feature->feature_data[feature->add_length];
10263 
10264 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10265 		goto done;
10266 
10267 f10:	/* Random Read */
10268 	scsi_ulto2b(0x0010, feature->feature_code);
10269 	feature->flags = 0x00;
10270 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10271 		feature->flags |= SGC_F_CURRENT;
10272 	feature->add_length = 8;
10273 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10274 	scsi_ulto2b(1, &feature->feature_data[4]);
10275 	feature->feature_data[6] = 0x00;
10276 	feature = (struct scsi_get_config_feature *)
10277 	    &feature->feature_data[feature->add_length];
10278 
10279 f1d:	/* Multi-Read */
10280 	scsi_ulto2b(0x001D, 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 = 0;
10285 	feature = (struct scsi_get_config_feature *)
10286 	    &feature->feature_data[feature->add_length];
10287 
10288 f1e:	/* CD Read */
10289 	scsi_ulto2b(0x001E, feature->feature_code);
10290 	feature->flags = 0x00;
10291 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10292 		feature->flags |= SGC_F_CURRENT;
10293 	feature->add_length = 4;
10294 	feature->feature_data[0] = 0x00;
10295 	feature = (struct scsi_get_config_feature *)
10296 	    &feature->feature_data[feature->add_length];
10297 
10298 f1f:	/* DVD Read */
10299 	scsi_ulto2b(0x001F, feature->feature_code);
10300 	feature->flags = 0x08;
10301 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10302 		feature->flags |= SGC_F_CURRENT;
10303 	feature->add_length = 4;
10304 	feature->feature_data[0] = 0x01;
10305 	feature->feature_data[2] = 0x03;
10306 	feature = (struct scsi_get_config_feature *)
10307 	    &feature->feature_data[feature->add_length];
10308 
10309 f2a:	/* DVD+RW */
10310 	scsi_ulto2b(0x002A, feature->feature_code);
10311 	feature->flags = 0x04;
10312 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10313 		feature->flags |= SGC_F_CURRENT;
10314 	feature->add_length = 4;
10315 	feature->feature_data[0] = 0x00;
10316 	feature->feature_data[1] = 0x00;
10317 	feature = (struct scsi_get_config_feature *)
10318 	    &feature->feature_data[feature->add_length];
10319 
10320 f2b:	/* DVD+R */
10321 	scsi_ulto2b(0x002B, feature->feature_code);
10322 	feature->flags = 0x00;
10323 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10324 		feature->flags |= SGC_F_CURRENT;
10325 	feature->add_length = 4;
10326 	feature->feature_data[0] = 0x00;
10327 	feature = (struct scsi_get_config_feature *)
10328 	    &feature->feature_data[feature->add_length];
10329 
10330 f3a:	/* DVD+RW Dual Layer */
10331 	scsi_ulto2b(0x003A, feature->feature_code);
10332 	feature->flags = 0x00;
10333 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10334 		feature->flags |= SGC_F_CURRENT;
10335 	feature->add_length = 4;
10336 	feature->feature_data[0] = 0x00;
10337 	feature->feature_data[1] = 0x00;
10338 	feature = (struct scsi_get_config_feature *)
10339 	    &feature->feature_data[feature->add_length];
10340 
10341 f3b:	/* DVD+R Dual Layer */
10342 	scsi_ulto2b(0x003B, feature->feature_code);
10343 	feature->flags = 0x00;
10344 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10345 		feature->flags |= SGC_F_CURRENT;
10346 	feature->add_length = 4;
10347 	feature->feature_data[0] = 0x00;
10348 	feature = (struct scsi_get_config_feature *)
10349 	    &feature->feature_data[feature->add_length];
10350 
10351 done:
10352 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10353 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10354 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10355 		if (scsi_2btoul(feature->feature_code) == starting)
10356 			feature = (struct scsi_get_config_feature *)
10357 			    &feature->feature_data[feature->add_length];
10358 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10359 	}
10360 	scsi_ulto4b(data_len - 4, hdr->data_length);
10361 	ctsio->kern_data_len = min(data_len, alloc_len);
10362 	ctsio->kern_total_len = ctsio->kern_data_len;
10363 
10364 	ctl_set_success(ctsio);
10365 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10366 	ctsio->be_move_done = ctl_config_move_done;
10367 	ctl_datamove((union ctl_io *)ctsio);
10368 	return (CTL_RETVAL_COMPLETE);
10369 }
10370 
10371 int
10372 ctl_get_event_status(struct ctl_scsiio *ctsio)
10373 {
10374 	struct scsi_get_event_status_header *hdr;
10375 	struct scsi_get_event_status *cdb;
10376 	uint32_t alloc_len, data_len;
10377 	int notif_class;
10378 
10379 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10380 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10381 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10382 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10383 		ctl_done((union ctl_io *)ctsio);
10384 		return (CTL_RETVAL_COMPLETE);
10385 	}
10386 	notif_class = cdb->notif_class;
10387 	alloc_len = scsi_2btoul(cdb->length);
10388 
10389 	data_len = sizeof(struct scsi_get_event_status_header);
10390 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10391 	ctsio->kern_sg_entries = 0;
10392 	ctsio->kern_rel_offset = 0;
10393 	ctsio->kern_data_len = min(data_len, alloc_len);
10394 	ctsio->kern_total_len = ctsio->kern_data_len;
10395 
10396 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10397 	scsi_ulto2b(0, hdr->descr_length);
10398 	hdr->nea_class = SGESN_NEA;
10399 	hdr->supported_class = 0;
10400 
10401 	ctl_set_success(ctsio);
10402 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10403 	ctsio->be_move_done = ctl_config_move_done;
10404 	ctl_datamove((union ctl_io *)ctsio);
10405 	return (CTL_RETVAL_COMPLETE);
10406 }
10407 
10408 int
10409 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10410 {
10411 	struct scsi_mechanism_status_header *hdr;
10412 	struct scsi_mechanism_status *cdb;
10413 	uint32_t alloc_len, data_len;
10414 
10415 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10416 	alloc_len = scsi_2btoul(cdb->length);
10417 
10418 	data_len = sizeof(struct scsi_mechanism_status_header);
10419 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10420 	ctsio->kern_sg_entries = 0;
10421 	ctsio->kern_rel_offset = 0;
10422 	ctsio->kern_data_len = min(data_len, alloc_len);
10423 	ctsio->kern_total_len = ctsio->kern_data_len;
10424 
10425 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10426 	hdr->state1 = 0x00;
10427 	hdr->state2 = 0xe0;
10428 	scsi_ulto3b(0, hdr->lba);
10429 	hdr->slots_num = 0;
10430 	scsi_ulto2b(0, hdr->slots_length);
10431 
10432 	ctl_set_success(ctsio);
10433 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10434 	ctsio->be_move_done = ctl_config_move_done;
10435 	ctl_datamove((union ctl_io *)ctsio);
10436 	return (CTL_RETVAL_COMPLETE);
10437 }
10438 
10439 static void
10440 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10441 {
10442 
10443 	lba += 150;
10444 	buf[0] = 0;
10445 	buf[1] = bin2bcd((lba / 75) / 60);
10446 	buf[2] = bin2bcd((lba / 75) % 60);
10447 	buf[3] = bin2bcd(lba % 75);
10448 }
10449 
10450 int
10451 ctl_read_toc(struct ctl_scsiio *ctsio)
10452 {
10453 	struct ctl_lun *lun = CTL_LUN(ctsio);
10454 	struct scsi_read_toc_hdr *hdr;
10455 	struct scsi_read_toc_type01_descr *descr;
10456 	struct scsi_read_toc *cdb;
10457 	uint32_t alloc_len, data_len;
10458 	int format, msf;
10459 
10460 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10461 	msf = (cdb->byte2 & CD_MSF) != 0;
10462 	format = cdb->format;
10463 	alloc_len = scsi_2btoul(cdb->data_len);
10464 
10465 	data_len = sizeof(struct scsi_read_toc_hdr);
10466 	if (format == 0)
10467 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10468 	else
10469 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10470 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10471 	ctsio->kern_sg_entries = 0;
10472 	ctsio->kern_rel_offset = 0;
10473 	ctsio->kern_data_len = min(data_len, alloc_len);
10474 	ctsio->kern_total_len = ctsio->kern_data_len;
10475 
10476 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10477 	if (format == 0) {
10478 		scsi_ulto2b(0x12, hdr->data_length);
10479 		hdr->first = 1;
10480 		hdr->last = 1;
10481 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10482 		descr->addr_ctl = 0x14;
10483 		descr->track_number = 1;
10484 		if (msf)
10485 			ctl_ultomsf(0, descr->track_start);
10486 		else
10487 			scsi_ulto4b(0, descr->track_start);
10488 		descr++;
10489 		descr->addr_ctl = 0x14;
10490 		descr->track_number = 0xaa;
10491 		if (msf)
10492 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10493 		else
10494 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10495 	} else {
10496 		scsi_ulto2b(0x0a, hdr->data_length);
10497 		hdr->first = 1;
10498 		hdr->last = 1;
10499 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10500 		descr->addr_ctl = 0x14;
10501 		descr->track_number = 1;
10502 		if (msf)
10503 			ctl_ultomsf(0, descr->track_start);
10504 		else
10505 			scsi_ulto4b(0, descr->track_start);
10506 	}
10507 
10508 	ctl_set_success(ctsio);
10509 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10510 	ctsio->be_move_done = ctl_config_move_done;
10511 	ctl_datamove((union ctl_io *)ctsio);
10512 	return (CTL_RETVAL_COMPLETE);
10513 }
10514 
10515 /*
10516  * For known CDB types, parse the LBA and length.
10517  */
10518 static int
10519 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10520 {
10521 	if (io->io_hdr.io_type != CTL_IO_SCSI)
10522 		return (1);
10523 
10524 	switch (io->scsiio.cdb[0]) {
10525 	case COMPARE_AND_WRITE: {
10526 		struct scsi_compare_and_write *cdb;
10527 
10528 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10529 
10530 		*lba = scsi_8btou64(cdb->addr);
10531 		*len = cdb->length;
10532 		break;
10533 	}
10534 	case READ_6:
10535 	case WRITE_6: {
10536 		struct scsi_rw_6 *cdb;
10537 
10538 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10539 
10540 		*lba = scsi_3btoul(cdb->addr);
10541 		/* only 5 bits are valid in the most significant address byte */
10542 		*lba &= 0x1fffff;
10543 		*len = cdb->length;
10544 		break;
10545 	}
10546 	case READ_10:
10547 	case WRITE_10: {
10548 		struct scsi_rw_10 *cdb;
10549 
10550 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10551 
10552 		*lba = scsi_4btoul(cdb->addr);
10553 		*len = scsi_2btoul(cdb->length);
10554 		break;
10555 	}
10556 	case WRITE_VERIFY_10: {
10557 		struct scsi_write_verify_10 *cdb;
10558 
10559 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10560 
10561 		*lba = scsi_4btoul(cdb->addr);
10562 		*len = scsi_2btoul(cdb->length);
10563 		break;
10564 	}
10565 	case READ_12:
10566 	case WRITE_12: {
10567 		struct scsi_rw_12 *cdb;
10568 
10569 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10570 
10571 		*lba = scsi_4btoul(cdb->addr);
10572 		*len = scsi_4btoul(cdb->length);
10573 		break;
10574 	}
10575 	case WRITE_VERIFY_12: {
10576 		struct scsi_write_verify_12 *cdb;
10577 
10578 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10579 
10580 		*lba = scsi_4btoul(cdb->addr);
10581 		*len = scsi_4btoul(cdb->length);
10582 		break;
10583 	}
10584 	case READ_16:
10585 	case WRITE_16: {
10586 		struct scsi_rw_16 *cdb;
10587 
10588 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10589 
10590 		*lba = scsi_8btou64(cdb->addr);
10591 		*len = scsi_4btoul(cdb->length);
10592 		break;
10593 	}
10594 	case WRITE_ATOMIC_16: {
10595 		struct scsi_write_atomic_16 *cdb;
10596 
10597 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10598 
10599 		*lba = scsi_8btou64(cdb->addr);
10600 		*len = scsi_2btoul(cdb->length);
10601 		break;
10602 	}
10603 	case WRITE_VERIFY_16: {
10604 		struct scsi_write_verify_16 *cdb;
10605 
10606 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10607 
10608 		*lba = scsi_8btou64(cdb->addr);
10609 		*len = scsi_4btoul(cdb->length);
10610 		break;
10611 	}
10612 	case WRITE_SAME_10: {
10613 		struct scsi_write_same_10 *cdb;
10614 
10615 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10616 
10617 		*lba = scsi_4btoul(cdb->addr);
10618 		*len = scsi_2btoul(cdb->length);
10619 		break;
10620 	}
10621 	case WRITE_SAME_16: {
10622 		struct scsi_write_same_16 *cdb;
10623 
10624 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10625 
10626 		*lba = scsi_8btou64(cdb->addr);
10627 		*len = scsi_4btoul(cdb->length);
10628 		break;
10629 	}
10630 	case VERIFY_10: {
10631 		struct scsi_verify_10 *cdb;
10632 
10633 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10634 
10635 		*lba = scsi_4btoul(cdb->addr);
10636 		*len = scsi_2btoul(cdb->length);
10637 		break;
10638 	}
10639 	case VERIFY_12: {
10640 		struct scsi_verify_12 *cdb;
10641 
10642 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10643 
10644 		*lba = scsi_4btoul(cdb->addr);
10645 		*len = scsi_4btoul(cdb->length);
10646 		break;
10647 	}
10648 	case VERIFY_16: {
10649 		struct scsi_verify_16 *cdb;
10650 
10651 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10652 
10653 		*lba = scsi_8btou64(cdb->addr);
10654 		*len = scsi_4btoul(cdb->length);
10655 		break;
10656 	}
10657 	case UNMAP: {
10658 		*lba = 0;
10659 		*len = UINT64_MAX;
10660 		break;
10661 	}
10662 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10663 		struct scsi_get_lba_status *cdb;
10664 
10665 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10666 		*lba = scsi_8btou64(cdb->addr);
10667 		*len = UINT32_MAX;
10668 		break;
10669 	}
10670 	default:
10671 		return (1);
10672 		break; /* NOTREACHED */
10673 	}
10674 
10675 	return (0);
10676 }
10677 
10678 static ctl_action
10679 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10680     bool seq)
10681 {
10682 	uint64_t endlba1, endlba2;
10683 
10684 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10685 	endlba2 = lba2 + len2 - 1;
10686 
10687 	if ((endlba1 < lba2) || (endlba2 < lba1))
10688 		return (CTL_ACTION_PASS);
10689 	else
10690 		return (CTL_ACTION_BLOCK);
10691 }
10692 
10693 static int
10694 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10695 {
10696 	struct ctl_ptr_len_flags *ptrlen;
10697 	struct scsi_unmap_desc *buf, *end, *range;
10698 	uint64_t lba;
10699 	uint32_t len;
10700 
10701 	/* If not UNMAP -- go other way. */
10702 	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10703 	    io->scsiio.cdb[0] != UNMAP)
10704 		return (CTL_ACTION_ERROR);
10705 
10706 	/* If UNMAP without data -- block and wait for data. */
10707 	ptrlen = (struct ctl_ptr_len_flags *)
10708 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10709 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10710 	    ptrlen->ptr == NULL)
10711 		return (CTL_ACTION_BLOCK);
10712 
10713 	/* UNMAP with data -- check for collision. */
10714 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10715 	end = buf + ptrlen->len / sizeof(*buf);
10716 	for (range = buf; range < end; range++) {
10717 		lba = scsi_8btou64(range->lba);
10718 		len = scsi_4btoul(range->length);
10719 		if ((lba < lba2 + len2) && (lba + len > lba2))
10720 			return (CTL_ACTION_BLOCK);
10721 	}
10722 	return (CTL_ACTION_PASS);
10723 }
10724 
10725 static ctl_action
10726 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10727 {
10728 	uint64_t lba1, lba2;
10729 	uint64_t len1, len2;
10730 	int retval;
10731 
10732 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10733 		return (CTL_ACTION_ERROR);
10734 
10735 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10736 	if (retval != CTL_ACTION_ERROR)
10737 		return (retval);
10738 
10739 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10740 		return (CTL_ACTION_ERROR);
10741 
10742 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10743 		seq = FALSE;
10744 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10745 }
10746 
10747 static ctl_action
10748 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10749 {
10750 	uint64_t lba1, lba2;
10751 	uint64_t len1, len2;
10752 
10753 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10754 		return (CTL_ACTION_PASS);
10755 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10756 		return (CTL_ACTION_ERROR);
10757 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10758 		return (CTL_ACTION_ERROR);
10759 
10760 	if (lba1 + len1 == lba2)
10761 		return (CTL_ACTION_BLOCK);
10762 	return (CTL_ACTION_PASS);
10763 }
10764 
10765 static ctl_action
10766 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10767     union ctl_io *ooa_io)
10768 {
10769 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10770 	const ctl_serialize_action *serialize_row;
10771 
10772 	/*
10773 	 * The initiator attempted multiple untagged commands at the same
10774 	 * time.  Can't do that.
10775 	 */
10776 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10777 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10778 	 && ((pending_io->io_hdr.nexus.targ_port ==
10779 	      ooa_io->io_hdr.nexus.targ_port)
10780 	  && (pending_io->io_hdr.nexus.initid ==
10781 	      ooa_io->io_hdr.nexus.initid))
10782 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10783 	      CTL_FLAG_STATUS_SENT)) == 0))
10784 		return (CTL_ACTION_OVERLAP);
10785 
10786 	/*
10787 	 * The initiator attempted to send multiple tagged commands with
10788 	 * the same ID.  (It's fine if different initiators have the same
10789 	 * tag ID.)
10790 	 *
10791 	 * Even if all of those conditions are true, we don't kill the I/O
10792 	 * if the command ahead of us has been aborted.  We won't end up
10793 	 * sending it to the FETD, and it's perfectly legal to resend a
10794 	 * command with the same tag number as long as the previous
10795 	 * instance of this tag number has been aborted somehow.
10796 	 */
10797 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10798 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10799 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10800 	 && ((pending_io->io_hdr.nexus.targ_port ==
10801 	      ooa_io->io_hdr.nexus.targ_port)
10802 	  && (pending_io->io_hdr.nexus.initid ==
10803 	      ooa_io->io_hdr.nexus.initid))
10804 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10805 	      CTL_FLAG_STATUS_SENT)) == 0))
10806 		return (CTL_ACTION_OVERLAP_TAG);
10807 
10808 	/*
10809 	 * If we get a head of queue tag, SAM-3 says that we should
10810 	 * immediately execute it.
10811 	 *
10812 	 * What happens if this command would normally block for some other
10813 	 * reason?  e.g. a request sense with a head of queue tag
10814 	 * immediately after a write.  Normally that would block, but this
10815 	 * will result in its getting executed immediately...
10816 	 *
10817 	 * We currently return "pass" instead of "skip", so we'll end up
10818 	 * going through the rest of the queue to check for overlapped tags.
10819 	 *
10820 	 * XXX KDM check for other types of blockage first??
10821 	 */
10822 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10823 		return (CTL_ACTION_PASS);
10824 
10825 	/*
10826 	 * Ordered tags have to block until all items ahead of them
10827 	 * have completed.  If we get called with an ordered tag, we always
10828 	 * block, if something else is ahead of us in the queue.
10829 	 */
10830 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10831 		return (CTL_ACTION_BLOCK);
10832 
10833 	/*
10834 	 * Simple tags get blocked until all head of queue and ordered tags
10835 	 * ahead of them have completed.  I'm lumping untagged commands in
10836 	 * with simple tags here.  XXX KDM is that the right thing to do?
10837 	 */
10838 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10839 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
10840 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10841 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
10842 		return (CTL_ACTION_BLOCK);
10843 
10844 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
10845 	KASSERT(pending_entry->seridx < CTL_SERIDX_COUNT,
10846 	    ("%s: Invalid seridx %d for pending CDB %02x %02x @ %p",
10847 	     __func__, pending_entry->seridx, pending_io->scsiio.cdb[0],
10848 	     pending_io->scsiio.cdb[1], pending_io));
10849 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
10850 	if (ooa_entry->seridx == CTL_SERIDX_INVLD)
10851 		return (CTL_ACTION_PASS); /* Unsupported command in OOA queue */
10852 	KASSERT(ooa_entry->seridx < CTL_SERIDX_COUNT,
10853 	    ("%s: Invalid seridx %d for ooa CDB %02x %02x @ %p",
10854 	     __func__, ooa_entry->seridx, ooa_io->scsiio.cdb[0],
10855 	     ooa_io->scsiio.cdb[1], ooa_io));
10856 
10857 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
10858 
10859 	switch (serialize_row[pending_entry->seridx]) {
10860 	case CTL_SER_BLOCK:
10861 		return (CTL_ACTION_BLOCK);
10862 	case CTL_SER_EXTENT:
10863 		return (ctl_extent_check(ooa_io, pending_io,
10864 		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10865 	case CTL_SER_EXTENTOPT:
10866 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
10867 		    SCP_QUEUE_ALG_UNRESTRICTED)
10868 			return (ctl_extent_check(ooa_io, pending_io,
10869 			    (lun->be_lun &&
10870 			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
10871 		return (CTL_ACTION_PASS);
10872 	case CTL_SER_EXTENTSEQ:
10873 		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
10874 			return (ctl_extent_check_seq(ooa_io, pending_io));
10875 		return (CTL_ACTION_PASS);
10876 	case CTL_SER_PASS:
10877 		return (CTL_ACTION_PASS);
10878 	case CTL_SER_BLOCKOPT:
10879 		if ((lun->MODE_CTRL.queue_flags & SCP_QUEUE_ALG_MASK) !=
10880 		    SCP_QUEUE_ALG_UNRESTRICTED)
10881 			return (CTL_ACTION_BLOCK);
10882 		return (CTL_ACTION_PASS);
10883 	case CTL_SER_SKIP:
10884 		return (CTL_ACTION_SKIP);
10885 	default:
10886 		panic("%s: Invalid serialization value %d for %d => %d",
10887 		    __func__, serialize_row[pending_entry->seridx],
10888 		    pending_entry->seridx, ooa_entry->seridx);
10889 	}
10890 
10891 	return (CTL_ACTION_ERROR);
10892 }
10893 
10894 /*
10895  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
10896  * Assumptions:
10897  * - pending_io is generally either incoming, or on the blocked queue
10898  * - starting I/O is the I/O we want to start the check with.
10899  */
10900 static ctl_action
10901 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
10902 	      union ctl_io *starting_io)
10903 {
10904 	union ctl_io *ooa_io;
10905 	ctl_action action;
10906 
10907 	mtx_assert(&lun->lun_lock, MA_OWNED);
10908 
10909 	/*
10910 	 * Run back along the OOA queue, starting with the current
10911 	 * blocked I/O and going through every I/O before it on the
10912 	 * queue.  If starting_io is NULL, we'll just end up returning
10913 	 * CTL_ACTION_PASS.
10914 	 */
10915 	for (ooa_io = starting_io; ooa_io != NULL;
10916 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
10917 	     ooa_links)){
10918 
10919 		/*
10920 		 * This routine just checks to see whether
10921 		 * cur_blocked is blocked by ooa_io, which is ahead
10922 		 * of it in the queue.  It doesn't queue/dequeue
10923 		 * cur_blocked.
10924 		 */
10925 		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
10926 		switch (action) {
10927 		case CTL_ACTION_BLOCK:
10928 		case CTL_ACTION_OVERLAP:
10929 		case CTL_ACTION_OVERLAP_TAG:
10930 		case CTL_ACTION_SKIP:
10931 		case CTL_ACTION_ERROR:
10932 			return (action);
10933 			break; /* NOTREACHED */
10934 		case CTL_ACTION_PASS:
10935 			break;
10936 		default:
10937 			panic("%s: Invalid action %d\n", __func__, action);
10938 		}
10939 	}
10940 
10941 	return (CTL_ACTION_PASS);
10942 }
10943 
10944 /*
10945  * Assumptions:
10946  * - An I/O has just completed, and has been removed from the per-LUN OOA
10947  *   queue, so some items on the blocked queue may now be unblocked.
10948  */
10949 static int
10950 ctl_check_blocked(struct ctl_lun *lun)
10951 {
10952 	struct ctl_softc *softc = lun->ctl_softc;
10953 	union ctl_io *cur_blocked, *next_blocked;
10954 
10955 	mtx_assert(&lun->lun_lock, MA_OWNED);
10956 
10957 	/*
10958 	 * Run forward from the head of the blocked queue, checking each
10959 	 * entry against the I/Os prior to it on the OOA queue to see if
10960 	 * there is still any blockage.
10961 	 *
10962 	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
10963 	 * with our removing a variable on it while it is traversing the
10964 	 * list.
10965 	 */
10966 	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
10967 	     cur_blocked != NULL; cur_blocked = next_blocked) {
10968 		union ctl_io *prev_ooa;
10969 		ctl_action action;
10970 
10971 		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
10972 							  blocked_links);
10973 
10974 		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
10975 						      ctl_ooaq, ooa_links);
10976 
10977 		/*
10978 		 * If cur_blocked happens to be the first item in the OOA
10979 		 * queue now, prev_ooa will be NULL, and the action
10980 		 * returned will just be CTL_ACTION_PASS.
10981 		 */
10982 		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
10983 
10984 		switch (action) {
10985 		case CTL_ACTION_BLOCK:
10986 			/* Nothing to do here, still blocked */
10987 			break;
10988 		case CTL_ACTION_OVERLAP:
10989 		case CTL_ACTION_OVERLAP_TAG:
10990 			/*
10991 			 * This shouldn't happen!  In theory we've already
10992 			 * checked this command for overlap...
10993 			 */
10994 			break;
10995 		case CTL_ACTION_PASS:
10996 		case CTL_ACTION_SKIP: {
10997 			const struct ctl_cmd_entry *entry;
10998 
10999 			/*
11000 			 * The skip case shouldn't happen, this transaction
11001 			 * should have never made it onto the blocked queue.
11002 			 */
11003 			/*
11004 			 * This I/O is no longer blocked, we can remove it
11005 			 * from the blocked queue.  Since this is a TAILQ
11006 			 * (doubly linked list), we can do O(1) removals
11007 			 * from any place on the list.
11008 			 */
11009 			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11010 				     blocked_links);
11011 			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11012 
11013 			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11014 			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11015 				/*
11016 				 * Need to send IO back to original side to
11017 				 * run
11018 				 */
11019 				union ctl_ha_msg msg_info;
11020 
11021 				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11022 				msg_info.hdr.original_sc =
11023 					cur_blocked->io_hdr.original_sc;
11024 				msg_info.hdr.serializing_sc = cur_blocked;
11025 				msg_info.hdr.msg_type = CTL_MSG_R2R;
11026 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11027 				    sizeof(msg_info.hdr), M_NOWAIT);
11028 				break;
11029 			}
11030 			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11031 
11032 			/*
11033 			 * Check this I/O for LUN state changes that may
11034 			 * have happened while this command was blocked.
11035 			 * The LUN state may have been changed by a command
11036 			 * ahead of us in the queue, so we need to re-check
11037 			 * for any states that can be caused by SCSI
11038 			 * commands.
11039 			 */
11040 			if (ctl_scsiio_lun_check(lun, entry,
11041 						 &cur_blocked->scsiio) == 0) {
11042 				cur_blocked->io_hdr.flags |=
11043 				                      CTL_FLAG_IS_WAS_ON_RTR;
11044 				ctl_enqueue_rtr(cur_blocked);
11045 			} else
11046 				ctl_done(cur_blocked);
11047 			break;
11048 		}
11049 		default:
11050 			/*
11051 			 * This probably shouldn't happen -- we shouldn't
11052 			 * get CTL_ACTION_ERROR, or anything else.
11053 			 */
11054 			break;
11055 		}
11056 	}
11057 
11058 	return (CTL_RETVAL_COMPLETE);
11059 }
11060 
11061 /*
11062  * This routine (with one exception) checks LUN flags that can be set by
11063  * commands ahead of us in the OOA queue.  These flags have to be checked
11064  * when a command initially comes in, and when we pull a command off the
11065  * blocked queue and are preparing to execute it.  The reason we have to
11066  * check these flags for commands on the blocked queue is that the LUN
11067  * state may have been changed by a command ahead of us while we're on the
11068  * blocked queue.
11069  *
11070  * Ordering is somewhat important with these checks, so please pay
11071  * careful attention to the placement of any new checks.
11072  */
11073 static int
11074 ctl_scsiio_lun_check(struct ctl_lun *lun,
11075     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11076 {
11077 	struct ctl_softc *softc = lun->ctl_softc;
11078 	int retval;
11079 	uint32_t residx;
11080 
11081 	retval = 0;
11082 
11083 	mtx_assert(&lun->lun_lock, MA_OWNED);
11084 
11085 	/*
11086 	 * If this shelf is a secondary shelf controller, we may have to
11087 	 * reject some commands disallowed by HA mode and link state.
11088 	 */
11089 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11090 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11091 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11092 			ctl_set_lun_unavail(ctsio);
11093 			retval = 1;
11094 			goto bailout;
11095 		}
11096 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11097 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11098 			ctl_set_lun_transit(ctsio);
11099 			retval = 1;
11100 			goto bailout;
11101 		}
11102 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11103 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11104 			ctl_set_lun_standby(ctsio);
11105 			retval = 1;
11106 			goto bailout;
11107 		}
11108 
11109 		/* The rest of checks are only done on executing side */
11110 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11111 			goto bailout;
11112 	}
11113 
11114 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11115 		if (lun->be_lun &&
11116 		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11117 			ctl_set_hw_write_protected(ctsio);
11118 			retval = 1;
11119 			goto bailout;
11120 		}
11121 		if ((lun->MODE_CTRL.eca_and_aen & SCP_SWP) != 0) {
11122 			ctl_set_sense(ctsio, /*current_error*/ 1,
11123 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11124 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11125 			retval = 1;
11126 			goto bailout;
11127 		}
11128 	}
11129 
11130 	/*
11131 	 * Check for a reservation conflict.  If this command isn't allowed
11132 	 * even on reserved LUNs, and if this initiator isn't the one who
11133 	 * reserved us, reject the command with a reservation conflict.
11134 	 */
11135 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11136 	if ((lun->flags & CTL_LUN_RESERVED)
11137 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11138 		if (lun->res_idx != residx) {
11139 			ctl_set_reservation_conflict(ctsio);
11140 			retval = 1;
11141 			goto bailout;
11142 		}
11143 	}
11144 
11145 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11146 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11147 		/* No reservation or command is allowed. */;
11148 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11149 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11150 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11151 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11152 		/* The command is allowed for Write Exclusive resv. */;
11153 	} else {
11154 		/*
11155 		 * if we aren't registered or it's a res holder type
11156 		 * reservation and this isn't the res holder then set a
11157 		 * conflict.
11158 		 */
11159 		if (ctl_get_prkey(lun, residx) == 0 ||
11160 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11161 			ctl_set_reservation_conflict(ctsio);
11162 			retval = 1;
11163 			goto bailout;
11164 		}
11165 	}
11166 
11167 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11168 		if (lun->flags & CTL_LUN_EJECTED)
11169 			ctl_set_lun_ejected(ctsio);
11170 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11171 			if (lun->flags & CTL_LUN_REMOVABLE)
11172 				ctl_set_lun_no_media(ctsio);
11173 			else
11174 				ctl_set_lun_int_reqd(ctsio);
11175 		} else if (lun->flags & CTL_LUN_STOPPED)
11176 			ctl_set_lun_stopped(ctsio);
11177 		else
11178 			goto bailout;
11179 		retval = 1;
11180 		goto bailout;
11181 	}
11182 
11183 bailout:
11184 	return (retval);
11185 }
11186 
11187 static void
11188 ctl_failover_io(union ctl_io *io, int have_lock)
11189 {
11190 	ctl_set_busy(&io->scsiio);
11191 	ctl_done(io);
11192 }
11193 
11194 static void
11195 ctl_failover_lun(union ctl_io *rio)
11196 {
11197 	struct ctl_softc *softc = CTL_SOFTC(rio);
11198 	struct ctl_lun *lun;
11199 	struct ctl_io_hdr *io, *next_io;
11200 	uint32_t targ_lun;
11201 
11202 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11203 	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11204 
11205 	/* Find and lock the LUN. */
11206 	mtx_lock(&softc->ctl_lock);
11207 	if (targ_lun > CTL_MAX_LUNS ||
11208 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11209 		mtx_unlock(&softc->ctl_lock);
11210 		return;
11211 	}
11212 	mtx_lock(&lun->lun_lock);
11213 	mtx_unlock(&softc->ctl_lock);
11214 	if (lun->flags & CTL_LUN_DISABLED) {
11215 		mtx_unlock(&lun->lun_lock);
11216 		return;
11217 	}
11218 
11219 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11220 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11221 			/* We are master */
11222 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11223 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11224 					io->flags |= CTL_FLAG_ABORT;
11225 					io->flags |= CTL_FLAG_FAILOVER;
11226 				} else { /* This can be only due to DATAMOVE */
11227 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11228 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11229 					io->flags |= CTL_FLAG_IO_ACTIVE;
11230 					io->port_status = 31340;
11231 					ctl_enqueue_isc((union ctl_io *)io);
11232 				}
11233 			}
11234 			/* We are slave */
11235 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11236 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11237 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11238 					io->flags |= CTL_FLAG_FAILOVER;
11239 				} else {
11240 					ctl_set_busy(&((union ctl_io *)io)->
11241 					    scsiio);
11242 					ctl_done((union ctl_io *)io);
11243 				}
11244 			}
11245 		}
11246 	} else { /* SERIALIZE modes */
11247 		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11248 		    next_io) {
11249 			/* We are master */
11250 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11251 				TAILQ_REMOVE(&lun->blocked_queue, io,
11252 				    blocked_links);
11253 				io->flags &= ~CTL_FLAG_BLOCKED;
11254 				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11255 				ctl_free_io((union ctl_io *)io);
11256 			}
11257 		}
11258 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11259 			/* We are master */
11260 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11261 				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11262 				ctl_free_io((union ctl_io *)io);
11263 			}
11264 			/* We are slave */
11265 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11266 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11267 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11268 					ctl_set_busy(&((union ctl_io *)io)->
11269 					    scsiio);
11270 					ctl_done((union ctl_io *)io);
11271 				}
11272 			}
11273 		}
11274 		ctl_check_blocked(lun);
11275 	}
11276 	mtx_unlock(&lun->lun_lock);
11277 }
11278 
11279 static int
11280 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11281 {
11282 	struct ctl_lun *lun;
11283 	const struct ctl_cmd_entry *entry;
11284 	uint32_t initidx, targ_lun;
11285 	int retval = 0;
11286 
11287 	lun = NULL;
11288 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11289 	if (targ_lun < CTL_MAX_LUNS)
11290 		lun = softc->ctl_luns[targ_lun];
11291 	if (lun) {
11292 		/*
11293 		 * If the LUN is invalid, pretend that it doesn't exist.
11294 		 * It will go away as soon as all pending I/O has been
11295 		 * completed.
11296 		 */
11297 		mtx_lock(&lun->lun_lock);
11298 		if (lun->flags & CTL_LUN_DISABLED) {
11299 			mtx_unlock(&lun->lun_lock);
11300 			lun = NULL;
11301 		}
11302 	}
11303 	CTL_LUN(ctsio) = lun;
11304 	if (lun) {
11305 		CTL_BACKEND_LUN(ctsio) = lun->be_lun;
11306 
11307 		/*
11308 		 * Every I/O goes into the OOA queue for a particular LUN,
11309 		 * and stays there until completion.
11310 		 */
11311 #ifdef CTL_TIME_IO
11312 		if (TAILQ_EMPTY(&lun->ooa_queue))
11313 			lun->idle_time += getsbinuptime() - lun->last_busy;
11314 #endif
11315 		TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
11316 	}
11317 
11318 	/* Get command entry and return error if it is unsuppotyed. */
11319 	entry = ctl_validate_command(ctsio);
11320 	if (entry == NULL) {
11321 		if (lun)
11322 			mtx_unlock(&lun->lun_lock);
11323 		return (retval);
11324 	}
11325 
11326 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11327 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11328 
11329 	/*
11330 	 * Check to see whether we can send this command to LUNs that don't
11331 	 * exist.  This should pretty much only be the case for inquiry
11332 	 * and request sense.  Further checks, below, really require having
11333 	 * a LUN, so we can't really check the command anymore.  Just put
11334 	 * it on the rtr queue.
11335 	 */
11336 	if (lun == NULL) {
11337 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11338 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11339 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11340 			return (retval);
11341 		}
11342 
11343 		ctl_set_unsupported_lun(ctsio);
11344 		ctl_done((union ctl_io *)ctsio);
11345 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11346 		return (retval);
11347 	} else {
11348 		/*
11349 		 * Make sure we support this particular command on this LUN.
11350 		 * e.g., we don't support writes to the control LUN.
11351 		 */
11352 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11353 			mtx_unlock(&lun->lun_lock);
11354 			ctl_set_invalid_opcode(ctsio);
11355 			ctl_done((union ctl_io *)ctsio);
11356 			return (retval);
11357 		}
11358 	}
11359 
11360 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11361 
11362 	/*
11363 	 * If we've got a request sense, it'll clear the contingent
11364 	 * allegiance condition.  Otherwise, if we have a CA condition for
11365 	 * this initiator, clear it, because it sent down a command other
11366 	 * than request sense.
11367 	 */
11368 	if (ctsio->cdb[0] != REQUEST_SENSE) {
11369 		struct scsi_sense_data *ps;
11370 
11371 		ps = lun->pending_sense[initidx / CTL_MAX_INIT_PER_PORT];
11372 		if (ps != NULL)
11373 			ps[initidx % CTL_MAX_INIT_PER_PORT].error_code = 0;
11374 	}
11375 
11376 	/*
11377 	 * If the command has this flag set, it handles its own unit
11378 	 * attention reporting, we shouldn't do anything.  Otherwise we
11379 	 * check for any pending unit attentions, and send them back to the
11380 	 * initiator.  We only do this when a command initially comes in,
11381 	 * not when we pull it off the blocked queue.
11382 	 *
11383 	 * According to SAM-3, section 5.3.2, the order that things get
11384 	 * presented back to the host is basically unit attentions caused
11385 	 * by some sort of reset event, busy status, reservation conflicts
11386 	 * or task set full, and finally any other status.
11387 	 *
11388 	 * One issue here is that some of the unit attentions we report
11389 	 * don't fall into the "reset" category (e.g. "reported luns data
11390 	 * has changed").  So reporting it here, before the reservation
11391 	 * check, may be technically wrong.  I guess the only thing to do
11392 	 * would be to check for and report the reset events here, and then
11393 	 * check for the other unit attention types after we check for a
11394 	 * reservation conflict.
11395 	 *
11396 	 * XXX KDM need to fix this
11397 	 */
11398 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11399 		ctl_ua_type ua_type;
11400 		u_int sense_len = 0;
11401 
11402 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11403 		    &sense_len, SSD_TYPE_NONE);
11404 		if (ua_type != CTL_UA_NONE) {
11405 			mtx_unlock(&lun->lun_lock);
11406 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11407 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11408 			ctsio->sense_len = sense_len;
11409 			ctl_done((union ctl_io *)ctsio);
11410 			return (retval);
11411 		}
11412 	}
11413 
11414 
11415 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11416 		mtx_unlock(&lun->lun_lock);
11417 		ctl_done((union ctl_io *)ctsio);
11418 		return (retval);
11419 	}
11420 
11421 	/*
11422 	 * XXX CHD this is where we want to send IO to other side if
11423 	 * this LUN is secondary on this SC. We will need to make a copy
11424 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11425 	 * the copy we send as FROM_OTHER.
11426 	 * We also need to stuff the address of the original IO so we can
11427 	 * find it easily. Something similar will need be done on the other
11428 	 * side so when we are done we can find the copy.
11429 	 */
11430 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11431 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11432 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11433 		union ctl_ha_msg msg_info;
11434 		int isc_retval;
11435 
11436 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11437 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11438 		mtx_unlock(&lun->lun_lock);
11439 
11440 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11441 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11442 		msg_info.hdr.serializing_sc = NULL;
11443 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11444 		msg_info.scsi.tag_num = ctsio->tag_num;
11445 		msg_info.scsi.tag_type = ctsio->tag_type;
11446 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11447 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11448 
11449 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11450 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11451 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11452 			ctl_set_busy(ctsio);
11453 			ctl_done((union ctl_io *)ctsio);
11454 			return (retval);
11455 		}
11456 		return (retval);
11457 	}
11458 
11459 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11460 			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11461 			      ctl_ooaq, ooa_links))) {
11462 	case CTL_ACTION_BLOCK:
11463 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11464 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11465 				  blocked_links);
11466 		mtx_unlock(&lun->lun_lock);
11467 		return (retval);
11468 	case CTL_ACTION_PASS:
11469 	case CTL_ACTION_SKIP:
11470 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11471 		mtx_unlock(&lun->lun_lock);
11472 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11473 		break;
11474 	case CTL_ACTION_OVERLAP:
11475 		mtx_unlock(&lun->lun_lock);
11476 		ctl_set_overlapped_cmd(ctsio);
11477 		ctl_done((union ctl_io *)ctsio);
11478 		break;
11479 	case CTL_ACTION_OVERLAP_TAG:
11480 		mtx_unlock(&lun->lun_lock);
11481 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11482 		ctl_done((union ctl_io *)ctsio);
11483 		break;
11484 	case CTL_ACTION_ERROR:
11485 	default:
11486 		mtx_unlock(&lun->lun_lock);
11487 		ctl_set_internal_failure(ctsio,
11488 					 /*sks_valid*/ 0,
11489 					 /*retry_count*/ 0);
11490 		ctl_done((union ctl_io *)ctsio);
11491 		break;
11492 	}
11493 	return (retval);
11494 }
11495 
11496 const struct ctl_cmd_entry *
11497 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11498 {
11499 	const struct ctl_cmd_entry *entry;
11500 	int service_action;
11501 
11502 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11503 	if (sa)
11504 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11505 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11506 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11507 		entry = &((const struct ctl_cmd_entry *)
11508 		    entry->execute)[service_action];
11509 	}
11510 	return (entry);
11511 }
11512 
11513 const struct ctl_cmd_entry *
11514 ctl_validate_command(struct ctl_scsiio *ctsio)
11515 {
11516 	const struct ctl_cmd_entry *entry;
11517 	int i, sa;
11518 	uint8_t diff;
11519 
11520 	entry = ctl_get_cmd_entry(ctsio, &sa);
11521 	if (entry->execute == NULL) {
11522 		if (sa)
11523 			ctl_set_invalid_field(ctsio,
11524 					      /*sks_valid*/ 1,
11525 					      /*command*/ 1,
11526 					      /*field*/ 1,
11527 					      /*bit_valid*/ 1,
11528 					      /*bit*/ 4);
11529 		else
11530 			ctl_set_invalid_opcode(ctsio);
11531 		ctl_done((union ctl_io *)ctsio);
11532 		return (NULL);
11533 	}
11534 	KASSERT(entry->length > 0,
11535 	    ("Not defined length for command 0x%02x/0x%02x",
11536 	     ctsio->cdb[0], ctsio->cdb[1]));
11537 	for (i = 1; i < entry->length; i++) {
11538 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11539 		if (diff == 0)
11540 			continue;
11541 		ctl_set_invalid_field(ctsio,
11542 				      /*sks_valid*/ 1,
11543 				      /*command*/ 1,
11544 				      /*field*/ i,
11545 				      /*bit_valid*/ 1,
11546 				      /*bit*/ fls(diff) - 1);
11547 		ctl_done((union ctl_io *)ctsio);
11548 		return (NULL);
11549 	}
11550 	return (entry);
11551 }
11552 
11553 static int
11554 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11555 {
11556 
11557 	switch (lun_type) {
11558 	case T_DIRECT:
11559 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11560 			return (0);
11561 		break;
11562 	case T_PROCESSOR:
11563 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11564 			return (0);
11565 		break;
11566 	case T_CDROM:
11567 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11568 			return (0);
11569 		break;
11570 	default:
11571 		return (0);
11572 	}
11573 	return (1);
11574 }
11575 
11576 static int
11577 ctl_scsiio(struct ctl_scsiio *ctsio)
11578 {
11579 	int retval;
11580 	const struct ctl_cmd_entry *entry;
11581 
11582 	retval = CTL_RETVAL_COMPLETE;
11583 
11584 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11585 
11586 	entry = ctl_get_cmd_entry(ctsio, NULL);
11587 
11588 	/*
11589 	 * If this I/O has been aborted, just send it straight to
11590 	 * ctl_done() without executing it.
11591 	 */
11592 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11593 		ctl_done((union ctl_io *)ctsio);
11594 		goto bailout;
11595 	}
11596 
11597 	/*
11598 	 * All the checks should have been handled by ctl_scsiio_precheck().
11599 	 * We should be clear now to just execute the I/O.
11600 	 */
11601 	retval = entry->execute(ctsio);
11602 
11603 bailout:
11604 	return (retval);
11605 }
11606 
11607 static int
11608 ctl_target_reset(union ctl_io *io)
11609 {
11610 	struct ctl_softc *softc = CTL_SOFTC(io);
11611 	struct ctl_port *port = CTL_PORT(io);
11612 	struct ctl_lun *lun;
11613 	uint32_t initidx;
11614 	ctl_ua_type ua_type;
11615 
11616 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11617 		union ctl_ha_msg msg_info;
11618 
11619 		msg_info.hdr.nexus = io->io_hdr.nexus;
11620 		msg_info.task.task_action = io->taskio.task_action;
11621 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11622 		msg_info.hdr.original_sc = NULL;
11623 		msg_info.hdr.serializing_sc = NULL;
11624 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11625 		    sizeof(msg_info.task), M_WAITOK);
11626 	}
11627 
11628 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11629 	if (io->taskio.task_action == CTL_TASK_TARGET_RESET)
11630 		ua_type = CTL_UA_TARG_RESET;
11631 	else
11632 		ua_type = CTL_UA_BUS_RESET;
11633 	mtx_lock(&softc->ctl_lock);
11634 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11635 		if (port != NULL &&
11636 		    ctl_lun_map_to_port(port, lun->lun) == UINT32_MAX)
11637 			continue;
11638 		ctl_do_lun_reset(lun, initidx, ua_type);
11639 	}
11640 	mtx_unlock(&softc->ctl_lock);
11641 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11642 	return (0);
11643 }
11644 
11645 /*
11646  * The LUN should always be set.  The I/O is optional, and is used to
11647  * distinguish between I/Os sent by this initiator, and by other
11648  * initiators.  We set unit attention for initiators other than this one.
11649  * SAM-3 is vague on this point.  It does say that a unit attention should
11650  * be established for other initiators when a LUN is reset (see section
11651  * 5.7.3), but it doesn't specifically say that the unit attention should
11652  * be established for this particular initiator when a LUN is reset.  Here
11653  * is the relevant text, from SAM-3 rev 8:
11654  *
11655  * 5.7.2 When a SCSI initiator port aborts its own tasks
11656  *
11657  * When a SCSI initiator port causes its own task(s) to be aborted, no
11658  * notification that the task(s) have been aborted shall be returned to
11659  * the SCSI initiator port other than the completion response for the
11660  * command or task management function action that caused the task(s) to
11661  * be aborted and notification(s) associated with related effects of the
11662  * action (e.g., a reset unit attention condition).
11663  *
11664  * XXX KDM for now, we're setting unit attention for all initiators.
11665  */
11666 static void
11667 ctl_do_lun_reset(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua_type)
11668 {
11669 	union ctl_io *xio;
11670 	int i;
11671 
11672 	mtx_lock(&lun->lun_lock);
11673 	/* Abort tasks. */
11674 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11675 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11676 		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11677 	}
11678 	/* Clear CA. */
11679 	for (i = 0; i < CTL_MAX_PORTS; i++) {
11680 		free(lun->pending_sense[i], M_CTL);
11681 		lun->pending_sense[i] = NULL;
11682 	}
11683 	/* Clear reservation. */
11684 	lun->flags &= ~CTL_LUN_RESERVED;
11685 	/* Clear prevent media removal. */
11686 	if (lun->prevent) {
11687 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
11688 			ctl_clear_mask(lun->prevent, i);
11689 		lun->prevent_count = 0;
11690 	}
11691 	/* Clear TPC status */
11692 	ctl_tpc_lun_clear(lun, -1);
11693 	/* Establish UA. */
11694 #if 0
11695 	ctl_est_ua_all(lun, initidx, ua_type);
11696 #else
11697 	ctl_est_ua_all(lun, -1, ua_type);
11698 #endif
11699 	mtx_unlock(&lun->lun_lock);
11700 }
11701 
11702 static int
11703 ctl_lun_reset(union ctl_io *io)
11704 {
11705 	struct ctl_softc *softc = CTL_SOFTC(io);
11706 	struct ctl_lun *lun;
11707 	uint32_t targ_lun, initidx;
11708 
11709 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11710 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11711 	mtx_lock(&softc->ctl_lock);
11712 	if (targ_lun >= CTL_MAX_LUNS ||
11713 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11714 		mtx_unlock(&softc->ctl_lock);
11715 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11716 		return (1);
11717 	}
11718 	ctl_do_lun_reset(lun, initidx, CTL_UA_LUN_RESET);
11719 	mtx_unlock(&softc->ctl_lock);
11720 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11721 
11722 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11723 		union ctl_ha_msg msg_info;
11724 
11725 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11726 		msg_info.hdr.nexus = io->io_hdr.nexus;
11727 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11728 		msg_info.hdr.original_sc = NULL;
11729 		msg_info.hdr.serializing_sc = NULL;
11730 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11731 		    sizeof(msg_info.task), M_WAITOK);
11732 	}
11733 	return (0);
11734 }
11735 
11736 static void
11737 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11738     int other_sc)
11739 {
11740 	union ctl_io *xio;
11741 
11742 	mtx_assert(&lun->lun_lock, MA_OWNED);
11743 
11744 	/*
11745 	 * Run through the OOA queue and attempt to find the given I/O.
11746 	 * The target port, initiator ID, tag type and tag number have to
11747 	 * match the values that we got from the initiator.  If we have an
11748 	 * untagged command to abort, simply abort the first untagged command
11749 	 * we come to.  We only allow one untagged command at a time of course.
11750 	 */
11751 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11752 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11753 
11754 		if ((targ_port == UINT32_MAX ||
11755 		     targ_port == xio->io_hdr.nexus.targ_port) &&
11756 		    (init_id == UINT32_MAX ||
11757 		     init_id == xio->io_hdr.nexus.initid)) {
11758 			if (targ_port != xio->io_hdr.nexus.targ_port ||
11759 			    init_id != xio->io_hdr.nexus.initid)
11760 				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11761 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11762 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11763 				union ctl_ha_msg msg_info;
11764 
11765 				msg_info.hdr.nexus = xio->io_hdr.nexus;
11766 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11767 				msg_info.task.tag_num = xio->scsiio.tag_num;
11768 				msg_info.task.tag_type = xio->scsiio.tag_type;
11769 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11770 				msg_info.hdr.original_sc = NULL;
11771 				msg_info.hdr.serializing_sc = NULL;
11772 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11773 				    sizeof(msg_info.task), M_NOWAIT);
11774 			}
11775 		}
11776 	}
11777 }
11778 
11779 static int
11780 ctl_abort_task_set(union ctl_io *io)
11781 {
11782 	struct ctl_softc *softc = CTL_SOFTC(io);
11783 	struct ctl_lun *lun;
11784 	uint32_t targ_lun;
11785 
11786 	/*
11787 	 * Look up the LUN.
11788 	 */
11789 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11790 	mtx_lock(&softc->ctl_lock);
11791 	if (targ_lun >= CTL_MAX_LUNS ||
11792 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11793 		mtx_unlock(&softc->ctl_lock);
11794 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11795 		return (1);
11796 	}
11797 
11798 	mtx_lock(&lun->lun_lock);
11799 	mtx_unlock(&softc->ctl_lock);
11800 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11801 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11802 		    io->io_hdr.nexus.initid,
11803 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11804 	} else { /* CTL_TASK_CLEAR_TASK_SET */
11805 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11806 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11807 	}
11808 	mtx_unlock(&lun->lun_lock);
11809 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11810 	return (0);
11811 }
11812 
11813 static void
11814 ctl_i_t_nexus_loss(struct ctl_softc *softc, uint32_t initidx,
11815     ctl_ua_type ua_type)
11816 {
11817 	struct ctl_lun *lun;
11818 	struct scsi_sense_data *ps;
11819 	uint32_t p, i;
11820 
11821 	p = initidx / CTL_MAX_INIT_PER_PORT;
11822 	i = initidx % CTL_MAX_INIT_PER_PORT;
11823 	mtx_lock(&softc->ctl_lock);
11824 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11825 		mtx_lock(&lun->lun_lock);
11826 		/* Abort tasks. */
11827 		ctl_abort_tasks_lun(lun, p, i, 1);
11828 		/* Clear CA. */
11829 		ps = lun->pending_sense[p];
11830 		if (ps != NULL)
11831 			ps[i].error_code = 0;
11832 		/* Clear reservation. */
11833 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
11834 			lun->flags &= ~CTL_LUN_RESERVED;
11835 		/* Clear prevent media removal. */
11836 		if (lun->prevent && ctl_is_set(lun->prevent, initidx)) {
11837 			ctl_clear_mask(lun->prevent, initidx);
11838 			lun->prevent_count--;
11839 		}
11840 		/* Clear TPC status */
11841 		ctl_tpc_lun_clear(lun, initidx);
11842 		/* Establish UA. */
11843 		ctl_est_ua(lun, initidx, ua_type);
11844 		mtx_unlock(&lun->lun_lock);
11845 	}
11846 	mtx_unlock(&softc->ctl_lock);
11847 }
11848 
11849 static int
11850 ctl_i_t_nexus_reset(union ctl_io *io)
11851 {
11852 	struct ctl_softc *softc = CTL_SOFTC(io);
11853 	uint32_t initidx;
11854 
11855 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11856 		union ctl_ha_msg msg_info;
11857 
11858 		msg_info.hdr.nexus = io->io_hdr.nexus;
11859 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
11860 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11861 		msg_info.hdr.original_sc = NULL;
11862 		msg_info.hdr.serializing_sc = NULL;
11863 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11864 		    sizeof(msg_info.task), M_WAITOK);
11865 	}
11866 
11867 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11868 	ctl_i_t_nexus_loss(softc, initidx, CTL_UA_I_T_NEXUS_LOSS);
11869 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11870 	return (0);
11871 }
11872 
11873 static int
11874 ctl_abort_task(union ctl_io *io)
11875 {
11876 	struct ctl_softc *softc = CTL_SOFTC(io);
11877 	union ctl_io *xio;
11878 	struct ctl_lun *lun;
11879 #if 0
11880 	struct sbuf sb;
11881 	char printbuf[128];
11882 #endif
11883 	int found;
11884 	uint32_t targ_lun;
11885 
11886 	found = 0;
11887 
11888 	/*
11889 	 * Look up the LUN.
11890 	 */
11891 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11892 	mtx_lock(&softc->ctl_lock);
11893 	if (targ_lun >= CTL_MAX_LUNS ||
11894 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11895 		mtx_unlock(&softc->ctl_lock);
11896 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11897 		return (1);
11898 	}
11899 
11900 #if 0
11901 	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
11902 	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
11903 #endif
11904 
11905 	mtx_lock(&lun->lun_lock);
11906 	mtx_unlock(&softc->ctl_lock);
11907 	/*
11908 	 * Run through the OOA queue and attempt to find the given I/O.
11909 	 * The target port, initiator ID, tag type and tag number have to
11910 	 * match the values that we got from the initiator.  If we have an
11911 	 * untagged command to abort, simply abort the first untagged command
11912 	 * we come to.  We only allow one untagged command at a time of course.
11913 	 */
11914 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11915 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11916 #if 0
11917 		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
11918 
11919 		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
11920 			    lun->lun, xio->scsiio.tag_num,
11921 			    xio->scsiio.tag_type,
11922 			    (xio->io_hdr.blocked_links.tqe_prev
11923 			    == NULL) ? "" : " BLOCKED",
11924 			    (xio->io_hdr.flags &
11925 			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
11926 			    (xio->io_hdr.flags &
11927 			    CTL_FLAG_ABORT) ? " ABORT" : "",
11928 			    (xio->io_hdr.flags &
11929 			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
11930 		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
11931 		sbuf_finish(&sb);
11932 		printf("%s\n", sbuf_data(&sb));
11933 #endif
11934 
11935 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
11936 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
11937 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
11938 			continue;
11939 
11940 		/*
11941 		 * If the abort says that the task is untagged, the
11942 		 * task in the queue must be untagged.  Otherwise,
11943 		 * we just check to see whether the tag numbers
11944 		 * match.  This is because the QLogic firmware
11945 		 * doesn't pass back the tag type in an abort
11946 		 * request.
11947 		 */
11948 #if 0
11949 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
11950 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
11951 		 || (xio->scsiio.tag_num == io->taskio.tag_num))
11952 #endif
11953 		/*
11954 		 * XXX KDM we've got problems with FC, because it
11955 		 * doesn't send down a tag type with aborts.  So we
11956 		 * can only really go by the tag number...
11957 		 * This may cause problems with parallel SCSI.
11958 		 * Need to figure that out!!
11959 		 */
11960 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
11961 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11962 			found = 1;
11963 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
11964 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11965 				union ctl_ha_msg msg_info;
11966 
11967 				msg_info.hdr.nexus = io->io_hdr.nexus;
11968 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11969 				msg_info.task.tag_num = io->taskio.tag_num;
11970 				msg_info.task.tag_type = io->taskio.tag_type;
11971 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11972 				msg_info.hdr.original_sc = NULL;
11973 				msg_info.hdr.serializing_sc = NULL;
11974 #if 0
11975 				printf("Sent Abort to other side\n");
11976 #endif
11977 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11978 				    sizeof(msg_info.task), M_NOWAIT);
11979 			}
11980 #if 0
11981 			printf("ctl_abort_task: found I/O to abort\n");
11982 #endif
11983 		}
11984 	}
11985 	mtx_unlock(&lun->lun_lock);
11986 
11987 	if (found == 0) {
11988 		/*
11989 		 * This isn't really an error.  It's entirely possible for
11990 		 * the abort and command completion to cross on the wire.
11991 		 * This is more of an informative/diagnostic error.
11992 		 */
11993 #if 0
11994 		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
11995 		       "%u:%u:%u tag %d type %d\n",
11996 		       io->io_hdr.nexus.initid,
11997 		       io->io_hdr.nexus.targ_port,
11998 		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
11999 		       io->taskio.tag_type);
12000 #endif
12001 	}
12002 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12003 	return (0);
12004 }
12005 
12006 static int
12007 ctl_query_task(union ctl_io *io, int task_set)
12008 {
12009 	struct ctl_softc *softc = CTL_SOFTC(io);
12010 	union ctl_io *xio;
12011 	struct ctl_lun *lun;
12012 	int found = 0;
12013 	uint32_t targ_lun;
12014 
12015 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12016 	mtx_lock(&softc->ctl_lock);
12017 	if (targ_lun >= CTL_MAX_LUNS ||
12018 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12019 		mtx_unlock(&softc->ctl_lock);
12020 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12021 		return (1);
12022 	}
12023 	mtx_lock(&lun->lun_lock);
12024 	mtx_unlock(&softc->ctl_lock);
12025 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12026 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12027 
12028 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12029 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12030 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12031 			continue;
12032 
12033 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12034 			found = 1;
12035 			break;
12036 		}
12037 	}
12038 	mtx_unlock(&lun->lun_lock);
12039 	if (found)
12040 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12041 	else
12042 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12043 	return (0);
12044 }
12045 
12046 static int
12047 ctl_query_async_event(union ctl_io *io)
12048 {
12049 	struct ctl_softc *softc = CTL_SOFTC(io);
12050 	struct ctl_lun *lun;
12051 	ctl_ua_type ua;
12052 	uint32_t targ_lun, initidx;
12053 
12054 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12055 	mtx_lock(&softc->ctl_lock);
12056 	if (targ_lun >= CTL_MAX_LUNS ||
12057 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12058 		mtx_unlock(&softc->ctl_lock);
12059 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12060 		return (1);
12061 	}
12062 	mtx_lock(&lun->lun_lock);
12063 	mtx_unlock(&softc->ctl_lock);
12064 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12065 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12066 	mtx_unlock(&lun->lun_lock);
12067 	if (ua != CTL_UA_NONE)
12068 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12069 	else
12070 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12071 	return (0);
12072 }
12073 
12074 static void
12075 ctl_run_task(union ctl_io *io)
12076 {
12077 	int retval = 1;
12078 
12079 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12080 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12081 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12082 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12083 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12084 	switch (io->taskio.task_action) {
12085 	case CTL_TASK_ABORT_TASK:
12086 		retval = ctl_abort_task(io);
12087 		break;
12088 	case CTL_TASK_ABORT_TASK_SET:
12089 	case CTL_TASK_CLEAR_TASK_SET:
12090 		retval = ctl_abort_task_set(io);
12091 		break;
12092 	case CTL_TASK_CLEAR_ACA:
12093 		break;
12094 	case CTL_TASK_I_T_NEXUS_RESET:
12095 		retval = ctl_i_t_nexus_reset(io);
12096 		break;
12097 	case CTL_TASK_LUN_RESET:
12098 		retval = ctl_lun_reset(io);
12099 		break;
12100 	case CTL_TASK_TARGET_RESET:
12101 	case CTL_TASK_BUS_RESET:
12102 		retval = ctl_target_reset(io);
12103 		break;
12104 	case CTL_TASK_PORT_LOGIN:
12105 		break;
12106 	case CTL_TASK_PORT_LOGOUT:
12107 		break;
12108 	case CTL_TASK_QUERY_TASK:
12109 		retval = ctl_query_task(io, 0);
12110 		break;
12111 	case CTL_TASK_QUERY_TASK_SET:
12112 		retval = ctl_query_task(io, 1);
12113 		break;
12114 	case CTL_TASK_QUERY_ASYNC_EVENT:
12115 		retval = ctl_query_async_event(io);
12116 		break;
12117 	default:
12118 		printf("%s: got unknown task management event %d\n",
12119 		       __func__, io->taskio.task_action);
12120 		break;
12121 	}
12122 	if (retval == 0)
12123 		io->io_hdr.status = CTL_SUCCESS;
12124 	else
12125 		io->io_hdr.status = CTL_ERROR;
12126 	ctl_done(io);
12127 }
12128 
12129 /*
12130  * For HA operation.  Handle commands that come in from the other
12131  * controller.
12132  */
12133 static void
12134 ctl_handle_isc(union ctl_io *io)
12135 {
12136 	struct ctl_softc *softc = CTL_SOFTC(io);
12137 	struct ctl_lun *lun;
12138 	const struct ctl_cmd_entry *entry;
12139 	uint32_t targ_lun;
12140 
12141 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12142 	switch (io->io_hdr.msg_type) {
12143 	case CTL_MSG_SERIALIZE:
12144 		ctl_serialize_other_sc_cmd(&io->scsiio);
12145 		break;
12146 	case CTL_MSG_R2R:		/* Only used in SER_ONLY mode. */
12147 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12148 		if (targ_lun >= CTL_MAX_LUNS ||
12149 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12150 			ctl_done(io);
12151 			break;
12152 		}
12153 		mtx_lock(&lun->lun_lock);
12154 		if (ctl_scsiio_lun_check(lun, entry, &io->scsiio) != 0) {
12155 			mtx_unlock(&lun->lun_lock);
12156 			ctl_done(io);
12157 			break;
12158 		}
12159 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12160 		mtx_unlock(&lun->lun_lock);
12161 		ctl_enqueue_rtr(io);
12162 		break;
12163 	case CTL_MSG_FINISH_IO:
12164 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12165 			ctl_done(io);
12166 			break;
12167 		}
12168 		if (targ_lun >= CTL_MAX_LUNS ||
12169 		    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12170 			ctl_free_io(io);
12171 			break;
12172 		}
12173 		mtx_lock(&lun->lun_lock);
12174 		TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
12175 		ctl_check_blocked(lun);
12176 		mtx_unlock(&lun->lun_lock);
12177 		ctl_free_io(io);
12178 		break;
12179 	case CTL_MSG_PERS_ACTION:
12180 		ctl_hndl_per_res_out_on_other_sc(io);
12181 		ctl_free_io(io);
12182 		break;
12183 	case CTL_MSG_BAD_JUJU:
12184 		ctl_done(io);
12185 		break;
12186 	case CTL_MSG_DATAMOVE:		/* Only used in XFER mode */
12187 		ctl_datamove_remote(io);
12188 		break;
12189 	case CTL_MSG_DATAMOVE_DONE:	/* Only used in XFER mode */
12190 		io->scsiio.be_move_done(io);
12191 		break;
12192 	case CTL_MSG_FAILOVER:
12193 		ctl_failover_lun(io);
12194 		ctl_free_io(io);
12195 		break;
12196 	default:
12197 		printf("%s: Invalid message type %d\n",
12198 		       __func__, io->io_hdr.msg_type);
12199 		ctl_free_io(io);
12200 		break;
12201 	}
12202 
12203 }
12204 
12205 
12206 /*
12207  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12208  * there is no match.
12209  */
12210 static ctl_lun_error_pattern
12211 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12212 {
12213 	const struct ctl_cmd_entry *entry;
12214 	ctl_lun_error_pattern filtered_pattern, pattern;
12215 
12216 	pattern = desc->error_pattern;
12217 
12218 	/*
12219 	 * XXX KDM we need more data passed into this function to match a
12220 	 * custom pattern, and we actually need to implement custom pattern
12221 	 * matching.
12222 	 */
12223 	if (pattern & CTL_LUN_PAT_CMD)
12224 		return (CTL_LUN_PAT_CMD);
12225 
12226 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12227 		return (CTL_LUN_PAT_ANY);
12228 
12229 	entry = ctl_get_cmd_entry(ctsio, NULL);
12230 
12231 	filtered_pattern = entry->pattern & pattern;
12232 
12233 	/*
12234 	 * If the user requested specific flags in the pattern (e.g.
12235 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12236 	 * flags.
12237 	 *
12238 	 * If the user did not specify any flags, it doesn't matter whether
12239 	 * or not the command supports the flags.
12240 	 */
12241 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12242 	     (pattern & ~CTL_LUN_PAT_MASK))
12243 		return (CTL_LUN_PAT_NONE);
12244 
12245 	/*
12246 	 * If the user asked for a range check, see if the requested LBA
12247 	 * range overlaps with this command's LBA range.
12248 	 */
12249 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12250 		uint64_t lba1;
12251 		uint64_t len1;
12252 		ctl_action action;
12253 		int retval;
12254 
12255 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12256 		if (retval != 0)
12257 			return (CTL_LUN_PAT_NONE);
12258 
12259 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12260 					      desc->lba_range.len, FALSE);
12261 		/*
12262 		 * A "pass" means that the LBA ranges don't overlap, so
12263 		 * this doesn't match the user's range criteria.
12264 		 */
12265 		if (action == CTL_ACTION_PASS)
12266 			return (CTL_LUN_PAT_NONE);
12267 	}
12268 
12269 	return (filtered_pattern);
12270 }
12271 
12272 static void
12273 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12274 {
12275 	struct ctl_error_desc *desc, *desc2;
12276 
12277 	mtx_assert(&lun->lun_lock, MA_OWNED);
12278 
12279 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12280 		ctl_lun_error_pattern pattern;
12281 		/*
12282 		 * Check to see whether this particular command matches
12283 		 * the pattern in the descriptor.
12284 		 */
12285 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12286 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12287 			continue;
12288 
12289 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12290 		case CTL_LUN_INJ_ABORTED:
12291 			ctl_set_aborted(&io->scsiio);
12292 			break;
12293 		case CTL_LUN_INJ_MEDIUM_ERR:
12294 			ctl_set_medium_error(&io->scsiio,
12295 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12296 			     CTL_FLAG_DATA_OUT);
12297 			break;
12298 		case CTL_LUN_INJ_UA:
12299 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12300 			 * OCCURRED */
12301 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12302 			break;
12303 		case CTL_LUN_INJ_CUSTOM:
12304 			/*
12305 			 * We're assuming the user knows what he is doing.
12306 			 * Just copy the sense information without doing
12307 			 * checks.
12308 			 */
12309 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12310 			      MIN(sizeof(desc->custom_sense),
12311 				  sizeof(io->scsiio.sense_data)));
12312 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12313 			io->scsiio.sense_len = SSD_FULL_SIZE;
12314 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12315 			break;
12316 		case CTL_LUN_INJ_NONE:
12317 		default:
12318 			/*
12319 			 * If this is an error injection type we don't know
12320 			 * about, clear the continuous flag (if it is set)
12321 			 * so it will get deleted below.
12322 			 */
12323 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12324 			break;
12325 		}
12326 		/*
12327 		 * By default, each error injection action is a one-shot
12328 		 */
12329 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12330 			continue;
12331 
12332 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12333 
12334 		free(desc, M_CTL);
12335 	}
12336 }
12337 
12338 #ifdef CTL_IO_DELAY
12339 static void
12340 ctl_datamove_timer_wakeup(void *arg)
12341 {
12342 	union ctl_io *io;
12343 
12344 	io = (union ctl_io *)arg;
12345 
12346 	ctl_datamove(io);
12347 }
12348 #endif /* CTL_IO_DELAY */
12349 
12350 void
12351 ctl_datamove(union ctl_io *io)
12352 {
12353 	void (*fe_datamove)(union ctl_io *io);
12354 
12355 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12356 
12357 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12358 
12359 	/* No data transferred yet.  Frontend must update this when done. */
12360 	io->scsiio.kern_data_resid = io->scsiio.kern_data_len;
12361 
12362 #ifdef CTL_TIME_IO
12363 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12364 		char str[256];
12365 		char path_str[64];
12366 		struct sbuf sb;
12367 
12368 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12369 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12370 
12371 		sbuf_cat(&sb, path_str);
12372 		switch (io->io_hdr.io_type) {
12373 		case CTL_IO_SCSI:
12374 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12375 			sbuf_printf(&sb, "\n");
12376 			sbuf_cat(&sb, path_str);
12377 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12378 				    io->scsiio.tag_num, io->scsiio.tag_type);
12379 			break;
12380 		case CTL_IO_TASK:
12381 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12382 				    "Tag Type: %d\n", io->taskio.task_action,
12383 				    io->taskio.tag_num, io->taskio.tag_type);
12384 			break;
12385 		default:
12386 			panic("%s: Invalid CTL I/O type %d\n",
12387 			    __func__, io->io_hdr.io_type);
12388 		}
12389 		sbuf_cat(&sb, path_str);
12390 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12391 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12392 		sbuf_finish(&sb);
12393 		printf("%s", sbuf_data(&sb));
12394 	}
12395 #endif /* CTL_TIME_IO */
12396 
12397 #ifdef CTL_IO_DELAY
12398 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12399 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12400 	} else {
12401 		struct ctl_lun *lun;
12402 
12403 		lun = CTL_LUN(io);
12404 		if ((lun != NULL)
12405 		 && (lun->delay_info.datamove_delay > 0)) {
12406 
12407 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12408 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12409 			callout_reset(&io->io_hdr.delay_callout,
12410 				      lun->delay_info.datamove_delay * hz,
12411 				      ctl_datamove_timer_wakeup, io);
12412 			if (lun->delay_info.datamove_type ==
12413 			    CTL_DELAY_TYPE_ONESHOT)
12414 				lun->delay_info.datamove_delay = 0;
12415 			return;
12416 		}
12417 	}
12418 #endif
12419 
12420 	/*
12421 	 * This command has been aborted.  Set the port status, so we fail
12422 	 * the data move.
12423 	 */
12424 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12425 		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12426 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12427 		       io->io_hdr.nexus.targ_port,
12428 		       io->io_hdr.nexus.targ_lun);
12429 		io->io_hdr.port_status = 31337;
12430 		/*
12431 		 * Note that the backend, in this case, will get the
12432 		 * callback in its context.  In other cases it may get
12433 		 * called in the frontend's interrupt thread context.
12434 		 */
12435 		io->scsiio.be_move_done(io);
12436 		return;
12437 	}
12438 
12439 	/* Don't confuse frontend with zero length data move. */
12440 	if (io->scsiio.kern_data_len == 0) {
12441 		io->scsiio.be_move_done(io);
12442 		return;
12443 	}
12444 
12445 	fe_datamove = CTL_PORT(io)->fe_datamove;
12446 	fe_datamove(io);
12447 }
12448 
12449 static void
12450 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12451 {
12452 	union ctl_ha_msg msg;
12453 #ifdef CTL_TIME_IO
12454 	struct bintime cur_bt;
12455 #endif
12456 
12457 	memset(&msg, 0, sizeof(msg));
12458 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12459 	msg.hdr.original_sc = io;
12460 	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12461 	msg.hdr.nexus = io->io_hdr.nexus;
12462 	msg.hdr.status = io->io_hdr.status;
12463 	msg.scsi.kern_data_resid = io->scsiio.kern_data_resid;
12464 	msg.scsi.tag_num = io->scsiio.tag_num;
12465 	msg.scsi.tag_type = io->scsiio.tag_type;
12466 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12467 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12468 	       io->scsiio.sense_len);
12469 	msg.scsi.sense_len = io->scsiio.sense_len;
12470 	msg.scsi.port_status = io->io_hdr.port_status;
12471 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12472 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12473 		ctl_failover_io(io, /*have_lock*/ have_lock);
12474 		return;
12475 	}
12476 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12477 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12478 	    msg.scsi.sense_len, M_WAITOK);
12479 
12480 #ifdef CTL_TIME_IO
12481 	getbinuptime(&cur_bt);
12482 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12483 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12484 #endif
12485 	io->io_hdr.num_dmas++;
12486 }
12487 
12488 /*
12489  * The DMA to the remote side is done, now we need to tell the other side
12490  * we're done so it can continue with its data movement.
12491  */
12492 static void
12493 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12494 {
12495 	union ctl_io *io;
12496 	uint32_t i;
12497 
12498 	io = rq->context;
12499 
12500 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12501 		printf("%s: ISC DMA write failed with error %d", __func__,
12502 		       rq->ret);
12503 		ctl_set_internal_failure(&io->scsiio,
12504 					 /*sks_valid*/ 1,
12505 					 /*retry_count*/ rq->ret);
12506 	}
12507 
12508 	ctl_dt_req_free(rq);
12509 
12510 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12511 		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12512 	free(io->io_hdr.remote_sglist, M_CTL);
12513 	io->io_hdr.remote_sglist = NULL;
12514 	io->io_hdr.local_sglist = NULL;
12515 
12516 	/*
12517 	 * The data is in local and remote memory, so now we need to send
12518 	 * status (good or back) back to the other side.
12519 	 */
12520 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12521 }
12522 
12523 /*
12524  * We've moved the data from the host/controller into local memory.  Now we
12525  * need to push it over to the remote controller's memory.
12526  */
12527 static int
12528 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12529 {
12530 	int retval;
12531 
12532 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12533 					  ctl_datamove_remote_write_cb);
12534 	return (retval);
12535 }
12536 
12537 static void
12538 ctl_datamove_remote_write(union ctl_io *io)
12539 {
12540 	int retval;
12541 	void (*fe_datamove)(union ctl_io *io);
12542 
12543 	/*
12544 	 * - Get the data from the host/HBA into local memory.
12545 	 * - DMA memory from the local controller to the remote controller.
12546 	 * - Send status back to the remote controller.
12547 	 */
12548 
12549 	retval = ctl_datamove_remote_sgl_setup(io);
12550 	if (retval != 0)
12551 		return;
12552 
12553 	/* Switch the pointer over so the FETD knows what to do */
12554 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12555 
12556 	/*
12557 	 * Use a custom move done callback, since we need to send completion
12558 	 * back to the other controller, not to the backend on this side.
12559 	 */
12560 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12561 
12562 	fe_datamove = CTL_PORT(io)->fe_datamove;
12563 	fe_datamove(io);
12564 }
12565 
12566 static int
12567 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12568 {
12569 #if 0
12570 	char str[256];
12571 	char path_str[64];
12572 	struct sbuf sb;
12573 #endif
12574 	uint32_t i;
12575 
12576 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12577 		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12578 	free(io->io_hdr.remote_sglist, M_CTL);
12579 	io->io_hdr.remote_sglist = NULL;
12580 	io->io_hdr.local_sglist = NULL;
12581 
12582 #if 0
12583 	scsi_path_string(io, path_str, sizeof(path_str));
12584 	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12585 	sbuf_cat(&sb, path_str);
12586 	scsi_command_string(&io->scsiio, NULL, &sb);
12587 	sbuf_printf(&sb, "\n");
12588 	sbuf_cat(&sb, path_str);
12589 	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12590 		    io->scsiio.tag_num, io->scsiio.tag_type);
12591 	sbuf_cat(&sb, path_str);
12592 	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12593 		    io->io_hdr.flags, io->io_hdr.status);
12594 	sbuf_finish(&sb);
12595 	printk("%s", sbuf_data(&sb));
12596 #endif
12597 
12598 
12599 	/*
12600 	 * The read is done, now we need to send status (good or bad) back
12601 	 * to the other side.
12602 	 */
12603 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12604 
12605 	return (0);
12606 }
12607 
12608 static void
12609 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12610 {
12611 	union ctl_io *io;
12612 	void (*fe_datamove)(union ctl_io *io);
12613 
12614 	io = rq->context;
12615 
12616 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12617 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12618 		       rq->ret);
12619 		ctl_set_internal_failure(&io->scsiio,
12620 					 /*sks_valid*/ 1,
12621 					 /*retry_count*/ rq->ret);
12622 	}
12623 
12624 	ctl_dt_req_free(rq);
12625 
12626 	/* Switch the pointer over so the FETD knows what to do */
12627 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12628 
12629 	/*
12630 	 * Use a custom move done callback, since we need to send completion
12631 	 * back to the other controller, not to the backend on this side.
12632 	 */
12633 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12634 
12635 	/* XXX KDM add checks like the ones in ctl_datamove? */
12636 
12637 	fe_datamove = CTL_PORT(io)->fe_datamove;
12638 	fe_datamove(io);
12639 }
12640 
12641 static int
12642 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12643 {
12644 	struct ctl_sg_entry *local_sglist;
12645 	uint32_t len_to_go;
12646 	int retval;
12647 	int i;
12648 
12649 	retval = 0;
12650 	local_sglist = io->io_hdr.local_sglist;
12651 	len_to_go = io->scsiio.kern_data_len;
12652 
12653 	/*
12654 	 * The difficult thing here is that the size of the various
12655 	 * S/G segments may be different than the size from the
12656 	 * remote controller.  That'll make it harder when DMAing
12657 	 * the data back to the other side.
12658 	 */
12659 	for (i = 0; len_to_go > 0; i++) {
12660 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12661 		local_sglist[i].addr =
12662 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12663 
12664 		len_to_go -= local_sglist[i].len;
12665 	}
12666 	/*
12667 	 * Reset the number of S/G entries accordingly.  The original
12668 	 * number of S/G entries is available in rem_sg_entries.
12669 	 */
12670 	io->scsiio.kern_sg_entries = i;
12671 
12672 #if 0
12673 	printf("%s: kern_sg_entries = %d\n", __func__,
12674 	       io->scsiio.kern_sg_entries);
12675 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12676 		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12677 		       local_sglist[i].addr, local_sglist[i].len);
12678 #endif
12679 
12680 	return (retval);
12681 }
12682 
12683 static int
12684 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12685 			 ctl_ha_dt_cb callback)
12686 {
12687 	struct ctl_ha_dt_req *rq;
12688 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12689 	uint32_t local_used, remote_used, total_used;
12690 	int i, j, isc_ret;
12691 
12692 	rq = ctl_dt_req_alloc();
12693 
12694 	/*
12695 	 * If we failed to allocate the request, and if the DMA didn't fail
12696 	 * anyway, set busy status.  This is just a resource allocation
12697 	 * failure.
12698 	 */
12699 	if ((rq == NULL)
12700 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12701 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12702 		ctl_set_busy(&io->scsiio);
12703 
12704 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12705 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12706 
12707 		if (rq != NULL)
12708 			ctl_dt_req_free(rq);
12709 
12710 		/*
12711 		 * The data move failed.  We need to return status back
12712 		 * to the other controller.  No point in trying to DMA
12713 		 * data to the remote controller.
12714 		 */
12715 
12716 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12717 
12718 		return (1);
12719 	}
12720 
12721 	local_sglist = io->io_hdr.local_sglist;
12722 	remote_sglist = io->io_hdr.remote_sglist;
12723 	local_used = 0;
12724 	remote_used = 0;
12725 	total_used = 0;
12726 
12727 	/*
12728 	 * Pull/push the data over the wire from/to the other controller.
12729 	 * This takes into account the possibility that the local and
12730 	 * remote sglists may not be identical in terms of the size of
12731 	 * the elements and the number of elements.
12732 	 *
12733 	 * One fundamental assumption here is that the length allocated for
12734 	 * both the local and remote sglists is identical.  Otherwise, we've
12735 	 * essentially got a coding error of some sort.
12736 	 */
12737 	isc_ret = CTL_HA_STATUS_SUCCESS;
12738 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12739 		uint32_t cur_len;
12740 		uint8_t *tmp_ptr;
12741 
12742 		rq->command = command;
12743 		rq->context = io;
12744 
12745 		/*
12746 		 * Both pointers should be aligned.  But it is possible
12747 		 * that the allocation length is not.  They should both
12748 		 * also have enough slack left over at the end, though,
12749 		 * to round up to the next 8 byte boundary.
12750 		 */
12751 		cur_len = MIN(local_sglist[i].len - local_used,
12752 			      remote_sglist[j].len - remote_used);
12753 		rq->size = cur_len;
12754 
12755 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12756 		tmp_ptr += local_used;
12757 
12758 #if 0
12759 		/* Use physical addresses when talking to ISC hardware */
12760 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12761 			/* XXX KDM use busdma */
12762 			rq->local = vtophys(tmp_ptr);
12763 		} else
12764 			rq->local = tmp_ptr;
12765 #else
12766 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12767 		    ("HA does not support BUS_ADDR"));
12768 		rq->local = tmp_ptr;
12769 #endif
12770 
12771 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12772 		tmp_ptr += remote_used;
12773 		rq->remote = tmp_ptr;
12774 
12775 		rq->callback = NULL;
12776 
12777 		local_used += cur_len;
12778 		if (local_used >= local_sglist[i].len) {
12779 			i++;
12780 			local_used = 0;
12781 		}
12782 
12783 		remote_used += cur_len;
12784 		if (remote_used >= remote_sglist[j].len) {
12785 			j++;
12786 			remote_used = 0;
12787 		}
12788 		total_used += cur_len;
12789 
12790 		if (total_used >= io->scsiio.kern_data_len)
12791 			rq->callback = callback;
12792 
12793 #if 0
12794 		printf("%s: %s: local %p remote %p size %d\n", __func__,
12795 		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12796 		       rq->local, rq->remote, rq->size);
12797 #endif
12798 
12799 		isc_ret = ctl_dt_single(rq);
12800 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12801 			break;
12802 	}
12803 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12804 		rq->ret = isc_ret;
12805 		callback(rq);
12806 	}
12807 
12808 	return (0);
12809 }
12810 
12811 static void
12812 ctl_datamove_remote_read(union ctl_io *io)
12813 {
12814 	int retval;
12815 	uint32_t i;
12816 
12817 	/*
12818 	 * This will send an error to the other controller in the case of a
12819 	 * failure.
12820 	 */
12821 	retval = ctl_datamove_remote_sgl_setup(io);
12822 	if (retval != 0)
12823 		return;
12824 
12825 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
12826 					  ctl_datamove_remote_read_cb);
12827 	if (retval != 0) {
12828 		/*
12829 		 * Make sure we free memory if there was an error..  The
12830 		 * ctl_datamove_remote_xfer() function will send the
12831 		 * datamove done message, or call the callback with an
12832 		 * error if there is a problem.
12833 		 */
12834 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12835 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
12836 		free(io->io_hdr.remote_sglist, M_CTL);
12837 		io->io_hdr.remote_sglist = NULL;
12838 		io->io_hdr.local_sglist = NULL;
12839 	}
12840 }
12841 
12842 /*
12843  * Process a datamove request from the other controller.  This is used for
12844  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
12845  * first.  Once that is complete, the data gets DMAed into the remote
12846  * controller's memory.  For reads, we DMA from the remote controller's
12847  * memory into our memory first, and then move it out to the FETD.
12848  */
12849 static void
12850 ctl_datamove_remote(union ctl_io *io)
12851 {
12852 
12853 	mtx_assert(&((struct ctl_softc *)CTL_SOFTC(io))->ctl_lock, MA_NOTOWNED);
12854 
12855 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12856 		ctl_failover_io(io, /*have_lock*/ 0);
12857 		return;
12858 	}
12859 
12860 	/*
12861 	 * Note that we look for an aborted I/O here, but don't do some of
12862 	 * the other checks that ctl_datamove() normally does.
12863 	 * We don't need to run the datamove delay code, since that should
12864 	 * have been done if need be on the other controller.
12865 	 */
12866 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12867 		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
12868 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12869 		       io->io_hdr.nexus.targ_port,
12870 		       io->io_hdr.nexus.targ_lun);
12871 		io->io_hdr.port_status = 31338;
12872 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12873 		return;
12874 	}
12875 
12876 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
12877 		ctl_datamove_remote_write(io);
12878 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
12879 		ctl_datamove_remote_read(io);
12880 	else {
12881 		io->io_hdr.port_status = 31339;
12882 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12883 	}
12884 }
12885 
12886 static void
12887 ctl_process_done(union ctl_io *io)
12888 {
12889 	struct ctl_softc *softc = CTL_SOFTC(io);
12890 	struct ctl_port *port = CTL_PORT(io);
12891 	struct ctl_lun *lun = CTL_LUN(io);
12892 	void (*fe_done)(union ctl_io *io);
12893 	union ctl_ha_msg msg;
12894 
12895 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
12896 	fe_done = port->fe_done;
12897 
12898 #ifdef CTL_TIME_IO
12899 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12900 		char str[256];
12901 		char path_str[64];
12902 		struct sbuf sb;
12903 
12904 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12905 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12906 
12907 		sbuf_cat(&sb, path_str);
12908 		switch (io->io_hdr.io_type) {
12909 		case CTL_IO_SCSI:
12910 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12911 			sbuf_printf(&sb, "\n");
12912 			sbuf_cat(&sb, path_str);
12913 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12914 				    io->scsiio.tag_num, io->scsiio.tag_type);
12915 			break;
12916 		case CTL_IO_TASK:
12917 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12918 				    "Tag Type: %d\n", io->taskio.task_action,
12919 				    io->taskio.tag_num, io->taskio.tag_type);
12920 			break;
12921 		default:
12922 			panic("%s: Invalid CTL I/O type %d\n",
12923 			    __func__, io->io_hdr.io_type);
12924 		}
12925 		sbuf_cat(&sb, path_str);
12926 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
12927 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12928 		sbuf_finish(&sb);
12929 		printf("%s", sbuf_data(&sb));
12930 	}
12931 #endif /* CTL_TIME_IO */
12932 
12933 	switch (io->io_hdr.io_type) {
12934 	case CTL_IO_SCSI:
12935 		break;
12936 	case CTL_IO_TASK:
12937 		if (ctl_debug & CTL_DEBUG_INFO)
12938 			ctl_io_error_print(io, NULL);
12939 		fe_done(io);
12940 		return;
12941 	default:
12942 		panic("%s: Invalid CTL I/O type %d\n",
12943 		    __func__, io->io_hdr.io_type);
12944 	}
12945 
12946 	if (lun == NULL) {
12947 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
12948 				 io->io_hdr.nexus.targ_mapped_lun));
12949 		goto bailout;
12950 	}
12951 
12952 	mtx_lock(&lun->lun_lock);
12953 
12954 	/*
12955 	 * Check to see if we have any informational exception and status
12956 	 * of this command can be modified to report it in form of either
12957 	 * RECOVERED ERROR or NO SENSE, depending on MRIE mode page field.
12958 	 */
12959 	if (lun->ie_reported == 0 && lun->ie_asc != 0 &&
12960 	    io->io_hdr.status == CTL_SUCCESS &&
12961 	    (io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0) {
12962 		uint8_t mrie = lun->MODE_IE.mrie;
12963 		uint8_t per = ((lun->MODE_RWER.byte3 & SMS_RWER_PER) ||
12964 		    (lun->MODE_VER.byte3 & SMS_VER_PER));
12965 		if (((mrie == SIEP_MRIE_REC_COND && per) ||
12966 		     mrie == SIEP_MRIE_REC_UNCOND ||
12967 		     mrie == SIEP_MRIE_NO_SENSE) &&
12968 		    (ctl_get_cmd_entry(&io->scsiio, NULL)->flags &
12969 		     CTL_CMD_FLAG_NO_SENSE) == 0) {
12970 			ctl_set_sense(&io->scsiio,
12971 			      /*current_error*/ 1,
12972 			      /*sense_key*/ (mrie == SIEP_MRIE_NO_SENSE) ?
12973 			        SSD_KEY_NO_SENSE : SSD_KEY_RECOVERED_ERROR,
12974 			      /*asc*/ lun->ie_asc,
12975 			      /*ascq*/ lun->ie_ascq,
12976 			      SSD_ELEM_NONE);
12977 			lun->ie_reported = 1;
12978 		}
12979 	} else if (lun->ie_reported < 0)
12980 		lun->ie_reported = 0;
12981 
12982 	/*
12983 	 * Check to see if we have any errors to inject here.  We only
12984 	 * inject errors for commands that don't already have errors set.
12985 	 */
12986 	if (!STAILQ_EMPTY(&lun->error_list) &&
12987 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
12988 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
12989 		ctl_inject_error(lun, io);
12990 
12991 	/*
12992 	 * XXX KDM how do we treat commands that aren't completed
12993 	 * successfully?
12994 	 *
12995 	 * XXX KDM should we also track I/O latency?
12996 	 */
12997 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
12998 	    io->io_hdr.io_type == CTL_IO_SCSI) {
12999 		int type;
13000 #ifdef CTL_TIME_IO
13001 		struct bintime bt;
13002 
13003 		getbinuptime(&bt);
13004 		bintime_sub(&bt, &io->io_hdr.start_bt);
13005 #endif
13006 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13007 		    CTL_FLAG_DATA_IN)
13008 			type = CTL_STATS_READ;
13009 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13010 		    CTL_FLAG_DATA_OUT)
13011 			type = CTL_STATS_WRITE;
13012 		else
13013 			type = CTL_STATS_NO_IO;
13014 
13015 #ifdef CTL_LEGACY_STATS
13016 		uint32_t targ_port = port->targ_port;
13017 		lun->legacy_stats.ports[targ_port].bytes[type] +=
13018 		    io->scsiio.kern_total_len;
13019 		lun->legacy_stats.ports[targ_port].operations[type] ++;
13020 		lun->legacy_stats.ports[targ_port].num_dmas[type] +=
13021 		    io->io_hdr.num_dmas;
13022 #ifdef CTL_TIME_IO
13023 		bintime_add(&lun->legacy_stats.ports[targ_port].dma_time[type],
13024 		   &io->io_hdr.dma_bt);
13025 		bintime_add(&lun->legacy_stats.ports[targ_port].time[type],
13026 		    &bt);
13027 #endif
13028 #endif /* CTL_LEGACY_STATS */
13029 
13030 		lun->stats.bytes[type] += io->scsiio.kern_total_len;
13031 		lun->stats.operations[type] ++;
13032 		lun->stats.dmas[type] += io->io_hdr.num_dmas;
13033 #ifdef CTL_TIME_IO
13034 		bintime_add(&lun->stats.dma_time[type], &io->io_hdr.dma_bt);
13035 		bintime_add(&lun->stats.time[type], &bt);
13036 #endif
13037 
13038 		mtx_lock(&port->port_lock);
13039 		port->stats.bytes[type] += io->scsiio.kern_total_len;
13040 		port->stats.operations[type] ++;
13041 		port->stats.dmas[type] += io->io_hdr.num_dmas;
13042 #ifdef CTL_TIME_IO
13043 		bintime_add(&port->stats.dma_time[type], &io->io_hdr.dma_bt);
13044 		bintime_add(&port->stats.time[type], &bt);
13045 #endif
13046 		mtx_unlock(&port->port_lock);
13047 	}
13048 
13049 	/*
13050 	 * Remove this from the OOA queue.
13051 	 */
13052 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13053 #ifdef CTL_TIME_IO
13054 	if (TAILQ_EMPTY(&lun->ooa_queue))
13055 		lun->last_busy = getsbinuptime();
13056 #endif
13057 
13058 	/*
13059 	 * Run through the blocked queue on this LUN and see if anything
13060 	 * has become unblocked, now that this transaction is done.
13061 	 */
13062 	ctl_check_blocked(lun);
13063 
13064 	/*
13065 	 * If the LUN has been invalidated, free it if there is nothing
13066 	 * left on its OOA queue.
13067 	 */
13068 	if ((lun->flags & CTL_LUN_INVALID)
13069 	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13070 		mtx_unlock(&lun->lun_lock);
13071 		mtx_lock(&softc->ctl_lock);
13072 		ctl_free_lun(lun);
13073 		mtx_unlock(&softc->ctl_lock);
13074 	} else
13075 		mtx_unlock(&lun->lun_lock);
13076 
13077 bailout:
13078 
13079 	/*
13080 	 * If this command has been aborted, make sure we set the status
13081 	 * properly.  The FETD is responsible for freeing the I/O and doing
13082 	 * whatever it needs to do to clean up its state.
13083 	 */
13084 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13085 		ctl_set_task_aborted(&io->scsiio);
13086 
13087 	/*
13088 	 * If enabled, print command error status.
13089 	 */
13090 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13091 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13092 		ctl_io_error_print(io, NULL);
13093 
13094 	/*
13095 	 * Tell the FETD or the other shelf controller we're done with this
13096 	 * command.  Note that only SCSI commands get to this point.  Task
13097 	 * management commands are completed above.
13098 	 */
13099 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13100 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13101 		memset(&msg, 0, sizeof(msg));
13102 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13103 		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13104 		msg.hdr.nexus = io->io_hdr.nexus;
13105 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13106 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13107 		    M_WAITOK);
13108 	}
13109 
13110 	fe_done(io);
13111 }
13112 
13113 /*
13114  * Front end should call this if it doesn't do autosense.  When the request
13115  * sense comes back in from the initiator, we'll dequeue this and send it.
13116  */
13117 int
13118 ctl_queue_sense(union ctl_io *io)
13119 {
13120 	struct ctl_softc *softc = CTL_SOFTC(io);
13121 	struct ctl_port *port = CTL_PORT(io);
13122 	struct ctl_lun *lun;
13123 	struct scsi_sense_data *ps;
13124 	uint32_t initidx, p, targ_lun;
13125 
13126 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13127 
13128 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13129 
13130 	/*
13131 	 * LUN lookup will likely move to the ctl_work_thread() once we
13132 	 * have our new queueing infrastructure (that doesn't put things on
13133 	 * a per-LUN queue initially).  That is so that we can handle
13134 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13135 	 * can't deal with that right now.
13136 	 * If we don't have a LUN for this, just toss the sense information.
13137 	 */
13138 	mtx_lock(&softc->ctl_lock);
13139 	if (targ_lun >= CTL_MAX_LUNS ||
13140 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
13141 		mtx_unlock(&softc->ctl_lock);
13142 		goto bailout;
13143 	}
13144 	mtx_lock(&lun->lun_lock);
13145 	mtx_unlock(&softc->ctl_lock);
13146 
13147 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13148 	p = initidx / CTL_MAX_INIT_PER_PORT;
13149 	if (lun->pending_sense[p] == NULL) {
13150 		lun->pending_sense[p] = malloc(sizeof(*ps) * CTL_MAX_INIT_PER_PORT,
13151 		    M_CTL, M_NOWAIT | M_ZERO);
13152 	}
13153 	if ((ps = lun->pending_sense[p]) != NULL) {
13154 		ps += initidx % CTL_MAX_INIT_PER_PORT;
13155 		memset(ps, 0, sizeof(*ps));
13156 		memcpy(ps, &io->scsiio.sense_data, io->scsiio.sense_len);
13157 	}
13158 	mtx_unlock(&lun->lun_lock);
13159 
13160 bailout:
13161 	ctl_free_io(io);
13162 	return (CTL_RETVAL_COMPLETE);
13163 }
13164 
13165 /*
13166  * Primary command inlet from frontend ports.  All SCSI and task I/O
13167  * requests must go through this function.
13168  */
13169 int
13170 ctl_queue(union ctl_io *io)
13171 {
13172 	struct ctl_port *port = CTL_PORT(io);
13173 
13174 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13175 
13176 #ifdef CTL_TIME_IO
13177 	io->io_hdr.start_time = time_uptime;
13178 	getbinuptime(&io->io_hdr.start_bt);
13179 #endif /* CTL_TIME_IO */
13180 
13181 	/* Map FE-specific LUN ID into global one. */
13182 	io->io_hdr.nexus.targ_mapped_lun =
13183 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13184 
13185 	switch (io->io_hdr.io_type) {
13186 	case CTL_IO_SCSI:
13187 	case CTL_IO_TASK:
13188 		if (ctl_debug & CTL_DEBUG_CDB)
13189 			ctl_io_print(io);
13190 		ctl_enqueue_incoming(io);
13191 		break;
13192 	default:
13193 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13194 		return (EINVAL);
13195 	}
13196 
13197 	return (CTL_RETVAL_COMPLETE);
13198 }
13199 
13200 #ifdef CTL_IO_DELAY
13201 static void
13202 ctl_done_timer_wakeup(void *arg)
13203 {
13204 	union ctl_io *io;
13205 
13206 	io = (union ctl_io *)arg;
13207 	ctl_done(io);
13208 }
13209 #endif /* CTL_IO_DELAY */
13210 
13211 void
13212 ctl_serseq_done(union ctl_io *io)
13213 {
13214 	struct ctl_lun *lun = CTL_LUN(io);;
13215 
13216 	if (lun->be_lun == NULL ||
13217 	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13218 		return;
13219 	mtx_lock(&lun->lun_lock);
13220 	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13221 	ctl_check_blocked(lun);
13222 	mtx_unlock(&lun->lun_lock);
13223 }
13224 
13225 void
13226 ctl_done(union ctl_io *io)
13227 {
13228 
13229 	/*
13230 	 * Enable this to catch duplicate completion issues.
13231 	 */
13232 #if 0
13233 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13234 		printf("%s: type %d msg %d cdb %x iptl: "
13235 		       "%u:%u:%u tag 0x%04x "
13236 		       "flag %#x status %x\n",
13237 			__func__,
13238 			io->io_hdr.io_type,
13239 			io->io_hdr.msg_type,
13240 			io->scsiio.cdb[0],
13241 			io->io_hdr.nexus.initid,
13242 			io->io_hdr.nexus.targ_port,
13243 			io->io_hdr.nexus.targ_lun,
13244 			(io->io_hdr.io_type ==
13245 			CTL_IO_TASK) ?
13246 			io->taskio.tag_num :
13247 			io->scsiio.tag_num,
13248 		        io->io_hdr.flags,
13249 			io->io_hdr.status);
13250 	} else
13251 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13252 #endif
13253 
13254 	/*
13255 	 * This is an internal copy of an I/O, and should not go through
13256 	 * the normal done processing logic.
13257 	 */
13258 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13259 		return;
13260 
13261 #ifdef CTL_IO_DELAY
13262 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13263 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13264 	} else {
13265 		struct ctl_lun *lun = CTL_LUN(io);
13266 
13267 		if ((lun != NULL)
13268 		 && (lun->delay_info.done_delay > 0)) {
13269 
13270 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13271 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13272 			callout_reset(&io->io_hdr.delay_callout,
13273 				      lun->delay_info.done_delay * hz,
13274 				      ctl_done_timer_wakeup, io);
13275 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13276 				lun->delay_info.done_delay = 0;
13277 			return;
13278 		}
13279 	}
13280 #endif /* CTL_IO_DELAY */
13281 
13282 	ctl_enqueue_done(io);
13283 }
13284 
13285 static void
13286 ctl_work_thread(void *arg)
13287 {
13288 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13289 	struct ctl_softc *softc = thr->ctl_softc;
13290 	union ctl_io *io;
13291 	int retval;
13292 
13293 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13294 
13295 	while (!softc->shutdown) {
13296 		/*
13297 		 * We handle the queues in this order:
13298 		 * - ISC
13299 		 * - done queue (to free up resources, unblock other commands)
13300 		 * - RtR queue
13301 		 * - incoming queue
13302 		 *
13303 		 * If those queues are empty, we break out of the loop and
13304 		 * go to sleep.
13305 		 */
13306 		mtx_lock(&thr->queue_lock);
13307 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13308 		if (io != NULL) {
13309 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13310 			mtx_unlock(&thr->queue_lock);
13311 			ctl_handle_isc(io);
13312 			continue;
13313 		}
13314 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13315 		if (io != NULL) {
13316 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13317 			/* clear any blocked commands, call fe_done */
13318 			mtx_unlock(&thr->queue_lock);
13319 			ctl_process_done(io);
13320 			continue;
13321 		}
13322 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13323 		if (io != NULL) {
13324 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13325 			mtx_unlock(&thr->queue_lock);
13326 			if (io->io_hdr.io_type == CTL_IO_TASK)
13327 				ctl_run_task(io);
13328 			else
13329 				ctl_scsiio_precheck(softc, &io->scsiio);
13330 			continue;
13331 		}
13332 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13333 		if (io != NULL) {
13334 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13335 			mtx_unlock(&thr->queue_lock);
13336 			retval = ctl_scsiio(&io->scsiio);
13337 			if (retval != CTL_RETVAL_COMPLETE)
13338 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13339 			continue;
13340 		}
13341 
13342 		/* Sleep until we have something to do. */
13343 		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13344 	}
13345 	thr->thread = NULL;
13346 	kthread_exit();
13347 }
13348 
13349 static void
13350 ctl_lun_thread(void *arg)
13351 {
13352 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13353 	struct ctl_be_lun *be_lun;
13354 
13355 	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13356 
13357 	while (!softc->shutdown) {
13358 		mtx_lock(&softc->ctl_lock);
13359 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13360 		if (be_lun != NULL) {
13361 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13362 			mtx_unlock(&softc->ctl_lock);
13363 			ctl_create_lun(be_lun);
13364 			continue;
13365 		}
13366 
13367 		/* Sleep until we have something to do. */
13368 		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13369 		    PDROP | PRIBIO, "-", 0);
13370 	}
13371 	softc->lun_thread = NULL;
13372 	kthread_exit();
13373 }
13374 
13375 static void
13376 ctl_thresh_thread(void *arg)
13377 {
13378 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13379 	struct ctl_lun *lun;
13380 	struct ctl_logical_block_provisioning_page *page;
13381 	const char *attr;
13382 	union ctl_ha_msg msg;
13383 	uint64_t thres, val;
13384 	int i, e, set;
13385 
13386 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13387 
13388 	while (!softc->shutdown) {
13389 		mtx_lock(&softc->ctl_lock);
13390 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13391 			if ((lun->flags & CTL_LUN_DISABLED) ||
13392 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13393 			    lun->backend->lun_attr == NULL)
13394 				continue;
13395 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13396 			    softc->ha_mode == CTL_HA_MODE_XFER)
13397 				continue;
13398 			if ((lun->MODE_RWER.byte8 & SMS_RWER_LBPERE) == 0)
13399 				continue;
13400 			e = 0;
13401 			page = &lun->MODE_LBP;
13402 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13403 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13404 					continue;
13405 				thres = scsi_4btoul(page->descr[i].count);
13406 				thres <<= CTL_LBP_EXPONENT;
13407 				switch (page->descr[i].resource) {
13408 				case 0x01:
13409 					attr = "blocksavail";
13410 					break;
13411 				case 0x02:
13412 					attr = "blocksused";
13413 					break;
13414 				case 0xf1:
13415 					attr = "poolblocksavail";
13416 					break;
13417 				case 0xf2:
13418 					attr = "poolblocksused";
13419 					break;
13420 				default:
13421 					continue;
13422 				}
13423 				mtx_unlock(&softc->ctl_lock); // XXX
13424 				val = lun->backend->lun_attr(
13425 				    lun->be_lun->be_lun, attr);
13426 				mtx_lock(&softc->ctl_lock);
13427 				if (val == UINT64_MAX)
13428 					continue;
13429 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13430 				    == SLBPPD_ARMING_INC)
13431 					e = (val >= thres);
13432 				else
13433 					e = (val <= thres);
13434 				if (e)
13435 					break;
13436 			}
13437 			mtx_lock(&lun->lun_lock);
13438 			if (e) {
13439 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13440 				    (uint8_t *)page, lun->ua_tpt_info);
13441 				if (lun->lasttpt == 0 ||
13442 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13443 					lun->lasttpt = time_uptime;
13444 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13445 					set = 1;
13446 				} else
13447 					set = 0;
13448 			} else {
13449 				lun->lasttpt = 0;
13450 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13451 				set = -1;
13452 			}
13453 			mtx_unlock(&lun->lun_lock);
13454 			if (set != 0 &&
13455 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13456 				/* Send msg to other side. */
13457 				bzero(&msg.ua, sizeof(msg.ua));
13458 				msg.hdr.msg_type = CTL_MSG_UA;
13459 				msg.hdr.nexus.initid = -1;
13460 				msg.hdr.nexus.targ_port = -1;
13461 				msg.hdr.nexus.targ_lun = lun->lun;
13462 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13463 				msg.ua.ua_all = 1;
13464 				msg.ua.ua_set = (set > 0);
13465 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13466 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13467 				mtx_unlock(&softc->ctl_lock); // XXX
13468 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13469 				    sizeof(msg.ua), M_WAITOK);
13470 				mtx_lock(&softc->ctl_lock);
13471 			}
13472 		}
13473 		mtx_sleep(&softc->thresh_thread, &softc->ctl_lock,
13474 		    PDROP | PRIBIO, "-", CTL_LBP_PERIOD * hz);
13475 	}
13476 	softc->thresh_thread = NULL;
13477 	kthread_exit();
13478 }
13479 
13480 static void
13481 ctl_enqueue_incoming(union ctl_io *io)
13482 {
13483 	struct ctl_softc *softc = CTL_SOFTC(io);
13484 	struct ctl_thread *thr;
13485 	u_int idx;
13486 
13487 	idx = (io->io_hdr.nexus.targ_port * 127 +
13488 	       io->io_hdr.nexus.initid) % worker_threads;
13489 	thr = &softc->threads[idx];
13490 	mtx_lock(&thr->queue_lock);
13491 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13492 	mtx_unlock(&thr->queue_lock);
13493 	wakeup(thr);
13494 }
13495 
13496 static void
13497 ctl_enqueue_rtr(union ctl_io *io)
13498 {
13499 	struct ctl_softc *softc = CTL_SOFTC(io);
13500 	struct ctl_thread *thr;
13501 
13502 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13503 	mtx_lock(&thr->queue_lock);
13504 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13505 	mtx_unlock(&thr->queue_lock);
13506 	wakeup(thr);
13507 }
13508 
13509 static void
13510 ctl_enqueue_done(union ctl_io *io)
13511 {
13512 	struct ctl_softc *softc = CTL_SOFTC(io);
13513 	struct ctl_thread *thr;
13514 
13515 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13516 	mtx_lock(&thr->queue_lock);
13517 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13518 	mtx_unlock(&thr->queue_lock);
13519 	wakeup(thr);
13520 }
13521 
13522 static void
13523 ctl_enqueue_isc(union ctl_io *io)
13524 {
13525 	struct ctl_softc *softc = CTL_SOFTC(io);
13526 	struct ctl_thread *thr;
13527 
13528 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13529 	mtx_lock(&thr->queue_lock);
13530 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13531 	mtx_unlock(&thr->queue_lock);
13532 	wakeup(thr);
13533 }
13534 
13535 /*
13536  *  vim: ts=8
13537  */
13538