xref: /freebsd/sys/cam/ctl/ctl.c (revision a4dc509f723944821bcfcc52005ff87c9a5dee5b)
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * Copyright (c) 2015 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 copan_debugconf_subpage debugconf_page_default = {
97 	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
98 	DBGCNF_SUBPAGE_CODE,		/* subpage */
99 	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
100 	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
101 	DBGCNF_VERSION,			/* page_version */
102 	{CTL_TIME_IO_DEFAULT_SECS>>8,
103 	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
104 };
105 
106 const static struct copan_debugconf_subpage debugconf_page_changeable = {
107 	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
108 	DBGCNF_SUBPAGE_CODE,		/* subpage */
109 	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
110 	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
111 	0,				/* page_version */
112 	{0xff,0xff},			/* ctl_time_io_secs */
113 };
114 
115 const static struct scsi_da_rw_recovery_page rw_er_page_default = {
116 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
117 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
118 	/*byte3*/SMS_RWER_AWRE|SMS_RWER_ARRE,
119 	/*read_retry_count*/0,
120 	/*correction_span*/0,
121 	/*head_offset_count*/0,
122 	/*data_strobe_offset_cnt*/0,
123 	/*byte8*/SMS_RWER_LBPERE,
124 	/*write_retry_count*/0,
125 	/*reserved2*/0,
126 	/*recovery_time_limit*/{0, 0},
127 };
128 
129 const static struct scsi_da_rw_recovery_page rw_er_page_changeable = {
130 	/*page_code*/SMS_RW_ERROR_RECOVERY_PAGE,
131 	/*page_length*/sizeof(struct scsi_da_rw_recovery_page) - 2,
132 	/*byte3*/0,
133 	/*read_retry_count*/0,
134 	/*correction_span*/0,
135 	/*head_offset_count*/0,
136 	/*data_strobe_offset_cnt*/0,
137 	/*byte8*/0,
138 	/*write_retry_count*/0,
139 	/*reserved2*/0,
140 	/*recovery_time_limit*/{0, 0},
141 };
142 
143 const static struct scsi_format_page format_page_default = {
144 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
145 	/*page_length*/sizeof(struct scsi_format_page) - 2,
146 	/*tracks_per_zone*/ {0, 0},
147 	/*alt_sectors_per_zone*/ {0, 0},
148 	/*alt_tracks_per_zone*/ {0, 0},
149 	/*alt_tracks_per_lun*/ {0, 0},
150 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
151 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
152 	/*bytes_per_sector*/ {0, 0},
153 	/*interleave*/ {0, 0},
154 	/*track_skew*/ {0, 0},
155 	/*cylinder_skew*/ {0, 0},
156 	/*flags*/ SFP_HSEC,
157 	/*reserved*/ {0, 0, 0}
158 };
159 
160 const static struct scsi_format_page format_page_changeable = {
161 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
162 	/*page_length*/sizeof(struct scsi_format_page) - 2,
163 	/*tracks_per_zone*/ {0, 0},
164 	/*alt_sectors_per_zone*/ {0, 0},
165 	/*alt_tracks_per_zone*/ {0, 0},
166 	/*alt_tracks_per_lun*/ {0, 0},
167 	/*sectors_per_track*/ {0, 0},
168 	/*bytes_per_sector*/ {0, 0},
169 	/*interleave*/ {0, 0},
170 	/*track_skew*/ {0, 0},
171 	/*cylinder_skew*/ {0, 0},
172 	/*flags*/ 0,
173 	/*reserved*/ {0, 0, 0}
174 };
175 
176 const static struct scsi_rigid_disk_page rigid_disk_page_default = {
177 	/*page_code*/SMS_RIGID_DISK_PAGE,
178 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
179 	/*cylinders*/ {0, 0, 0},
180 	/*heads*/ CTL_DEFAULT_HEADS,
181 	/*start_write_precomp*/ {0, 0, 0},
182 	/*start_reduced_current*/ {0, 0, 0},
183 	/*step_rate*/ {0, 0},
184 	/*landing_zone_cylinder*/ {0, 0, 0},
185 	/*rpl*/ SRDP_RPL_DISABLED,
186 	/*rotational_offset*/ 0,
187 	/*reserved1*/ 0,
188 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
189 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
190 	/*reserved2*/ {0, 0}
191 };
192 
193 const static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
194 	/*page_code*/SMS_RIGID_DISK_PAGE,
195 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
196 	/*cylinders*/ {0, 0, 0},
197 	/*heads*/ 0,
198 	/*start_write_precomp*/ {0, 0, 0},
199 	/*start_reduced_current*/ {0, 0, 0},
200 	/*step_rate*/ {0, 0},
201 	/*landing_zone_cylinder*/ {0, 0, 0},
202 	/*rpl*/ 0,
203 	/*rotational_offset*/ 0,
204 	/*reserved1*/ 0,
205 	/*rotation_rate*/ {0, 0},
206 	/*reserved2*/ {0, 0}
207 };
208 
209 const static struct scsi_caching_page caching_page_default = {
210 	/*page_code*/SMS_CACHING_PAGE,
211 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
212 	/*flags1*/ SCP_DISC | SCP_WCE,
213 	/*ret_priority*/ 0,
214 	/*disable_pf_transfer_len*/ {0xff, 0xff},
215 	/*min_prefetch*/ {0, 0},
216 	/*max_prefetch*/ {0xff, 0xff},
217 	/*max_pf_ceiling*/ {0xff, 0xff},
218 	/*flags2*/ 0,
219 	/*cache_segments*/ 0,
220 	/*cache_seg_size*/ {0, 0},
221 	/*reserved*/ 0,
222 	/*non_cache_seg_size*/ {0, 0, 0}
223 };
224 
225 const static struct scsi_caching_page caching_page_changeable = {
226 	/*page_code*/SMS_CACHING_PAGE,
227 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
228 	/*flags1*/ SCP_WCE | SCP_RCD,
229 	/*ret_priority*/ 0,
230 	/*disable_pf_transfer_len*/ {0, 0},
231 	/*min_prefetch*/ {0, 0},
232 	/*max_prefetch*/ {0, 0},
233 	/*max_pf_ceiling*/ {0, 0},
234 	/*flags2*/ 0,
235 	/*cache_segments*/ 0,
236 	/*cache_seg_size*/ {0, 0},
237 	/*reserved*/ 0,
238 	/*non_cache_seg_size*/ {0, 0, 0}
239 };
240 
241 const static struct scsi_control_page control_page_default = {
242 	/*page_code*/SMS_CONTROL_MODE_PAGE,
243 	/*page_length*/sizeof(struct scsi_control_page) - 2,
244 	/*rlec*/0,
245 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
246 	/*eca_and_aen*/0,
247 	/*flags4*/SCP_TAS,
248 	/*aen_holdoff_period*/{0, 0},
249 	/*busy_timeout_period*/{0, 0},
250 	/*extended_selftest_completion_time*/{0, 0}
251 };
252 
253 const static struct scsi_control_page control_page_changeable = {
254 	/*page_code*/SMS_CONTROL_MODE_PAGE,
255 	/*page_length*/sizeof(struct scsi_control_page) - 2,
256 	/*rlec*/SCP_DSENSE,
257 	/*queue_flags*/SCP_QUEUE_ALG_MASK,
258 	/*eca_and_aen*/SCP_SWP,
259 	/*flags4*/0,
260 	/*aen_holdoff_period*/{0, 0},
261 	/*busy_timeout_period*/{0, 0},
262 	/*extended_selftest_completion_time*/{0, 0}
263 };
264 
265 #define CTL_CEM_LEN	(sizeof(struct scsi_control_ext_page) - 4)
266 
267 const static struct scsi_control_ext_page control_ext_page_default = {
268 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
269 	/*subpage_code*/0x01,
270 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
271 	/*flags*/0,
272 	/*prio*/0,
273 	/*max_sense*/0
274 };
275 
276 const static struct scsi_control_ext_page control_ext_page_changeable = {
277 	/*page_code*/SMS_CONTROL_MODE_PAGE | SMPH_SPF,
278 	/*subpage_code*/0x01,
279 	/*page_length*/{CTL_CEM_LEN >> 8, CTL_CEM_LEN},
280 	/*flags*/0,
281 	/*prio*/0,
282 	/*max_sense*/0
283 };
284 
285 const static struct scsi_info_exceptions_page ie_page_default = {
286 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
287 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
288 	/*info_flags*/SIEP_FLAGS_DEXCPT,
289 	/*mrie*/0,
290 	/*interval_timer*/{0, 0, 0, 0},
291 	/*report_count*/{0, 0, 0, 0}
292 };
293 
294 const static struct scsi_info_exceptions_page ie_page_changeable = {
295 	/*page_code*/SMS_INFO_EXCEPTIONS_PAGE,
296 	/*page_length*/sizeof(struct scsi_info_exceptions_page) - 2,
297 	/*info_flags*/0,
298 	/*mrie*/0,
299 	/*interval_timer*/{0, 0, 0, 0},
300 	/*report_count*/{0, 0, 0, 0}
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*/0,
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 
411 /*
412  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
413  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
414  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
415  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
416  */
417 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
418 
419 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
420 				  int param);
421 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
422 static void ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest);
423 static int ctl_init(void);
424 void ctl_shutdown(void);
425 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
426 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
427 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
428 static void ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
429 			      struct ctl_ooa *ooa_hdr,
430 			      struct ctl_ooa_entry *kern_entries);
431 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
432 		     struct thread *td);
433 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
434 			 struct ctl_be_lun *be_lun);
435 static int ctl_free_lun(struct ctl_lun *lun);
436 static void ctl_create_lun(struct ctl_be_lun *be_lun);
437 static struct ctl_port * ctl_io_port(struct ctl_io_hdr *io_hdr);
438 
439 static int ctl_do_mode_select(union ctl_io *io);
440 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
441 			   uint64_t res_key, uint64_t sa_res_key,
442 			   uint8_t type, uint32_t residx,
443 			   struct ctl_scsiio *ctsio,
444 			   struct scsi_per_res_out *cdb,
445 			   struct scsi_per_res_out_parms* param);
446 static void ctl_pro_preempt_other(struct ctl_lun *lun,
447 				  union ctl_ha_msg *msg);
448 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
449 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
450 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
451 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
452 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
453 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
454 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
455 					 int alloc_len);
456 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
457 					 int alloc_len);
458 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
459 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
460 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
461 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
462 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
463 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2,
464     bool seq);
465 static ctl_action ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2);
466 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
467     union ctl_io *pending_io, union ctl_io *ooa_io);
468 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
469 				union ctl_io *starting_io);
470 static int ctl_check_blocked(struct ctl_lun *lun);
471 static int ctl_scsiio_lun_check(struct ctl_lun *lun,
472 				const struct ctl_cmd_entry *entry,
473 				struct ctl_scsiio *ctsio);
474 static void ctl_failover_lun(union ctl_io *io);
475 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
476 			       struct ctl_scsiio *ctsio);
477 static int ctl_scsiio(struct ctl_scsiio *ctsio);
478 
479 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
480 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
481 			    ctl_ua_type ua_type);
482 static int ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io,
483 			 ctl_ua_type ua_type);
484 static int ctl_lun_reset(struct ctl_softc *ctl_softc, 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 int ctl_i_t_nexus_reset(union ctl_io *io);
489 static int ctl_query_async_event(union ctl_io *io);
490 static void ctl_run_task(union ctl_io *io);
491 #ifdef CTL_IO_DELAY
492 static void ctl_datamove_timer_wakeup(void *arg);
493 static void ctl_done_timer_wakeup(void *arg);
494 #endif /* CTL_IO_DELAY */
495 
496 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
497 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
498 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
499 static void ctl_datamove_remote_write(union ctl_io *io);
500 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
501 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
502 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
503 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
504 				    ctl_ha_dt_cb callback);
505 static void ctl_datamove_remote_read(union ctl_io *io);
506 static void ctl_datamove_remote(union ctl_io *io);
507 static void ctl_process_done(union ctl_io *io);
508 static void ctl_lun_thread(void *arg);
509 static void ctl_thresh_thread(void *arg);
510 static void ctl_work_thread(void *arg);
511 static void ctl_enqueue_incoming(union ctl_io *io);
512 static void ctl_enqueue_rtr(union ctl_io *io);
513 static void ctl_enqueue_done(union ctl_io *io);
514 static void ctl_enqueue_isc(union ctl_io *io);
515 static const struct ctl_cmd_entry *
516     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
517 static const struct ctl_cmd_entry *
518     ctl_validate_command(struct ctl_scsiio *ctsio);
519 static int ctl_cmd_applicable(uint8_t lun_type,
520     const struct ctl_cmd_entry *entry);
521 
522 static uint64_t ctl_get_prkey(struct ctl_lun *lun, uint32_t residx);
523 static void ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx);
524 static void ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx);
525 static void ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key);
526 
527 /*
528  * Load the serialization table.  This isn't very pretty, but is probably
529  * the easiest way to do it.
530  */
531 #include "ctl_ser_table.c"
532 
533 /*
534  * We only need to define open, close and ioctl routines for this driver.
535  */
536 static struct cdevsw ctl_cdevsw = {
537 	.d_version =	D_VERSION,
538 	.d_flags =	0,
539 	.d_open =	ctl_open,
540 	.d_close =	ctl_close,
541 	.d_ioctl =	ctl_ioctl,
542 	.d_name =	"ctl",
543 };
544 
545 
546 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
547 
548 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
549 
550 static moduledata_t ctl_moduledata = {
551 	"ctl",
552 	ctl_module_event_handler,
553 	NULL
554 };
555 
556 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
557 MODULE_VERSION(ctl, 1);
558 
559 static struct ctl_frontend ha_frontend =
560 {
561 	.name = "ha",
562 };
563 
564 static void
565 ctl_ha_datamove(union ctl_io *io)
566 {
567 	struct ctl_lun *lun;
568 	struct ctl_sg_entry *sgl;
569 	union ctl_ha_msg msg;
570 	uint32_t sg_entries_sent;
571 	int do_sg_copy, i, j;
572 
573 	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
574 	memset(&msg.dt, 0, sizeof(msg.dt));
575 	msg.hdr.msg_type = CTL_MSG_DATAMOVE;
576 	msg.hdr.original_sc = io->io_hdr.original_sc;
577 	msg.hdr.serializing_sc = io;
578 	msg.hdr.nexus = io->io_hdr.nexus;
579 	msg.hdr.status = io->io_hdr.status;
580 	msg.dt.flags = io->io_hdr.flags;
581 
582 	/*
583 	 * We convert everything into a S/G list here.  We can't
584 	 * pass by reference, only by value between controllers.
585 	 * So we can't pass a pointer to the S/G list, only as many
586 	 * S/G entries as we can fit in here.  If it's possible for
587 	 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
588 	 * then we need to break this up into multiple transfers.
589 	 */
590 	if (io->scsiio.kern_sg_entries == 0) {
591 		msg.dt.kern_sg_entries = 1;
592 #if 0
593 		if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
594 			msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
595 		} else {
596 			/* XXX KDM use busdma here! */
597 			msg.dt.sg_list[0].addr =
598 			    (void *)vtophys(io->scsiio.kern_data_ptr);
599 		}
600 #else
601 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
602 		    ("HA does not support BUS_ADDR"));
603 		msg.dt.sg_list[0].addr = io->scsiio.kern_data_ptr;
604 #endif
605 		msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
606 		do_sg_copy = 0;
607 	} else {
608 		msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
609 		do_sg_copy = 1;
610 	}
611 
612 	msg.dt.kern_data_len = io->scsiio.kern_data_len;
613 	msg.dt.kern_total_len = io->scsiio.kern_total_len;
614 	msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
615 	msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
616 	msg.dt.sg_sequence = 0;
617 
618 	/*
619 	 * Loop until we've sent all of the S/G entries.  On the
620 	 * other end, we'll recompose these S/G entries into one
621 	 * contiguous list before processing.
622 	 */
623 	for (sg_entries_sent = 0; sg_entries_sent < msg.dt.kern_sg_entries;
624 	    msg.dt.sg_sequence++) {
625 		msg.dt.cur_sg_entries = MIN((sizeof(msg.dt.sg_list) /
626 		    sizeof(msg.dt.sg_list[0])),
627 		    msg.dt.kern_sg_entries - sg_entries_sent);
628 		if (do_sg_copy != 0) {
629 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
630 			for (i = sg_entries_sent, j = 0;
631 			     i < msg.dt.cur_sg_entries; i++, j++) {
632 #if 0
633 				if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
634 					msg.dt.sg_list[j].addr = sgl[i].addr;
635 				} else {
636 					/* XXX KDM use busdma here! */
637 					msg.dt.sg_list[j].addr =
638 					    (void *)vtophys(sgl[i].addr);
639 				}
640 #else
641 				KASSERT((io->io_hdr.flags &
642 				    CTL_FLAG_BUS_ADDR) == 0,
643 				    ("HA does not support BUS_ADDR"));
644 				msg.dt.sg_list[j].addr = sgl[i].addr;
645 #endif
646 				msg.dt.sg_list[j].len = sgl[i].len;
647 			}
648 		}
649 
650 		sg_entries_sent += msg.dt.cur_sg_entries;
651 		msg.dt.sg_last = (sg_entries_sent >= msg.dt.kern_sg_entries);
652 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
653 		    sizeof(msg.dt) - sizeof(msg.dt.sg_list) +
654 		    sizeof(struct ctl_sg_entry) * msg.dt.cur_sg_entries,
655 		    M_WAITOK) > CTL_HA_STATUS_SUCCESS) {
656 			io->io_hdr.port_status = 31341;
657 			io->scsiio.be_move_done(io);
658 			return;
659 		}
660 		msg.dt.sent_sg_entries = sg_entries_sent;
661 	}
662 
663 	/*
664 	 * Officially handover the request from us to peer.
665 	 * If failover has just happened, then we must return error.
666 	 * If failover happen just after, then it is not our problem.
667 	 */
668 	if (lun)
669 		mtx_lock(&lun->lun_lock);
670 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
671 		if (lun)
672 			mtx_unlock(&lun->lun_lock);
673 		io->io_hdr.port_status = 31342;
674 		io->scsiio.be_move_done(io);
675 		return;
676 	}
677 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
678 	io->io_hdr.flags |= CTL_FLAG_DMA_INPROG;
679 	if (lun)
680 		mtx_unlock(&lun->lun_lock);
681 }
682 
683 static void
684 ctl_ha_done(union ctl_io *io)
685 {
686 	union ctl_ha_msg msg;
687 
688 	if (io->io_hdr.io_type == CTL_IO_SCSI) {
689 		memset(&msg, 0, sizeof(msg));
690 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
691 		msg.hdr.original_sc = io->io_hdr.original_sc;
692 		msg.hdr.nexus = io->io_hdr.nexus;
693 		msg.hdr.status = io->io_hdr.status;
694 		msg.scsi.scsi_status = io->scsiio.scsi_status;
695 		msg.scsi.tag_num = io->scsiio.tag_num;
696 		msg.scsi.tag_type = io->scsiio.tag_type;
697 		msg.scsi.sense_len = io->scsiio.sense_len;
698 		msg.scsi.sense_residual = io->scsiio.sense_residual;
699 		msg.scsi.residual = io->scsiio.residual;
700 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
701 		    io->scsiio.sense_len);
702 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
703 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
704 		    msg.scsi.sense_len, M_WAITOK);
705 	}
706 	ctl_free_io(io);
707 }
708 
709 static void
710 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
711 			    union ctl_ha_msg *msg_info)
712 {
713 	struct ctl_scsiio *ctsio;
714 
715 	if (msg_info->hdr.original_sc == NULL) {
716 		printf("%s: original_sc == NULL!\n", __func__);
717 		/* XXX KDM now what? */
718 		return;
719 	}
720 
721 	ctsio = &msg_info->hdr.original_sc->scsiio;
722 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
723 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
724 	ctsio->io_hdr.status = msg_info->hdr.status;
725 	ctsio->scsi_status = msg_info->scsi.scsi_status;
726 	ctsio->sense_len = msg_info->scsi.sense_len;
727 	ctsio->sense_residual = msg_info->scsi.sense_residual;
728 	ctsio->residual = msg_info->scsi.residual;
729 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
730 	       msg_info->scsi.sense_len);
731 	ctl_enqueue_isc((union ctl_io *)ctsio);
732 }
733 
734 static void
735 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
736 				union ctl_ha_msg *msg_info)
737 {
738 	struct ctl_scsiio *ctsio;
739 
740 	if (msg_info->hdr.serializing_sc == NULL) {
741 		printf("%s: serializing_sc == NULL!\n", __func__);
742 		/* XXX KDM now what? */
743 		return;
744 	}
745 
746 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
747 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
748 	ctl_enqueue_isc((union ctl_io *)ctsio);
749 }
750 
751 void
752 ctl_isc_announce_lun(struct ctl_lun *lun)
753 {
754 	struct ctl_softc *softc = lun->ctl_softc;
755 	union ctl_ha_msg *msg;
756 	struct ctl_ha_msg_lun_pr_key pr_key;
757 	int i, k;
758 
759 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
760 		return;
761 	mtx_lock(&lun->lun_lock);
762 	i = sizeof(msg->lun);
763 	if (lun->lun_devid)
764 		i += lun->lun_devid->len;
765 	i += sizeof(pr_key) * lun->pr_key_count;
766 alloc:
767 	mtx_unlock(&lun->lun_lock);
768 	msg = malloc(i, M_CTL, M_WAITOK);
769 	mtx_lock(&lun->lun_lock);
770 	k = sizeof(msg->lun);
771 	if (lun->lun_devid)
772 		k += lun->lun_devid->len;
773 	k += sizeof(pr_key) * lun->pr_key_count;
774 	if (i < k) {
775 		free(msg, M_CTL);
776 		i = k;
777 		goto alloc;
778 	}
779 	bzero(&msg->lun, sizeof(msg->lun));
780 	msg->hdr.msg_type = CTL_MSG_LUN_SYNC;
781 	msg->hdr.nexus.targ_lun = lun->lun;
782 	msg->hdr.nexus.targ_mapped_lun = lun->lun;
783 	msg->lun.flags = lun->flags;
784 	msg->lun.pr_generation = lun->pr_generation;
785 	msg->lun.pr_res_idx = lun->pr_res_idx;
786 	msg->lun.pr_res_type = lun->pr_res_type;
787 	msg->lun.pr_key_count = lun->pr_key_count;
788 	i = 0;
789 	if (lun->lun_devid) {
790 		msg->lun.lun_devid_len = lun->lun_devid->len;
791 		memcpy(&msg->lun.data[i], lun->lun_devid->data,
792 		    msg->lun.lun_devid_len);
793 		i += msg->lun.lun_devid_len;
794 	}
795 	for (k = 0; k < CTL_MAX_INITIATORS; k++) {
796 		if ((pr_key.pr_key = ctl_get_prkey(lun, k)) == 0)
797 			continue;
798 		pr_key.pr_iid = k;
799 		memcpy(&msg->lun.data[i], &pr_key, sizeof(pr_key));
800 		i += sizeof(pr_key);
801 	}
802 	mtx_unlock(&lun->lun_lock);
803 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
804 	    M_WAITOK);
805 	free(msg, M_CTL);
806 
807 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
808 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
809 			ctl_isc_announce_mode(lun, -1,
810 			    lun->mode_pages.index[i].page_code & SMPH_PC_MASK,
811 			    lun->mode_pages.index[i].subpage);
812 		}
813 	}
814 }
815 
816 void
817 ctl_isc_announce_port(struct ctl_port *port)
818 {
819 	struct ctl_softc *softc = port->ctl_softc;
820 	union ctl_ha_msg *msg;
821 	int i;
822 
823 	if (port->targ_port < softc->port_min ||
824 	    port->targ_port >= softc->port_max ||
825 	    softc->ha_link != CTL_HA_LINK_ONLINE)
826 		return;
827 	i = sizeof(msg->port) + strlen(port->port_name) + 1;
828 	if (port->lun_map)
829 		i += sizeof(uint32_t) * CTL_MAX_LUNS;
830 	if (port->port_devid)
831 		i += port->port_devid->len;
832 	if (port->target_devid)
833 		i += port->target_devid->len;
834 	if (port->init_devid)
835 		i += port->init_devid->len;
836 	msg = malloc(i, M_CTL, M_WAITOK);
837 	bzero(&msg->port, sizeof(msg->port));
838 	msg->hdr.msg_type = CTL_MSG_PORT_SYNC;
839 	msg->hdr.nexus.targ_port = port->targ_port;
840 	msg->port.port_type = port->port_type;
841 	msg->port.physical_port = port->physical_port;
842 	msg->port.virtual_port = port->virtual_port;
843 	msg->port.status = port->status;
844 	i = 0;
845 	msg->port.name_len = sprintf(&msg->port.data[i],
846 	    "%d:%s", softc->ha_id, port->port_name) + 1;
847 	i += msg->port.name_len;
848 	if (port->lun_map) {
849 		msg->port.lun_map_len = sizeof(uint32_t) * CTL_MAX_LUNS;
850 		memcpy(&msg->port.data[i], port->lun_map,
851 		    msg->port.lun_map_len);
852 		i += msg->port.lun_map_len;
853 	}
854 	if (port->port_devid) {
855 		msg->port.port_devid_len = port->port_devid->len;
856 		memcpy(&msg->port.data[i], port->port_devid->data,
857 		    msg->port.port_devid_len);
858 		i += msg->port.port_devid_len;
859 	}
860 	if (port->target_devid) {
861 		msg->port.target_devid_len = port->target_devid->len;
862 		memcpy(&msg->port.data[i], port->target_devid->data,
863 		    msg->port.target_devid_len);
864 		i += msg->port.target_devid_len;
865 	}
866 	if (port->init_devid) {
867 		msg->port.init_devid_len = port->init_devid->len;
868 		memcpy(&msg->port.data[i], port->init_devid->data,
869 		    msg->port.init_devid_len);
870 		i += msg->port.init_devid_len;
871 	}
872 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->port, sizeof(msg->port) + i,
873 	    M_WAITOK);
874 	free(msg, M_CTL);
875 }
876 
877 void
878 ctl_isc_announce_iid(struct ctl_port *port, int iid)
879 {
880 	struct ctl_softc *softc = port->ctl_softc;
881 	union ctl_ha_msg *msg;
882 	int i, l;
883 
884 	if (port->targ_port < softc->port_min ||
885 	    port->targ_port >= softc->port_max ||
886 	    softc->ha_link != CTL_HA_LINK_ONLINE)
887 		return;
888 	mtx_lock(&softc->ctl_lock);
889 	i = sizeof(msg->iid);
890 	l = 0;
891 	if (port->wwpn_iid[iid].name)
892 		l = strlen(port->wwpn_iid[iid].name) + 1;
893 	i += l;
894 	msg = malloc(i, M_CTL, M_NOWAIT);
895 	if (msg == NULL) {
896 		mtx_unlock(&softc->ctl_lock);
897 		return;
898 	}
899 	bzero(&msg->iid, sizeof(msg->iid));
900 	msg->hdr.msg_type = CTL_MSG_IID_SYNC;
901 	msg->hdr.nexus.targ_port = port->targ_port;
902 	msg->hdr.nexus.initid = iid;
903 	msg->iid.in_use = port->wwpn_iid[iid].in_use;
904 	msg->iid.name_len = l;
905 	msg->iid.wwpn = port->wwpn_iid[iid].wwpn;
906 	if (port->wwpn_iid[iid].name)
907 		strlcpy(msg->iid.data, port->wwpn_iid[iid].name, l);
908 	mtx_unlock(&softc->ctl_lock);
909 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg->iid, i, M_NOWAIT);
910 	free(msg, M_CTL);
911 }
912 
913 void
914 ctl_isc_announce_mode(struct ctl_lun *lun, uint32_t initidx,
915     uint8_t page, uint8_t subpage)
916 {
917 	struct ctl_softc *softc = lun->ctl_softc;
918 	union ctl_ha_msg msg;
919 	int i;
920 
921 	if (softc->ha_link != CTL_HA_LINK_ONLINE)
922 		return;
923 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
924 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
925 		    page && lun->mode_pages.index[i].subpage == subpage)
926 			break;
927 	}
928 	if (i == CTL_NUM_MODE_PAGES)
929 		return;
930 	bzero(&msg.mode, sizeof(msg.mode));
931 	msg.hdr.msg_type = CTL_MSG_MODE_SYNC;
932 	msg.hdr.nexus.targ_port = initidx / CTL_MAX_INIT_PER_PORT;
933 	msg.hdr.nexus.initid = initidx % CTL_MAX_INIT_PER_PORT;
934 	msg.hdr.nexus.targ_lun = lun->lun;
935 	msg.hdr.nexus.targ_mapped_lun = lun->lun;
936 	msg.mode.page_code = page;
937 	msg.mode.subpage = subpage;
938 	msg.mode.page_len = lun->mode_pages.index[i].page_len;
939 	memcpy(msg.mode.data, lun->mode_pages.index[i].page_data,
940 	    msg.mode.page_len);
941 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.mode, sizeof(msg.mode),
942 	    M_WAITOK);
943 }
944 
945 static void
946 ctl_isc_ha_link_up(struct ctl_softc *softc)
947 {
948 	struct ctl_port *port;
949 	struct ctl_lun *lun;
950 	union ctl_ha_msg msg;
951 	int i;
952 
953 	/* Announce this node parameters to peer for validation. */
954 	msg.login.msg_type = CTL_MSG_LOGIN;
955 	msg.login.version = CTL_HA_VERSION;
956 	msg.login.ha_mode = softc->ha_mode;
957 	msg.login.ha_id = softc->ha_id;
958 	msg.login.max_luns = CTL_MAX_LUNS;
959 	msg.login.max_ports = CTL_MAX_PORTS;
960 	msg.login.max_init_per_port = CTL_MAX_INIT_PER_PORT;
961 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg.login, sizeof(msg.login),
962 	    M_WAITOK);
963 
964 	STAILQ_FOREACH(port, &softc->port_list, links) {
965 		ctl_isc_announce_port(port);
966 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
967 			if (port->wwpn_iid[i].in_use)
968 				ctl_isc_announce_iid(port, i);
969 		}
970 	}
971 	STAILQ_FOREACH(lun, &softc->lun_list, links)
972 		ctl_isc_announce_lun(lun);
973 }
974 
975 static void
976 ctl_isc_ha_link_down(struct ctl_softc *softc)
977 {
978 	struct ctl_port *port;
979 	struct ctl_lun *lun;
980 	union ctl_io *io;
981 	int i;
982 
983 	mtx_lock(&softc->ctl_lock);
984 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
985 		mtx_lock(&lun->lun_lock);
986 		if (lun->flags & CTL_LUN_PEER_SC_PRIMARY) {
987 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
988 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
989 		}
990 		mtx_unlock(&lun->lun_lock);
991 
992 		mtx_unlock(&softc->ctl_lock);
993 		io = ctl_alloc_io(softc->othersc_pool);
994 		mtx_lock(&softc->ctl_lock);
995 		ctl_zero_io(io);
996 		io->io_hdr.msg_type = CTL_MSG_FAILOVER;
997 		io->io_hdr.nexus.targ_mapped_lun = lun->lun;
998 		ctl_enqueue_isc(io);
999 	}
1000 
1001 	STAILQ_FOREACH(port, &softc->port_list, links) {
1002 		if (port->targ_port >= softc->port_min &&
1003 		    port->targ_port < softc->port_max)
1004 			continue;
1005 		port->status &= ~CTL_PORT_STATUS_ONLINE;
1006 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1007 			port->wwpn_iid[i].in_use = 0;
1008 			free(port->wwpn_iid[i].name, M_CTL);
1009 			port->wwpn_iid[i].name = NULL;
1010 		}
1011 	}
1012 	mtx_unlock(&softc->ctl_lock);
1013 }
1014 
1015 static void
1016 ctl_isc_ua(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1017 {
1018 	struct ctl_lun *lun;
1019 	uint32_t iid = ctl_get_initindex(&msg->hdr.nexus);
1020 
1021 	mtx_lock(&softc->ctl_lock);
1022 	if (msg->hdr.nexus.targ_lun < CTL_MAX_LUNS &&
1023 	    (lun = softc->ctl_luns[msg->hdr.nexus.targ_mapped_lun]) != NULL) {
1024 		mtx_lock(&lun->lun_lock);
1025 		mtx_unlock(&softc->ctl_lock);
1026 		if (msg->ua.ua_type == CTL_UA_THIN_PROV_THRES &&
1027 		    msg->ua.ua_set)
1028 			memcpy(lun->ua_tpt_info, msg->ua.ua_info, 8);
1029 		if (msg->ua.ua_all) {
1030 			if (msg->ua.ua_set)
1031 				ctl_est_ua_all(lun, iid, msg->ua.ua_type);
1032 			else
1033 				ctl_clr_ua_all(lun, iid, msg->ua.ua_type);
1034 		} else {
1035 			if (msg->ua.ua_set)
1036 				ctl_est_ua(lun, iid, msg->ua.ua_type);
1037 			else
1038 				ctl_clr_ua(lun, iid, msg->ua.ua_type);
1039 		}
1040 		mtx_unlock(&lun->lun_lock);
1041 	} else
1042 		mtx_unlock(&softc->ctl_lock);
1043 }
1044 
1045 static void
1046 ctl_isc_lun_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1047 {
1048 	struct ctl_lun *lun;
1049 	struct ctl_ha_msg_lun_pr_key pr_key;
1050 	int i, k;
1051 	ctl_lun_flags oflags;
1052 	uint32_t targ_lun;
1053 
1054 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1055 	mtx_lock(&softc->ctl_lock);
1056 	if ((targ_lun >= CTL_MAX_LUNS) ||
1057 	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1058 		mtx_unlock(&softc->ctl_lock);
1059 		return;
1060 	}
1061 	mtx_lock(&lun->lun_lock);
1062 	mtx_unlock(&softc->ctl_lock);
1063 	if (lun->flags & CTL_LUN_DISABLED) {
1064 		mtx_unlock(&lun->lun_lock);
1065 		return;
1066 	}
1067 	i = (lun->lun_devid != NULL) ? lun->lun_devid->len : 0;
1068 	if (msg->lun.lun_devid_len != i || (i > 0 &&
1069 	    memcmp(&msg->lun.data[0], lun->lun_devid->data, i) != 0)) {
1070 		mtx_unlock(&lun->lun_lock);
1071 		printf("%s: Received conflicting HA LUN %d\n",
1072 		    __func__, msg->hdr.nexus.targ_lun);
1073 		return;
1074 	} else {
1075 		/* Record whether peer is primary. */
1076 		oflags = lun->flags;
1077 		if ((msg->lun.flags & CTL_LUN_PRIMARY_SC) &&
1078 		    (msg->lun.flags & CTL_LUN_DISABLED) == 0)
1079 			lun->flags |= CTL_LUN_PEER_SC_PRIMARY;
1080 		else
1081 			lun->flags &= ~CTL_LUN_PEER_SC_PRIMARY;
1082 		if (oflags != lun->flags)
1083 			ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
1084 
1085 		/* If peer is primary and we are not -- use data */
1086 		if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
1087 		    (lun->flags & CTL_LUN_PEER_SC_PRIMARY)) {
1088 			lun->pr_generation = msg->lun.pr_generation;
1089 			lun->pr_res_idx = msg->lun.pr_res_idx;
1090 			lun->pr_res_type = msg->lun.pr_res_type;
1091 			lun->pr_key_count = msg->lun.pr_key_count;
1092 			for (k = 0; k < CTL_MAX_INITIATORS; k++)
1093 				ctl_clr_prkey(lun, k);
1094 			for (k = 0; k < msg->lun.pr_key_count; k++) {
1095 				memcpy(&pr_key, &msg->lun.data[i],
1096 				    sizeof(pr_key));
1097 				ctl_alloc_prkey(lun, pr_key.pr_iid);
1098 				ctl_set_prkey(lun, pr_key.pr_iid,
1099 				    pr_key.pr_key);
1100 				i += sizeof(pr_key);
1101 			}
1102 		}
1103 
1104 		mtx_unlock(&lun->lun_lock);
1105 		CTL_DEBUG_PRINT(("%s: Known LUN %d, peer is %s\n",
1106 		    __func__, msg->hdr.nexus.targ_lun,
1107 		    (msg->lun.flags & CTL_LUN_PRIMARY_SC) ?
1108 		    "primary" : "secondary"));
1109 
1110 		/* If we are primary but peer doesn't know -- notify */
1111 		if ((lun->flags & CTL_LUN_PRIMARY_SC) &&
1112 		    (msg->lun.flags & CTL_LUN_PEER_SC_PRIMARY) == 0)
1113 			ctl_isc_announce_lun(lun);
1114 	}
1115 }
1116 
1117 static void
1118 ctl_isc_port_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1119 {
1120 	struct ctl_port *port;
1121 	struct ctl_lun *lun;
1122 	int i, new;
1123 
1124 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1125 	if (port == NULL) {
1126 		CTL_DEBUG_PRINT(("%s: New port %d\n", __func__,
1127 		    msg->hdr.nexus.targ_port));
1128 		new = 1;
1129 		port = malloc(sizeof(*port), M_CTL, M_WAITOK | M_ZERO);
1130 		port->frontend = &ha_frontend;
1131 		port->targ_port = msg->hdr.nexus.targ_port;
1132 		port->fe_datamove = ctl_ha_datamove;
1133 		port->fe_done = ctl_ha_done;
1134 	} else if (port->frontend == &ha_frontend) {
1135 		CTL_DEBUG_PRINT(("%s: Updated port %d\n", __func__,
1136 		    msg->hdr.nexus.targ_port));
1137 		new = 0;
1138 	} else {
1139 		printf("%s: Received conflicting HA port %d\n",
1140 		    __func__, msg->hdr.nexus.targ_port);
1141 		return;
1142 	}
1143 	port->port_type = msg->port.port_type;
1144 	port->physical_port = msg->port.physical_port;
1145 	port->virtual_port = msg->port.virtual_port;
1146 	port->status = msg->port.status;
1147 	i = 0;
1148 	free(port->port_name, M_CTL);
1149 	port->port_name = strndup(&msg->port.data[i], msg->port.name_len,
1150 	    M_CTL);
1151 	i += msg->port.name_len;
1152 	if (msg->port.lun_map_len != 0) {
1153 		if (port->lun_map == NULL)
1154 			port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
1155 			    M_CTL, M_WAITOK);
1156 		memcpy(port->lun_map, &msg->port.data[i],
1157 		    sizeof(uint32_t) * CTL_MAX_LUNS);
1158 		i += msg->port.lun_map_len;
1159 	} else {
1160 		free(port->lun_map, M_CTL);
1161 		port->lun_map = NULL;
1162 	}
1163 	if (msg->port.port_devid_len != 0) {
1164 		if (port->port_devid == NULL ||
1165 		    port->port_devid->len != msg->port.port_devid_len) {
1166 			free(port->port_devid, M_CTL);
1167 			port->port_devid = malloc(sizeof(struct ctl_devid) +
1168 			    msg->port.port_devid_len, M_CTL, M_WAITOK);
1169 		}
1170 		memcpy(port->port_devid->data, &msg->port.data[i],
1171 		    msg->port.port_devid_len);
1172 		port->port_devid->len = msg->port.port_devid_len;
1173 		i += msg->port.port_devid_len;
1174 	} else {
1175 		free(port->port_devid, M_CTL);
1176 		port->port_devid = NULL;
1177 	}
1178 	if (msg->port.target_devid_len != 0) {
1179 		if (port->target_devid == NULL ||
1180 		    port->target_devid->len != msg->port.target_devid_len) {
1181 			free(port->target_devid, M_CTL);
1182 			port->target_devid = malloc(sizeof(struct ctl_devid) +
1183 			    msg->port.target_devid_len, M_CTL, M_WAITOK);
1184 		}
1185 		memcpy(port->target_devid->data, &msg->port.data[i],
1186 		    msg->port.target_devid_len);
1187 		port->target_devid->len = msg->port.target_devid_len;
1188 		i += msg->port.target_devid_len;
1189 	} else {
1190 		free(port->target_devid, M_CTL);
1191 		port->target_devid = NULL;
1192 	}
1193 	if (msg->port.init_devid_len != 0) {
1194 		if (port->init_devid == NULL ||
1195 		    port->init_devid->len != msg->port.init_devid_len) {
1196 			free(port->init_devid, M_CTL);
1197 			port->init_devid = malloc(sizeof(struct ctl_devid) +
1198 			    msg->port.init_devid_len, M_CTL, M_WAITOK);
1199 		}
1200 		memcpy(port->init_devid->data, &msg->port.data[i],
1201 		    msg->port.init_devid_len);
1202 		port->init_devid->len = msg->port.init_devid_len;
1203 		i += msg->port.init_devid_len;
1204 	} else {
1205 		free(port->init_devid, M_CTL);
1206 		port->init_devid = NULL;
1207 	}
1208 	if (new) {
1209 		if (ctl_port_register(port) != 0) {
1210 			printf("%s: ctl_port_register() failed with error\n",
1211 			    __func__);
1212 		}
1213 	}
1214 	mtx_lock(&softc->ctl_lock);
1215 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1216 		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
1217 			continue;
1218 		mtx_lock(&lun->lun_lock);
1219 		ctl_est_ua_all(lun, -1, CTL_UA_INQ_CHANGE);
1220 		mtx_unlock(&lun->lun_lock);
1221 	}
1222 	mtx_unlock(&softc->ctl_lock);
1223 }
1224 
1225 static void
1226 ctl_isc_iid_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1227 {
1228 	struct ctl_port *port;
1229 	int iid;
1230 
1231 	port = softc->ctl_ports[msg->hdr.nexus.targ_port];
1232 	if (port == NULL) {
1233 		printf("%s: Received IID for unknown port %d\n",
1234 		    __func__, msg->hdr.nexus.targ_port);
1235 		return;
1236 	}
1237 	iid = msg->hdr.nexus.initid;
1238 	port->wwpn_iid[iid].in_use = msg->iid.in_use;
1239 	port->wwpn_iid[iid].wwpn = msg->iid.wwpn;
1240 	free(port->wwpn_iid[iid].name, M_CTL);
1241 	if (msg->iid.name_len) {
1242 		port->wwpn_iid[iid].name = strndup(&msg->iid.data[0],
1243 		    msg->iid.name_len, M_CTL);
1244 	} else
1245 		port->wwpn_iid[iid].name = NULL;
1246 }
1247 
1248 static void
1249 ctl_isc_login(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1250 {
1251 
1252 	if (msg->login.version != CTL_HA_VERSION) {
1253 		printf("CTL HA peers have different versions %d != %d\n",
1254 		    msg->login.version, CTL_HA_VERSION);
1255 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1256 		return;
1257 	}
1258 	if (msg->login.ha_mode != softc->ha_mode) {
1259 		printf("CTL HA peers have different ha_mode %d != %d\n",
1260 		    msg->login.ha_mode, softc->ha_mode);
1261 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1262 		return;
1263 	}
1264 	if (msg->login.ha_id == softc->ha_id) {
1265 		printf("CTL HA peers have same ha_id %d\n", msg->login.ha_id);
1266 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1267 		return;
1268 	}
1269 	if (msg->login.max_luns != CTL_MAX_LUNS ||
1270 	    msg->login.max_ports != CTL_MAX_PORTS ||
1271 	    msg->login.max_init_per_port != CTL_MAX_INIT_PER_PORT) {
1272 		printf("CTL HA peers have different limits\n");
1273 		ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1274 		return;
1275 	}
1276 }
1277 
1278 static void
1279 ctl_isc_mode_sync(struct ctl_softc *softc, union ctl_ha_msg *msg, int len)
1280 {
1281 	struct ctl_lun *lun;
1282 	int i;
1283 	uint32_t initidx, targ_lun;
1284 
1285 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
1286 	mtx_lock(&softc->ctl_lock);
1287 	if ((targ_lun >= CTL_MAX_LUNS) ||
1288 	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
1289 		mtx_unlock(&softc->ctl_lock);
1290 		return;
1291 	}
1292 	mtx_lock(&lun->lun_lock);
1293 	mtx_unlock(&softc->ctl_lock);
1294 	if (lun->flags & CTL_LUN_DISABLED) {
1295 		mtx_unlock(&lun->lun_lock);
1296 		return;
1297 	}
1298 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
1299 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) ==
1300 		    msg->mode.page_code &&
1301 		    lun->mode_pages.index[i].subpage == msg->mode.subpage)
1302 			break;
1303 	}
1304 	if (i == CTL_NUM_MODE_PAGES) {
1305 		mtx_unlock(&lun->lun_lock);
1306 		return;
1307 	}
1308 	memcpy(lun->mode_pages.index[i].page_data, msg->mode.data,
1309 	    lun->mode_pages.index[i].page_len);
1310 	initidx = ctl_get_initindex(&msg->hdr.nexus);
1311 	if (initidx != -1)
1312 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
1313 	mtx_unlock(&lun->lun_lock);
1314 }
1315 
1316 /*
1317  * ISC (Inter Shelf Communication) event handler.  Events from the HA
1318  * subsystem come in here.
1319  */
1320 static void
1321 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
1322 {
1323 	struct ctl_softc *softc = control_softc;
1324 	union ctl_io *io;
1325 	struct ctl_prio *presio;
1326 	ctl_ha_status isc_status;
1327 
1328 	CTL_DEBUG_PRINT(("CTL: Isc Msg event %d\n", event));
1329 	if (event == CTL_HA_EVT_MSG_RECV) {
1330 		union ctl_ha_msg *msg, msgbuf;
1331 
1332 		if (param > sizeof(msgbuf))
1333 			msg = malloc(param, M_CTL, M_WAITOK);
1334 		else
1335 			msg = &msgbuf;
1336 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, msg, param,
1337 		    M_WAITOK);
1338 		if (isc_status != CTL_HA_STATUS_SUCCESS) {
1339 			printf("%s: Error receiving message: %d\n",
1340 			    __func__, isc_status);
1341 			if (msg != &msgbuf)
1342 				free(msg, M_CTL);
1343 			return;
1344 		}
1345 
1346 		CTL_DEBUG_PRINT(("CTL: msg_type %d\n", msg->msg_type));
1347 		switch (msg->hdr.msg_type) {
1348 		case CTL_MSG_SERIALIZE:
1349 			io = ctl_alloc_io(softc->othersc_pool);
1350 			ctl_zero_io(io);
1351 			// populate ctsio from msg
1352 			io->io_hdr.io_type = CTL_IO_SCSI;
1353 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
1354 			io->io_hdr.original_sc = msg->hdr.original_sc;
1355 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
1356 					    CTL_FLAG_IO_ACTIVE;
1357 			/*
1358 			 * If we're in serialization-only mode, we don't
1359 			 * want to go through full done processing.  Thus
1360 			 * the COPY flag.
1361 			 *
1362 			 * XXX KDM add another flag that is more specific.
1363 			 */
1364 			if (softc->ha_mode != CTL_HA_MODE_XFER)
1365 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
1366 			io->io_hdr.nexus = msg->hdr.nexus;
1367 #if 0
1368 			printf("port %u, iid %u, lun %u\n",
1369 			       io->io_hdr.nexus.targ_port,
1370 			       io->io_hdr.nexus.initid,
1371 			       io->io_hdr.nexus.targ_lun);
1372 #endif
1373 			io->scsiio.tag_num = msg->scsi.tag_num;
1374 			io->scsiio.tag_type = msg->scsi.tag_type;
1375 #ifdef CTL_TIME_IO
1376 			io->io_hdr.start_time = time_uptime;
1377 			getbinuptime(&io->io_hdr.start_bt);
1378 #endif /* CTL_TIME_IO */
1379 			io->scsiio.cdb_len = msg->scsi.cdb_len;
1380 			memcpy(io->scsiio.cdb, msg->scsi.cdb,
1381 			       CTL_MAX_CDBLEN);
1382 			if (softc->ha_mode == CTL_HA_MODE_XFER) {
1383 				const struct ctl_cmd_entry *entry;
1384 
1385 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
1386 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
1387 				io->io_hdr.flags |=
1388 					entry->flags & CTL_FLAG_DATA_MASK;
1389 			}
1390 			ctl_enqueue_isc(io);
1391 			break;
1392 
1393 		/* Performed on the Originating SC, XFER mode only */
1394 		case CTL_MSG_DATAMOVE: {
1395 			struct ctl_sg_entry *sgl;
1396 			int i, j;
1397 
1398 			io = msg->hdr.original_sc;
1399 			if (io == NULL) {
1400 				printf("%s: original_sc == NULL!\n", __func__);
1401 				/* XXX KDM do something here */
1402 				break;
1403 			}
1404 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
1405 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1406 			/*
1407 			 * Keep track of this, we need to send it back over
1408 			 * when the datamove is complete.
1409 			 */
1410 			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1411 			if (msg->hdr.status == CTL_SUCCESS)
1412 				io->io_hdr.status = msg->hdr.status;
1413 
1414 			if (msg->dt.sg_sequence == 0) {
1415 #ifdef CTL_TIME_IO
1416 				getbinuptime(&io->io_hdr.dma_start_bt);
1417 #endif
1418 				i = msg->dt.kern_sg_entries +
1419 				    msg->dt.kern_data_len /
1420 				    CTL_HA_DATAMOVE_SEGMENT + 1;
1421 				sgl = malloc(sizeof(*sgl) * i, M_CTL,
1422 				    M_WAITOK | M_ZERO);
1423 				io->io_hdr.remote_sglist = sgl;
1424 				io->io_hdr.local_sglist =
1425 				    &sgl[msg->dt.kern_sg_entries];
1426 
1427 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
1428 
1429 				io->scsiio.kern_sg_entries =
1430 					msg->dt.kern_sg_entries;
1431 				io->scsiio.rem_sg_entries =
1432 					msg->dt.kern_sg_entries;
1433 				io->scsiio.kern_data_len =
1434 					msg->dt.kern_data_len;
1435 				io->scsiio.kern_total_len =
1436 					msg->dt.kern_total_len;
1437 				io->scsiio.kern_data_resid =
1438 					msg->dt.kern_data_resid;
1439 				io->scsiio.kern_rel_offset =
1440 					msg->dt.kern_rel_offset;
1441 				io->io_hdr.flags &= ~CTL_FLAG_BUS_ADDR;
1442 				io->io_hdr.flags |= msg->dt.flags &
1443 				    CTL_FLAG_BUS_ADDR;
1444 			} else
1445 				sgl = (struct ctl_sg_entry *)
1446 					io->scsiio.kern_data_ptr;
1447 
1448 			for (i = msg->dt.sent_sg_entries, j = 0;
1449 			     i < (msg->dt.sent_sg_entries +
1450 			     msg->dt.cur_sg_entries); i++, j++) {
1451 				sgl[i].addr = msg->dt.sg_list[j].addr;
1452 				sgl[i].len = msg->dt.sg_list[j].len;
1453 
1454 #if 0
1455 				printf("%s: DATAMOVE: %p,%lu j=%d, i=%d\n",
1456 				    __func__, sgl[i].addr, sgl[i].len, j, i);
1457 #endif
1458 			}
1459 
1460 			/*
1461 			 * If this is the last piece of the I/O, we've got
1462 			 * the full S/G list.  Queue processing in the thread.
1463 			 * Otherwise wait for the next piece.
1464 			 */
1465 			if (msg->dt.sg_last != 0)
1466 				ctl_enqueue_isc(io);
1467 			break;
1468 		}
1469 		/* Performed on the Serializing (primary) SC, XFER mode only */
1470 		case CTL_MSG_DATAMOVE_DONE: {
1471 			if (msg->hdr.serializing_sc == NULL) {
1472 				printf("%s: serializing_sc == NULL!\n",
1473 				       __func__);
1474 				/* XXX KDM now what? */
1475 				break;
1476 			}
1477 			/*
1478 			 * We grab the sense information here in case
1479 			 * there was a failure, so we can return status
1480 			 * back to the initiator.
1481 			 */
1482 			io = msg->hdr.serializing_sc;
1483 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
1484 			io->io_hdr.flags &= ~CTL_FLAG_DMA_INPROG;
1485 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1486 			io->io_hdr.port_status = msg->scsi.fetd_status;
1487 			io->scsiio.residual = msg->scsi.residual;
1488 			if (msg->hdr.status != CTL_STATUS_NONE) {
1489 				io->io_hdr.status = msg->hdr.status;
1490 				io->scsiio.scsi_status = msg->scsi.scsi_status;
1491 				io->scsiio.sense_len = msg->scsi.sense_len;
1492 				io->scsiio.sense_residual =msg->scsi.sense_residual;
1493 				memcpy(&io->scsiio.sense_data,
1494 				    &msg->scsi.sense_data,
1495 				    msg->scsi.sense_len);
1496 				if (msg->hdr.status == CTL_SUCCESS)
1497 					io->io_hdr.flags |= CTL_FLAG_STATUS_SENT;
1498 			}
1499 			ctl_enqueue_isc(io);
1500 			break;
1501 		}
1502 
1503 		/* Preformed on Originating SC, SER_ONLY mode */
1504 		case CTL_MSG_R2R:
1505 			io = msg->hdr.original_sc;
1506 			if (io == NULL) {
1507 				printf("%s: original_sc == NULL!\n",
1508 				    __func__);
1509 				break;
1510 			}
1511 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1512 			io->io_hdr.msg_type = CTL_MSG_R2R;
1513 			io->io_hdr.serializing_sc = msg->hdr.serializing_sc;
1514 			ctl_enqueue_isc(io);
1515 			break;
1516 
1517 		/*
1518 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
1519 		 * mode.
1520 		 * Performed on the Originating (i.e. secondary) SC in XFER
1521 		 * mode
1522 		 */
1523 		case CTL_MSG_FINISH_IO:
1524 			if (softc->ha_mode == CTL_HA_MODE_XFER)
1525 				ctl_isc_handler_finish_xfer(softc, msg);
1526 			else
1527 				ctl_isc_handler_finish_ser_only(softc, msg);
1528 			break;
1529 
1530 		/* Preformed on Originating SC */
1531 		case CTL_MSG_BAD_JUJU:
1532 			io = msg->hdr.original_sc;
1533 			if (io == NULL) {
1534 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
1535 				       __func__);
1536 				break;
1537 			}
1538 			ctl_copy_sense_data(msg, io);
1539 			/*
1540 			 * IO should have already been cleaned up on other
1541 			 * SC so clear this flag so we won't send a message
1542 			 * back to finish the IO there.
1543 			 */
1544 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
1545 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
1546 
1547 			/* io = msg->hdr.serializing_sc; */
1548 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
1549 			ctl_enqueue_isc(io);
1550 			break;
1551 
1552 		/* Handle resets sent from the other side */
1553 		case CTL_MSG_MANAGE_TASKS: {
1554 			struct ctl_taskio *taskio;
1555 			taskio = (struct ctl_taskio *)ctl_alloc_io(
1556 			    softc->othersc_pool);
1557 			ctl_zero_io((union ctl_io *)taskio);
1558 			taskio->io_hdr.io_type = CTL_IO_TASK;
1559 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1560 			taskio->io_hdr.nexus = msg->hdr.nexus;
1561 			taskio->task_action = msg->task.task_action;
1562 			taskio->tag_num = msg->task.tag_num;
1563 			taskio->tag_type = msg->task.tag_type;
1564 #ifdef CTL_TIME_IO
1565 			taskio->io_hdr.start_time = time_uptime;
1566 			getbinuptime(&taskio->io_hdr.start_bt);
1567 #endif /* CTL_TIME_IO */
1568 			ctl_run_task((union ctl_io *)taskio);
1569 			break;
1570 		}
1571 		/* Persistent Reserve action which needs attention */
1572 		case CTL_MSG_PERS_ACTION:
1573 			presio = (struct ctl_prio *)ctl_alloc_io(
1574 			    softc->othersc_pool);
1575 			ctl_zero_io((union ctl_io *)presio);
1576 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
1577 			presio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
1578 			presio->io_hdr.nexus = msg->hdr.nexus;
1579 			presio->pr_msg = msg->pr;
1580 			ctl_enqueue_isc((union ctl_io *)presio);
1581 			break;
1582 		case CTL_MSG_UA:
1583 			ctl_isc_ua(softc, msg, param);
1584 			break;
1585 		case CTL_MSG_PORT_SYNC:
1586 			ctl_isc_port_sync(softc, msg, param);
1587 			break;
1588 		case CTL_MSG_LUN_SYNC:
1589 			ctl_isc_lun_sync(softc, msg, param);
1590 			break;
1591 		case CTL_MSG_IID_SYNC:
1592 			ctl_isc_iid_sync(softc, msg, param);
1593 			break;
1594 		case CTL_MSG_LOGIN:
1595 			ctl_isc_login(softc, msg, param);
1596 			break;
1597 		case CTL_MSG_MODE_SYNC:
1598 			ctl_isc_mode_sync(softc, msg, param);
1599 			break;
1600 		default:
1601 			printf("Received HA message of unknown type %d\n",
1602 			    msg->hdr.msg_type);
1603 			ctl_ha_msg_abort(CTL_HA_CHAN_CTL);
1604 			break;
1605 		}
1606 		if (msg != &msgbuf)
1607 			free(msg, M_CTL);
1608 	} else if (event == CTL_HA_EVT_LINK_CHANGE) {
1609 		printf("CTL: HA link status changed from %d to %d\n",
1610 		    softc->ha_link, param);
1611 		if (param == softc->ha_link)
1612 			return;
1613 		if (softc->ha_link == CTL_HA_LINK_ONLINE) {
1614 			softc->ha_link = param;
1615 			ctl_isc_ha_link_down(softc);
1616 		} else {
1617 			softc->ha_link = param;
1618 			if (softc->ha_link == CTL_HA_LINK_ONLINE)
1619 				ctl_isc_ha_link_up(softc);
1620 		}
1621 		return;
1622 	} else {
1623 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
1624 		return;
1625 	}
1626 }
1627 
1628 static void
1629 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
1630 {
1631 
1632 	memcpy(&dest->scsiio.sense_data, &src->scsi.sense_data,
1633 	    src->scsi.sense_len);
1634 	dest->scsiio.scsi_status = src->scsi.scsi_status;
1635 	dest->scsiio.sense_len = src->scsi.sense_len;
1636 	dest->io_hdr.status = src->hdr.status;
1637 }
1638 
1639 static void
1640 ctl_copy_sense_data_back(union ctl_io *src, union ctl_ha_msg *dest)
1641 {
1642 
1643 	memcpy(&dest->scsi.sense_data, &src->scsiio.sense_data,
1644 	    src->scsiio.sense_len);
1645 	dest->scsi.scsi_status = src->scsiio.scsi_status;
1646 	dest->scsi.sense_len = src->scsiio.sense_len;
1647 	dest->hdr.status = src->io_hdr.status;
1648 }
1649 
1650 void
1651 ctl_est_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1652 {
1653 	struct ctl_softc *softc = lun->ctl_softc;
1654 	ctl_ua_type *pu;
1655 
1656 	if (initidx < softc->init_min || initidx >= softc->init_max)
1657 		return;
1658 	mtx_assert(&lun->lun_lock, MA_OWNED);
1659 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1660 	if (pu == NULL)
1661 		return;
1662 	pu[initidx % CTL_MAX_INIT_PER_PORT] |= ua;
1663 }
1664 
1665 void
1666 ctl_est_ua_port(struct ctl_lun *lun, int port, uint32_t except, ctl_ua_type ua)
1667 {
1668 	int i;
1669 
1670 	mtx_assert(&lun->lun_lock, MA_OWNED);
1671 	if (lun->pending_ua[port] == NULL)
1672 		return;
1673 	for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1674 		if (port * CTL_MAX_INIT_PER_PORT + i == except)
1675 			continue;
1676 		lun->pending_ua[port][i] |= ua;
1677 	}
1678 }
1679 
1680 void
1681 ctl_est_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1682 {
1683 	struct ctl_softc *softc = lun->ctl_softc;
1684 	int i;
1685 
1686 	mtx_assert(&lun->lun_lock, MA_OWNED);
1687 	for (i = softc->port_min; i < softc->port_max; i++)
1688 		ctl_est_ua_port(lun, i, except, ua);
1689 }
1690 
1691 void
1692 ctl_clr_ua(struct ctl_lun *lun, uint32_t initidx, ctl_ua_type ua)
1693 {
1694 	struct ctl_softc *softc = lun->ctl_softc;
1695 	ctl_ua_type *pu;
1696 
1697 	if (initidx < softc->init_min || initidx >= softc->init_max)
1698 		return;
1699 	mtx_assert(&lun->lun_lock, MA_OWNED);
1700 	pu = lun->pending_ua[initidx / CTL_MAX_INIT_PER_PORT];
1701 	if (pu == NULL)
1702 		return;
1703 	pu[initidx % CTL_MAX_INIT_PER_PORT] &= ~ua;
1704 }
1705 
1706 void
1707 ctl_clr_ua_all(struct ctl_lun *lun, uint32_t except, ctl_ua_type ua)
1708 {
1709 	struct ctl_softc *softc = lun->ctl_softc;
1710 	int i, j;
1711 
1712 	mtx_assert(&lun->lun_lock, MA_OWNED);
1713 	for (i = softc->port_min; i < softc->port_max; i++) {
1714 		if (lun->pending_ua[i] == NULL)
1715 			continue;
1716 		for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
1717 			if (i * CTL_MAX_INIT_PER_PORT + j == except)
1718 				continue;
1719 			lun->pending_ua[i][j] &= ~ua;
1720 		}
1721 	}
1722 }
1723 
1724 void
1725 ctl_clr_ua_allluns(struct ctl_softc *ctl_softc, uint32_t initidx,
1726     ctl_ua_type ua_type)
1727 {
1728 	struct ctl_lun *lun;
1729 
1730 	mtx_assert(&ctl_softc->ctl_lock, MA_OWNED);
1731 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links) {
1732 		mtx_lock(&lun->lun_lock);
1733 		ctl_clr_ua(lun, initidx, ua_type);
1734 		mtx_unlock(&lun->lun_lock);
1735 	}
1736 }
1737 
1738 static int
1739 ctl_ha_role_sysctl(SYSCTL_HANDLER_ARGS)
1740 {
1741 	struct ctl_softc *softc = (struct ctl_softc *)arg1;
1742 	struct ctl_lun *lun;
1743 	struct ctl_lun_req ireq;
1744 	int error, value;
1745 
1746 	value = (softc->flags & CTL_FLAG_ACTIVE_SHELF) ? 0 : 1;
1747 	error = sysctl_handle_int(oidp, &value, 0, req);
1748 	if ((error != 0) || (req->newptr == NULL))
1749 		return (error);
1750 
1751 	mtx_lock(&softc->ctl_lock);
1752 	if (value == 0)
1753 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1754 	else
1755 		softc->flags &= ~CTL_FLAG_ACTIVE_SHELF;
1756 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
1757 		mtx_unlock(&softc->ctl_lock);
1758 		bzero(&ireq, sizeof(ireq));
1759 		ireq.reqtype = CTL_LUNREQ_MODIFY;
1760 		ireq.reqdata.modify.lun_id = lun->lun;
1761 		lun->backend->ioctl(NULL, CTL_LUN_REQ, (caddr_t)&ireq, 0,
1762 		    curthread);
1763 		if (ireq.status != CTL_LUN_OK) {
1764 			printf("%s: CTL_LUNREQ_MODIFY returned %d '%s'\n",
1765 			    __func__, ireq.status, ireq.error_str);
1766 		}
1767 		mtx_lock(&softc->ctl_lock);
1768 	}
1769 	mtx_unlock(&softc->ctl_lock);
1770 	return (0);
1771 }
1772 
1773 static int
1774 ctl_init(void)
1775 {
1776 	struct ctl_softc *softc;
1777 	void *other_pool;
1778 	int i, error;
1779 
1780 	softc = control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
1781 			       M_WAITOK | M_ZERO);
1782 
1783 	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
1784 			      "cam/ctl");
1785 	softc->dev->si_drv1 = softc;
1786 
1787 	sysctl_ctx_init(&softc->sysctl_ctx);
1788 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
1789 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
1790 		CTLFLAG_RD, 0, "CAM Target Layer");
1791 
1792 	if (softc->sysctl_tree == NULL) {
1793 		printf("%s: unable to allocate sysctl tree\n", __func__);
1794 		destroy_dev(softc->dev);
1795 		free(control_softc, M_DEVBUF);
1796 		control_softc = NULL;
1797 		return (ENOMEM);
1798 	}
1799 
1800 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
1801 	softc->io_zone = uma_zcreate("CTL IO", sizeof(union ctl_io),
1802 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
1803 	softc->flags = 0;
1804 
1805 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1806 	    OID_AUTO, "ha_mode", CTLFLAG_RDTUN, (int *)&softc->ha_mode, 0,
1807 	    "HA mode (0 - act/stby, 1 - serialize only, 2 - xfer)");
1808 
1809 	/*
1810 	 * In Copan's HA scheme, the "master" and "slave" roles are
1811 	 * figured out through the slot the controller is in.  Although it
1812 	 * is an active/active system, someone has to be in charge.
1813 	 */
1814 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1815 	    OID_AUTO, "ha_id", CTLFLAG_RDTUN, &softc->ha_id, 0,
1816 	    "HA head ID (0 - no HA)");
1817 	if (softc->ha_id == 0 || softc->ha_id > NUM_TARGET_PORT_GROUPS) {
1818 		softc->flags |= CTL_FLAG_ACTIVE_SHELF;
1819 		softc->is_single = 1;
1820 		softc->port_cnt = CTL_MAX_PORTS;
1821 		softc->port_min = 0;
1822 	} else {
1823 		softc->port_cnt = CTL_MAX_PORTS / NUM_TARGET_PORT_GROUPS;
1824 		softc->port_min = (softc->ha_id - 1) * softc->port_cnt;
1825 	}
1826 	softc->port_max = softc->port_min + softc->port_cnt;
1827 	softc->init_min = softc->port_min * CTL_MAX_INIT_PER_PORT;
1828 	softc->init_max = softc->port_max * CTL_MAX_INIT_PER_PORT;
1829 
1830 	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
1831 	    OID_AUTO, "ha_link", CTLFLAG_RD, (int *)&softc->ha_link, 0,
1832 	    "HA link state (0 - offline, 1 - unknown, 2 - online)");
1833 
1834 	STAILQ_INIT(&softc->lun_list);
1835 	STAILQ_INIT(&softc->pending_lun_queue);
1836 	STAILQ_INIT(&softc->fe_list);
1837 	STAILQ_INIT(&softc->port_list);
1838 	STAILQ_INIT(&softc->be_list);
1839 	ctl_tpc_init(softc);
1840 
1841 	if (ctl_pool_create(softc, "othersc", CTL_POOL_ENTRIES_OTHER_SC,
1842 	                    &other_pool) != 0)
1843 	{
1844 		printf("ctl: can't allocate %d entry other SC pool, "
1845 		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1846 		return (ENOMEM);
1847 	}
1848 	softc->othersc_pool = other_pool;
1849 
1850 	if (worker_threads <= 0)
1851 		worker_threads = max(1, mp_ncpus / 4);
1852 	if (worker_threads > CTL_MAX_THREADS)
1853 		worker_threads = CTL_MAX_THREADS;
1854 
1855 	for (i = 0; i < worker_threads; i++) {
1856 		struct ctl_thread *thr = &softc->threads[i];
1857 
1858 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1859 		thr->ctl_softc = softc;
1860 		STAILQ_INIT(&thr->incoming_queue);
1861 		STAILQ_INIT(&thr->rtr_queue);
1862 		STAILQ_INIT(&thr->done_queue);
1863 		STAILQ_INIT(&thr->isc_queue);
1864 
1865 		error = kproc_kthread_add(ctl_work_thread, thr,
1866 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1867 		if (error != 0) {
1868 			printf("error creating CTL work thread!\n");
1869 			ctl_pool_free(other_pool);
1870 			return (error);
1871 		}
1872 	}
1873 	error = kproc_kthread_add(ctl_lun_thread, softc,
1874 	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1875 	if (error != 0) {
1876 		printf("error creating CTL lun thread!\n");
1877 		ctl_pool_free(other_pool);
1878 		return (error);
1879 	}
1880 	error = kproc_kthread_add(ctl_thresh_thread, softc,
1881 	    &softc->ctl_proc, NULL, 0, 0, "ctl", "thresh");
1882 	if (error != 0) {
1883 		printf("error creating CTL threshold thread!\n");
1884 		ctl_pool_free(other_pool);
1885 		return (error);
1886 	}
1887 
1888 	SYSCTL_ADD_PROC(&softc->sysctl_ctx,SYSCTL_CHILDREN(softc->sysctl_tree),
1889 	    OID_AUTO, "ha_role", CTLTYPE_INT | CTLFLAG_RWTUN,
1890 	    softc, 0, ctl_ha_role_sysctl, "I", "HA role for this head");
1891 
1892 	if (softc->is_single == 0) {
1893 		ctl_frontend_register(&ha_frontend);
1894 		if (ctl_ha_msg_init(softc) != CTL_HA_STATUS_SUCCESS) {
1895 			printf("ctl_init: ctl_ha_msg_init failed.\n");
1896 			softc->is_single = 1;
1897 		} else
1898 		if (ctl_ha_msg_register(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
1899 		    != CTL_HA_STATUS_SUCCESS) {
1900 			printf("ctl_init: ctl_ha_msg_register failed.\n");
1901 			softc->is_single = 1;
1902 		}
1903 	}
1904 	return (0);
1905 }
1906 
1907 void
1908 ctl_shutdown(void)
1909 {
1910 	struct ctl_softc *softc = control_softc;
1911 	struct ctl_lun *lun, *next_lun;
1912 
1913 	if (softc->is_single == 0) {
1914 		ctl_ha_msg_shutdown(softc);
1915 		if (ctl_ha_msg_deregister(CTL_HA_CHAN_CTL)
1916 		    != CTL_HA_STATUS_SUCCESS)
1917 			printf("%s: ctl_ha_msg_deregister failed.\n", __func__);
1918 		if (ctl_ha_msg_destroy(softc) != CTL_HA_STATUS_SUCCESS)
1919 			printf("%s: ctl_ha_msg_destroy failed.\n", __func__);
1920 		ctl_frontend_deregister(&ha_frontend);
1921 	}
1922 
1923 	mtx_lock(&softc->ctl_lock);
1924 
1925 	STAILQ_FOREACH_SAFE(lun, &softc->lun_list, links, next_lun)
1926 		ctl_free_lun(lun);
1927 
1928 	mtx_unlock(&softc->ctl_lock);
1929 
1930 #if 0
1931 	ctl_shutdown_thread(softc->work_thread);
1932 	mtx_destroy(&softc->queue_lock);
1933 #endif
1934 
1935 	ctl_tpc_shutdown(softc);
1936 	uma_zdestroy(softc->io_zone);
1937 	mtx_destroy(&softc->ctl_lock);
1938 
1939 	destroy_dev(softc->dev);
1940 
1941 	sysctl_ctx_free(&softc->sysctl_ctx);
1942 
1943 	free(control_softc, M_DEVBUF);
1944 	control_softc = NULL;
1945 }
1946 
1947 static int
1948 ctl_module_event_handler(module_t mod, int what, void *arg)
1949 {
1950 
1951 	switch (what) {
1952 	case MOD_LOAD:
1953 		return (ctl_init());
1954 	case MOD_UNLOAD:
1955 		return (EBUSY);
1956 	default:
1957 		return (EOPNOTSUPP);
1958 	}
1959 }
1960 
1961 /*
1962  * XXX KDM should we do some access checks here?  Bump a reference count to
1963  * prevent a CTL module from being unloaded while someone has it open?
1964  */
1965 static int
1966 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1967 {
1968 	return (0);
1969 }
1970 
1971 static int
1972 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1973 {
1974 	return (0);
1975 }
1976 
1977 /*
1978  * Remove an initiator by port number and initiator ID.
1979  * Returns 0 for success, -1 for failure.
1980  */
1981 int
1982 ctl_remove_initiator(struct ctl_port *port, int iid)
1983 {
1984 	struct ctl_softc *softc = port->ctl_softc;
1985 
1986 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1987 
1988 	if (iid > CTL_MAX_INIT_PER_PORT) {
1989 		printf("%s: initiator ID %u > maximun %u!\n",
1990 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1991 		return (-1);
1992 	}
1993 
1994 	mtx_lock(&softc->ctl_lock);
1995 	port->wwpn_iid[iid].in_use--;
1996 	port->wwpn_iid[iid].last_use = time_uptime;
1997 	mtx_unlock(&softc->ctl_lock);
1998 	ctl_isc_announce_iid(port, iid);
1999 
2000 	return (0);
2001 }
2002 
2003 /*
2004  * Add an initiator to the initiator map.
2005  * Returns iid for success, < 0 for failure.
2006  */
2007 int
2008 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
2009 {
2010 	struct ctl_softc *softc = port->ctl_softc;
2011 	time_t best_time;
2012 	int i, best;
2013 
2014 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
2015 
2016 	if (iid >= CTL_MAX_INIT_PER_PORT) {
2017 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
2018 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
2019 		free(name, M_CTL);
2020 		return (-1);
2021 	}
2022 
2023 	mtx_lock(&softc->ctl_lock);
2024 
2025 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
2026 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2027 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
2028 				iid = i;
2029 				break;
2030 			}
2031 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
2032 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
2033 				iid = i;
2034 				break;
2035 			}
2036 		}
2037 	}
2038 
2039 	if (iid < 0) {
2040 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2041 			if (port->wwpn_iid[i].in_use == 0 &&
2042 			    port->wwpn_iid[i].wwpn == 0 &&
2043 			    port->wwpn_iid[i].name == NULL) {
2044 				iid = i;
2045 				break;
2046 			}
2047 		}
2048 	}
2049 
2050 	if (iid < 0) {
2051 		best = -1;
2052 		best_time = INT32_MAX;
2053 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
2054 			if (port->wwpn_iid[i].in_use == 0) {
2055 				if (port->wwpn_iid[i].last_use < best_time) {
2056 					best = i;
2057 					best_time = port->wwpn_iid[i].last_use;
2058 				}
2059 			}
2060 		}
2061 		iid = best;
2062 	}
2063 
2064 	if (iid < 0) {
2065 		mtx_unlock(&softc->ctl_lock);
2066 		free(name, M_CTL);
2067 		return (-2);
2068 	}
2069 
2070 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
2071 		/*
2072 		 * This is not an error yet.
2073 		 */
2074 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
2075 #if 0
2076 			printf("%s: port %d iid %u WWPN %#jx arrived"
2077 			    " again\n", __func__, port->targ_port,
2078 			    iid, (uintmax_t)wwpn);
2079 #endif
2080 			goto take;
2081 		}
2082 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
2083 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
2084 #if 0
2085 			printf("%s: port %d iid %u name '%s' arrived"
2086 			    " again\n", __func__, port->targ_port,
2087 			    iid, name);
2088 #endif
2089 			goto take;
2090 		}
2091 
2092 		/*
2093 		 * This is an error, but what do we do about it?  The
2094 		 * driver is telling us we have a new WWPN for this
2095 		 * initiator ID, so we pretty much need to use it.
2096 		 */
2097 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
2098 		    " but WWPN %#jx '%s' is still at that address\n",
2099 		    __func__, port->targ_port, iid, wwpn, name,
2100 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
2101 		    port->wwpn_iid[iid].name);
2102 
2103 		/*
2104 		 * XXX KDM clear have_ca and ua_pending on each LUN for
2105 		 * this initiator.
2106 		 */
2107 	}
2108 take:
2109 	free(port->wwpn_iid[iid].name, M_CTL);
2110 	port->wwpn_iid[iid].name = name;
2111 	port->wwpn_iid[iid].wwpn = wwpn;
2112 	port->wwpn_iid[iid].in_use++;
2113 	mtx_unlock(&softc->ctl_lock);
2114 	ctl_isc_announce_iid(port, iid);
2115 
2116 	return (iid);
2117 }
2118 
2119 static int
2120 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
2121 {
2122 	int len;
2123 
2124 	switch (port->port_type) {
2125 	case CTL_PORT_FC:
2126 	{
2127 		struct scsi_transportid_fcp *id =
2128 		    (struct scsi_transportid_fcp *)buf;
2129 		if (port->wwpn_iid[iid].wwpn == 0)
2130 			return (0);
2131 		memset(id, 0, sizeof(*id));
2132 		id->format_protocol = SCSI_PROTO_FC;
2133 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
2134 		return (sizeof(*id));
2135 	}
2136 	case CTL_PORT_ISCSI:
2137 	{
2138 		struct scsi_transportid_iscsi_port *id =
2139 		    (struct scsi_transportid_iscsi_port *)buf;
2140 		if (port->wwpn_iid[iid].name == NULL)
2141 			return (0);
2142 		memset(id, 0, 256);
2143 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
2144 		    SCSI_PROTO_ISCSI;
2145 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
2146 		len = roundup2(min(len, 252), 4);
2147 		scsi_ulto2b(len, id->additional_length);
2148 		return (sizeof(*id) + len);
2149 	}
2150 	case CTL_PORT_SAS:
2151 	{
2152 		struct scsi_transportid_sas *id =
2153 		    (struct scsi_transportid_sas *)buf;
2154 		if (port->wwpn_iid[iid].wwpn == 0)
2155 			return (0);
2156 		memset(id, 0, sizeof(*id));
2157 		id->format_protocol = SCSI_PROTO_SAS;
2158 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
2159 		return (sizeof(*id));
2160 	}
2161 	default:
2162 	{
2163 		struct scsi_transportid_spi *id =
2164 		    (struct scsi_transportid_spi *)buf;
2165 		memset(id, 0, sizeof(*id));
2166 		id->format_protocol = SCSI_PROTO_SPI;
2167 		scsi_ulto2b(iid, id->scsi_addr);
2168 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
2169 		return (sizeof(*id));
2170 	}
2171 	}
2172 }
2173 
2174 /*
2175  * Serialize a command that went down the "wrong" side, and so was sent to
2176  * this controller for execution.  The logic is a little different than the
2177  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
2178  * sent back to the other side, but in the success case, we execute the
2179  * command on this side (XFER mode) or tell the other side to execute it
2180  * (SER_ONLY mode).
2181  */
2182 static int
2183 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
2184 {
2185 	struct ctl_softc *softc = control_softc;
2186 	union ctl_ha_msg msg_info;
2187 	struct ctl_port *port;
2188 	struct ctl_lun *lun;
2189 	const struct ctl_cmd_entry *entry;
2190 	int retval = 0;
2191 	uint32_t targ_lun;
2192 
2193 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
2194 	mtx_lock(&softc->ctl_lock);
2195 
2196 	/* Make sure that we know about this port. */
2197 	port = ctl_io_port(&ctsio->io_hdr);
2198 	if (port == NULL || (port->status & CTL_PORT_STATUS_ONLINE) == 0) {
2199 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2200 					 /*retry_count*/ 1);
2201 		goto badjuju;
2202 	}
2203 
2204 	/* Make sure that we know about this LUN. */
2205 	if ((targ_lun < CTL_MAX_LUNS) &&
2206 	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
2207 		mtx_lock(&lun->lun_lock);
2208 		mtx_unlock(&softc->ctl_lock);
2209 		/*
2210 		 * If the LUN is invalid, pretend that it doesn't exist.
2211 		 * It will go away as soon as all pending I/O has been
2212 		 * completed.
2213 		 */
2214 		if (lun->flags & CTL_LUN_DISABLED) {
2215 			mtx_unlock(&lun->lun_lock);
2216 			lun = NULL;
2217 		}
2218 	} else {
2219 		mtx_unlock(&softc->ctl_lock);
2220 		lun = NULL;
2221 	}
2222 	if (lun == NULL) {
2223 		/*
2224 		 * The other node would not send this request to us unless
2225 		 * received announce that we are primary node for this LUN.
2226 		 * If this LUN does not exist now, it is probably result of
2227 		 * a race, so respond to initiator in the most opaque way.
2228 		 */
2229 		ctl_set_busy(ctsio);
2230 		goto badjuju;
2231 	}
2232 
2233 	entry = ctl_get_cmd_entry(ctsio, NULL);
2234 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
2235 		mtx_unlock(&lun->lun_lock);
2236 		goto badjuju;
2237 	}
2238 
2239 	ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
2240 	ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = lun->be_lun;
2241 
2242 	/*
2243 	 * Every I/O goes into the OOA queue for a
2244 	 * particular LUN, and stays there until completion.
2245 	 */
2246 #ifdef CTL_TIME_IO
2247 	if (TAILQ_EMPTY(&lun->ooa_queue))
2248 		lun->idle_time += getsbinuptime() - lun->last_busy;
2249 #endif
2250 	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2251 
2252 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
2253 		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
2254 		 ooa_links))) {
2255 	case CTL_ACTION_BLOCK:
2256 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
2257 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
2258 				  blocked_links);
2259 		mtx_unlock(&lun->lun_lock);
2260 		break;
2261 	case CTL_ACTION_PASS:
2262 	case CTL_ACTION_SKIP:
2263 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
2264 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
2265 			ctl_enqueue_rtr((union ctl_io *)ctsio);
2266 			mtx_unlock(&lun->lun_lock);
2267 		} else {
2268 			ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
2269 			mtx_unlock(&lun->lun_lock);
2270 
2271 			/* send msg back to other side */
2272 			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2273 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
2274 			msg_info.hdr.msg_type = CTL_MSG_R2R;
2275 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2276 			    sizeof(msg_info.hdr), M_WAITOK);
2277 		}
2278 		break;
2279 	case CTL_ACTION_OVERLAP:
2280 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2281 		mtx_unlock(&lun->lun_lock);
2282 		ctl_set_overlapped_cmd(ctsio);
2283 		goto badjuju;
2284 	case CTL_ACTION_OVERLAP_TAG:
2285 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2286 		mtx_unlock(&lun->lun_lock);
2287 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num);
2288 		goto badjuju;
2289 	case CTL_ACTION_ERROR:
2290 	default:
2291 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
2292 		mtx_unlock(&lun->lun_lock);
2293 
2294 		ctl_set_internal_failure(ctsio, /*sks_valid*/ 0,
2295 					 /*retry_count*/ 0);
2296 badjuju:
2297 		ctl_copy_sense_data_back((union ctl_io *)ctsio, &msg_info);
2298 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
2299 		msg_info.hdr.serializing_sc = NULL;
2300 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
2301 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
2302 		    sizeof(msg_info.scsi), M_WAITOK);
2303 		retval = 1;
2304 		break;
2305 	}
2306 	return (retval);
2307 }
2308 
2309 /*
2310  * Returns 0 for success, errno for failure.
2311  */
2312 static void
2313 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2314 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2315 {
2316 	union ctl_io *io;
2317 
2318 	mtx_lock(&lun->lun_lock);
2319 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2320 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2321 	     ooa_links)) {
2322 		struct ctl_ooa_entry *entry;
2323 
2324 		/*
2325 		 * If we've got more than we can fit, just count the
2326 		 * remaining entries.
2327 		 */
2328 		if (*cur_fill_num >= ooa_hdr->alloc_num)
2329 			continue;
2330 
2331 		entry = &kern_entries[*cur_fill_num];
2332 
2333 		entry->tag_num = io->scsiio.tag_num;
2334 		entry->lun_num = lun->lun;
2335 #ifdef CTL_TIME_IO
2336 		entry->start_bt = io->io_hdr.start_bt;
2337 #endif
2338 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2339 		entry->cdb_len = io->scsiio.cdb_len;
2340 		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2341 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2342 
2343 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2344 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2345 
2346 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2347 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2348 
2349 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2350 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2351 
2352 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2353 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2354 	}
2355 	mtx_unlock(&lun->lun_lock);
2356 }
2357 
2358 static void *
2359 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2360 		 size_t error_str_len)
2361 {
2362 	void *kptr;
2363 
2364 	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2365 
2366 	if (copyin(user_addr, kptr, len) != 0) {
2367 		snprintf(error_str, error_str_len, "Error copying %d bytes "
2368 			 "from user address %p to kernel address %p", len,
2369 			 user_addr, kptr);
2370 		free(kptr, M_CTL);
2371 		return (NULL);
2372 	}
2373 
2374 	return (kptr);
2375 }
2376 
2377 static void
2378 ctl_free_args(int num_args, struct ctl_be_arg *args)
2379 {
2380 	int i;
2381 
2382 	if (args == NULL)
2383 		return;
2384 
2385 	for (i = 0; i < num_args; i++) {
2386 		free(args[i].kname, M_CTL);
2387 		free(args[i].kvalue, M_CTL);
2388 	}
2389 
2390 	free(args, M_CTL);
2391 }
2392 
2393 static struct ctl_be_arg *
2394 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2395 		char *error_str, size_t error_str_len)
2396 {
2397 	struct ctl_be_arg *args;
2398 	int i;
2399 
2400 	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2401 				error_str, error_str_len);
2402 
2403 	if (args == NULL)
2404 		goto bailout;
2405 
2406 	for (i = 0; i < num_args; i++) {
2407 		args[i].kname = NULL;
2408 		args[i].kvalue = NULL;
2409 	}
2410 
2411 	for (i = 0; i < num_args; i++) {
2412 		uint8_t *tmpptr;
2413 
2414 		args[i].kname = ctl_copyin_alloc(args[i].name,
2415 			args[i].namelen, error_str, error_str_len);
2416 		if (args[i].kname == NULL)
2417 			goto bailout;
2418 
2419 		if (args[i].kname[args[i].namelen - 1] != '\0') {
2420 			snprintf(error_str, error_str_len, "Argument %d "
2421 				 "name is not NUL-terminated", i);
2422 			goto bailout;
2423 		}
2424 
2425 		if (args[i].flags & CTL_BEARG_RD) {
2426 			tmpptr = ctl_copyin_alloc(args[i].value,
2427 				args[i].vallen, error_str, error_str_len);
2428 			if (tmpptr == NULL)
2429 				goto bailout;
2430 			if ((args[i].flags & CTL_BEARG_ASCII)
2431 			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2432 				snprintf(error_str, error_str_len, "Argument "
2433 				    "%d value is not NUL-terminated", i);
2434 				goto bailout;
2435 			}
2436 			args[i].kvalue = tmpptr;
2437 		} else {
2438 			args[i].kvalue = malloc(args[i].vallen,
2439 			    M_CTL, M_WAITOK | M_ZERO);
2440 		}
2441 	}
2442 
2443 	return (args);
2444 bailout:
2445 
2446 	ctl_free_args(num_args, args);
2447 
2448 	return (NULL);
2449 }
2450 
2451 static void
2452 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2453 {
2454 	int i;
2455 
2456 	for (i = 0; i < num_args; i++) {
2457 		if (args[i].flags & CTL_BEARG_WR)
2458 			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2459 	}
2460 }
2461 
2462 /*
2463  * Escape characters that are illegal or not recommended in XML.
2464  */
2465 int
2466 ctl_sbuf_printf_esc(struct sbuf *sb, char *str, int size)
2467 {
2468 	char *end = str + size;
2469 	int retval;
2470 
2471 	retval = 0;
2472 
2473 	for (; *str && str < end; str++) {
2474 		switch (*str) {
2475 		case '&':
2476 			retval = sbuf_printf(sb, "&amp;");
2477 			break;
2478 		case '>':
2479 			retval = sbuf_printf(sb, "&gt;");
2480 			break;
2481 		case '<':
2482 			retval = sbuf_printf(sb, "&lt;");
2483 			break;
2484 		default:
2485 			retval = sbuf_putc(sb, *str);
2486 			break;
2487 		}
2488 
2489 		if (retval != 0)
2490 			break;
2491 
2492 	}
2493 
2494 	return (retval);
2495 }
2496 
2497 static void
2498 ctl_id_sbuf(struct ctl_devid *id, struct sbuf *sb)
2499 {
2500 	struct scsi_vpd_id_descriptor *desc;
2501 	int i;
2502 
2503 	if (id == NULL || id->len < 4)
2504 		return;
2505 	desc = (struct scsi_vpd_id_descriptor *)id->data;
2506 	switch (desc->id_type & SVPD_ID_TYPE_MASK) {
2507 	case SVPD_ID_TYPE_T10:
2508 		sbuf_printf(sb, "t10.");
2509 		break;
2510 	case SVPD_ID_TYPE_EUI64:
2511 		sbuf_printf(sb, "eui.");
2512 		break;
2513 	case SVPD_ID_TYPE_NAA:
2514 		sbuf_printf(sb, "naa.");
2515 		break;
2516 	case SVPD_ID_TYPE_SCSI_NAME:
2517 		break;
2518 	}
2519 	switch (desc->proto_codeset & SVPD_ID_CODESET_MASK) {
2520 	case SVPD_ID_CODESET_BINARY:
2521 		for (i = 0; i < desc->length; i++)
2522 			sbuf_printf(sb, "%02x", desc->identifier[i]);
2523 		break;
2524 	case SVPD_ID_CODESET_ASCII:
2525 		sbuf_printf(sb, "%.*s", (int)desc->length,
2526 		    (char *)desc->identifier);
2527 		break;
2528 	case SVPD_ID_CODESET_UTF8:
2529 		sbuf_printf(sb, "%s", (char *)desc->identifier);
2530 		break;
2531 	}
2532 }
2533 
2534 static int
2535 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2536 	  struct thread *td)
2537 {
2538 	struct ctl_softc *softc = dev->si_drv1;
2539 	struct ctl_lun *lun;
2540 	int retval;
2541 
2542 	retval = 0;
2543 
2544 	switch (cmd) {
2545 	case CTL_IO:
2546 		retval = ctl_ioctl_io(dev, cmd, addr, flag, td);
2547 		break;
2548 	case CTL_ENABLE_PORT:
2549 	case CTL_DISABLE_PORT:
2550 	case CTL_SET_PORT_WWNS: {
2551 		struct ctl_port *port;
2552 		struct ctl_port_entry *entry;
2553 
2554 		entry = (struct ctl_port_entry *)addr;
2555 
2556 		mtx_lock(&softc->ctl_lock);
2557 		STAILQ_FOREACH(port, &softc->port_list, links) {
2558 			int action, done;
2559 
2560 			if (port->targ_port < softc->port_min ||
2561 			    port->targ_port >= softc->port_max)
2562 				continue;
2563 
2564 			action = 0;
2565 			done = 0;
2566 			if ((entry->port_type == CTL_PORT_NONE)
2567 			 && (entry->targ_port == port->targ_port)) {
2568 				/*
2569 				 * If the user only wants to enable or
2570 				 * disable or set WWNs on a specific port,
2571 				 * do the operation and we're done.
2572 				 */
2573 				action = 1;
2574 				done = 1;
2575 			} else if (entry->port_type & port->port_type) {
2576 				/*
2577 				 * Compare the user's type mask with the
2578 				 * particular frontend type to see if we
2579 				 * have a match.
2580 				 */
2581 				action = 1;
2582 				done = 0;
2583 
2584 				/*
2585 				 * Make sure the user isn't trying to set
2586 				 * WWNs on multiple ports at the same time.
2587 				 */
2588 				if (cmd == CTL_SET_PORT_WWNS) {
2589 					printf("%s: Can't set WWNs on "
2590 					       "multiple ports\n", __func__);
2591 					retval = EINVAL;
2592 					break;
2593 				}
2594 			}
2595 			if (action == 0)
2596 				continue;
2597 
2598 			/*
2599 			 * XXX KDM we have to drop the lock here, because
2600 			 * the online/offline operations can potentially
2601 			 * block.  We need to reference count the frontends
2602 			 * so they can't go away,
2603 			 */
2604 			if (cmd == CTL_ENABLE_PORT) {
2605 				mtx_unlock(&softc->ctl_lock);
2606 				ctl_port_online(port);
2607 				mtx_lock(&softc->ctl_lock);
2608 			} else if (cmd == CTL_DISABLE_PORT) {
2609 				mtx_unlock(&softc->ctl_lock);
2610 				ctl_port_offline(port);
2611 				mtx_lock(&softc->ctl_lock);
2612 			} else if (cmd == CTL_SET_PORT_WWNS) {
2613 				ctl_port_set_wwns(port,
2614 				    (entry->flags & CTL_PORT_WWNN_VALID) ?
2615 				    1 : 0, entry->wwnn,
2616 				    (entry->flags & CTL_PORT_WWPN_VALID) ?
2617 				    1 : 0, entry->wwpn);
2618 			}
2619 			if (done != 0)
2620 				break;
2621 		}
2622 		mtx_unlock(&softc->ctl_lock);
2623 		break;
2624 	}
2625 	case CTL_GET_OOA: {
2626 		struct ctl_ooa *ooa_hdr;
2627 		struct ctl_ooa_entry *entries;
2628 		uint32_t cur_fill_num;
2629 
2630 		ooa_hdr = (struct ctl_ooa *)addr;
2631 
2632 		if ((ooa_hdr->alloc_len == 0)
2633 		 || (ooa_hdr->alloc_num == 0)) {
2634 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2635 			       "must be non-zero\n", __func__,
2636 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2637 			retval = EINVAL;
2638 			break;
2639 		}
2640 
2641 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2642 		    sizeof(struct ctl_ooa_entry))) {
2643 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2644 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2645 			       __func__, ooa_hdr->alloc_len,
2646 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2647 			retval = EINVAL;
2648 			break;
2649 		}
2650 
2651 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2652 		if (entries == NULL) {
2653 			printf("%s: could not allocate %d bytes for OOA "
2654 			       "dump\n", __func__, ooa_hdr->alloc_len);
2655 			retval = ENOMEM;
2656 			break;
2657 		}
2658 
2659 		mtx_lock(&softc->ctl_lock);
2660 		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2661 		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2662 		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2663 			mtx_unlock(&softc->ctl_lock);
2664 			free(entries, M_CTL);
2665 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2666 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2667 			retval = EINVAL;
2668 			break;
2669 		}
2670 
2671 		cur_fill_num = 0;
2672 
2673 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2674 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2675 				ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2676 				    ooa_hdr, entries);
2677 			}
2678 		} else {
2679 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2680 			ctl_ioctl_fill_ooa(lun, &cur_fill_num, ooa_hdr,
2681 			    entries);
2682 		}
2683 		mtx_unlock(&softc->ctl_lock);
2684 
2685 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2686 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2687 			sizeof(struct ctl_ooa_entry);
2688 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2689 		if (retval != 0) {
2690 			printf("%s: error copying out %d bytes for OOA dump\n",
2691 			       __func__, ooa_hdr->fill_len);
2692 		}
2693 
2694 		getbinuptime(&ooa_hdr->cur_bt);
2695 
2696 		if (cur_fill_num > ooa_hdr->alloc_num) {
2697 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2698 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2699 		} else {
2700 			ooa_hdr->dropped_num = 0;
2701 			ooa_hdr->status = CTL_OOA_OK;
2702 		}
2703 
2704 		free(entries, M_CTL);
2705 		break;
2706 	}
2707 	case CTL_DELAY_IO: {
2708 		struct ctl_io_delay_info *delay_info;
2709 
2710 		delay_info = (struct ctl_io_delay_info *)addr;
2711 
2712 #ifdef CTL_IO_DELAY
2713 		mtx_lock(&softc->ctl_lock);
2714 
2715 		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2716 		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2717 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2718 		} else {
2719 			lun = softc->ctl_luns[delay_info->lun_id];
2720 			mtx_lock(&lun->lun_lock);
2721 
2722 			delay_info->status = CTL_DELAY_STATUS_OK;
2723 
2724 			switch (delay_info->delay_type) {
2725 			case CTL_DELAY_TYPE_CONT:
2726 				break;
2727 			case CTL_DELAY_TYPE_ONESHOT:
2728 				break;
2729 			default:
2730 				delay_info->status =
2731 					CTL_DELAY_STATUS_INVALID_TYPE;
2732 				break;
2733 			}
2734 
2735 			switch (delay_info->delay_loc) {
2736 			case CTL_DELAY_LOC_DATAMOVE:
2737 				lun->delay_info.datamove_type =
2738 					delay_info->delay_type;
2739 				lun->delay_info.datamove_delay =
2740 					delay_info->delay_secs;
2741 				break;
2742 			case CTL_DELAY_LOC_DONE:
2743 				lun->delay_info.done_type =
2744 					delay_info->delay_type;
2745 				lun->delay_info.done_delay =
2746 					delay_info->delay_secs;
2747 				break;
2748 			default:
2749 				delay_info->status =
2750 					CTL_DELAY_STATUS_INVALID_LOC;
2751 				break;
2752 			}
2753 			mtx_unlock(&lun->lun_lock);
2754 		}
2755 
2756 		mtx_unlock(&softc->ctl_lock);
2757 #else
2758 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2759 #endif /* CTL_IO_DELAY */
2760 		break;
2761 	}
2762 	case CTL_GETSTATS: {
2763 		struct ctl_stats *stats;
2764 		int i;
2765 
2766 		stats = (struct ctl_stats *)addr;
2767 
2768 		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2769 		     stats->alloc_len) {
2770 			stats->status = CTL_SS_NEED_MORE_SPACE;
2771 			stats->num_luns = softc->num_luns;
2772 			break;
2773 		}
2774 		/*
2775 		 * XXX KDM no locking here.  If the LUN list changes,
2776 		 * things can blow up.
2777 		 */
2778 		i = 0;
2779 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2780 			retval = copyout(&lun->stats, &stats->lun_stats[i++],
2781 					 sizeof(lun->stats));
2782 			if (retval != 0)
2783 				break;
2784 		}
2785 		stats->num_luns = softc->num_luns;
2786 		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2787 				 softc->num_luns;
2788 		stats->status = CTL_SS_OK;
2789 #ifdef CTL_TIME_IO
2790 		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2791 #else
2792 		stats->flags = CTL_STATS_FLAG_NONE;
2793 #endif
2794 		getnanouptime(&stats->timestamp);
2795 		break;
2796 	}
2797 	case CTL_ERROR_INJECT: {
2798 		struct ctl_error_desc *err_desc, *new_err_desc;
2799 
2800 		err_desc = (struct ctl_error_desc *)addr;
2801 
2802 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2803 				      M_WAITOK | M_ZERO);
2804 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2805 
2806 		mtx_lock(&softc->ctl_lock);
2807 		lun = softc->ctl_luns[err_desc->lun_id];
2808 		if (lun == NULL) {
2809 			mtx_unlock(&softc->ctl_lock);
2810 			free(new_err_desc, M_CTL);
2811 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2812 			       __func__, (uintmax_t)err_desc->lun_id);
2813 			retval = EINVAL;
2814 			break;
2815 		}
2816 		mtx_lock(&lun->lun_lock);
2817 		mtx_unlock(&softc->ctl_lock);
2818 
2819 		/*
2820 		 * We could do some checking here to verify the validity
2821 		 * of the request, but given the complexity of error
2822 		 * injection requests, the checking logic would be fairly
2823 		 * complex.
2824 		 *
2825 		 * For now, if the request is invalid, it just won't get
2826 		 * executed and might get deleted.
2827 		 */
2828 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2829 
2830 		/*
2831 		 * XXX KDM check to make sure the serial number is unique,
2832 		 * in case we somehow manage to wrap.  That shouldn't
2833 		 * happen for a very long time, but it's the right thing to
2834 		 * do.
2835 		 */
2836 		new_err_desc->serial = lun->error_serial;
2837 		err_desc->serial = lun->error_serial;
2838 		lun->error_serial++;
2839 
2840 		mtx_unlock(&lun->lun_lock);
2841 		break;
2842 	}
2843 	case CTL_ERROR_INJECT_DELETE: {
2844 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2845 		int delete_done;
2846 
2847 		delete_desc = (struct ctl_error_desc *)addr;
2848 		delete_done = 0;
2849 
2850 		mtx_lock(&softc->ctl_lock);
2851 		lun = softc->ctl_luns[delete_desc->lun_id];
2852 		if (lun == NULL) {
2853 			mtx_unlock(&softc->ctl_lock);
2854 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2855 			       __func__, (uintmax_t)delete_desc->lun_id);
2856 			retval = EINVAL;
2857 			break;
2858 		}
2859 		mtx_lock(&lun->lun_lock);
2860 		mtx_unlock(&softc->ctl_lock);
2861 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2862 			if (desc->serial != delete_desc->serial)
2863 				continue;
2864 
2865 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2866 				      links);
2867 			free(desc, M_CTL);
2868 			delete_done = 1;
2869 		}
2870 		mtx_unlock(&lun->lun_lock);
2871 		if (delete_done == 0) {
2872 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2873 			       "error serial %ju on LUN %u\n", __func__,
2874 			       delete_desc->serial, delete_desc->lun_id);
2875 			retval = EINVAL;
2876 			break;
2877 		}
2878 		break;
2879 	}
2880 	case CTL_DUMP_STRUCTS: {
2881 		int i, j, k;
2882 		struct ctl_port *port;
2883 		struct ctl_frontend *fe;
2884 
2885 		mtx_lock(&softc->ctl_lock);
2886 		printf("CTL Persistent Reservation information start:\n");
2887 		for (i = 0; i < CTL_MAX_LUNS; i++) {
2888 			lun = softc->ctl_luns[i];
2889 
2890 			if ((lun == NULL)
2891 			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2892 				continue;
2893 
2894 			for (j = 0; j < CTL_MAX_PORTS; j++) {
2895 				if (lun->pr_keys[j] == NULL)
2896 					continue;
2897 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2898 					if (lun->pr_keys[j][k] == 0)
2899 						continue;
2900 					printf("  LUN %d port %d iid %d key "
2901 					       "%#jx\n", i, j, k,
2902 					       (uintmax_t)lun->pr_keys[j][k]);
2903 				}
2904 			}
2905 		}
2906 		printf("CTL Persistent Reservation information end\n");
2907 		printf("CTL Ports:\n");
2908 		STAILQ_FOREACH(port, &softc->port_list, links) {
2909 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
2910 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
2911 			       port->frontend->name, port->port_type,
2912 			       port->physical_port, port->virtual_port,
2913 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
2914 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
2915 				if (port->wwpn_iid[j].in_use == 0 &&
2916 				    port->wwpn_iid[j].wwpn == 0 &&
2917 				    port->wwpn_iid[j].name == NULL)
2918 					continue;
2919 
2920 				printf("    iid %u use %d WWPN %#jx '%s'\n",
2921 				    j, port->wwpn_iid[j].in_use,
2922 				    (uintmax_t)port->wwpn_iid[j].wwpn,
2923 				    port->wwpn_iid[j].name);
2924 			}
2925 		}
2926 		printf("CTL Port information end\n");
2927 		mtx_unlock(&softc->ctl_lock);
2928 		/*
2929 		 * XXX KDM calling this without a lock.  We'd likely want
2930 		 * to drop the lock before calling the frontend's dump
2931 		 * routine anyway.
2932 		 */
2933 		printf("CTL Frontends:\n");
2934 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
2935 			printf("  Frontend '%s'\n", fe->name);
2936 			if (fe->fe_dump != NULL)
2937 				fe->fe_dump();
2938 		}
2939 		printf("CTL Frontend information end\n");
2940 		break;
2941 	}
2942 	case CTL_LUN_REQ: {
2943 		struct ctl_lun_req *lun_req;
2944 		struct ctl_backend_driver *backend;
2945 
2946 		lun_req = (struct ctl_lun_req *)addr;
2947 
2948 		backend = ctl_backend_find(lun_req->backend);
2949 		if (backend == NULL) {
2950 			lun_req->status = CTL_LUN_ERROR;
2951 			snprintf(lun_req->error_str,
2952 				 sizeof(lun_req->error_str),
2953 				 "Backend \"%s\" not found.",
2954 				 lun_req->backend);
2955 			break;
2956 		}
2957 		if (lun_req->num_be_args > 0) {
2958 			lun_req->kern_be_args = ctl_copyin_args(
2959 				lun_req->num_be_args,
2960 				lun_req->be_args,
2961 				lun_req->error_str,
2962 				sizeof(lun_req->error_str));
2963 			if (lun_req->kern_be_args == NULL) {
2964 				lun_req->status = CTL_LUN_ERROR;
2965 				break;
2966 			}
2967 		}
2968 
2969 		retval = backend->ioctl(dev, cmd, addr, flag, td);
2970 
2971 		if (lun_req->num_be_args > 0) {
2972 			ctl_copyout_args(lun_req->num_be_args,
2973 				      lun_req->kern_be_args);
2974 			ctl_free_args(lun_req->num_be_args,
2975 				      lun_req->kern_be_args);
2976 		}
2977 		break;
2978 	}
2979 	case CTL_LUN_LIST: {
2980 		struct sbuf *sb;
2981 		struct ctl_lun_list *list;
2982 		struct ctl_option *opt;
2983 
2984 		list = (struct ctl_lun_list *)addr;
2985 
2986 		/*
2987 		 * Allocate a fixed length sbuf here, based on the length
2988 		 * of the user's buffer.  We could allocate an auto-extending
2989 		 * buffer, and then tell the user how much larger our
2990 		 * amount of data is than his buffer, but that presents
2991 		 * some problems:
2992 		 *
2993 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
2994 		 *     we can't hold a lock while calling them with an
2995 		 *     auto-extending buffer.
2996  		 *
2997 		 * 2.  There is not currently a LUN reference counting
2998 		 *     mechanism, outside of outstanding transactions on
2999 		 *     the LUN's OOA queue.  So a LUN could go away on us
3000 		 *     while we're getting the LUN number, backend-specific
3001 		 *     information, etc.  Thus, given the way things
3002 		 *     currently work, we need to hold the CTL lock while
3003 		 *     grabbing LUN information.
3004 		 *
3005 		 * So, from the user's standpoint, the best thing to do is
3006 		 * allocate what he thinks is a reasonable buffer length,
3007 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3008 		 * double the buffer length and try again.  (And repeat
3009 		 * that until he succeeds.)
3010 		 */
3011 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3012 		if (sb == NULL) {
3013 			list->status = CTL_LUN_LIST_ERROR;
3014 			snprintf(list->error_str, sizeof(list->error_str),
3015 				 "Unable to allocate %d bytes for LUN list",
3016 				 list->alloc_len);
3017 			break;
3018 		}
3019 
3020 		sbuf_printf(sb, "<ctllunlist>\n");
3021 
3022 		mtx_lock(&softc->ctl_lock);
3023 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3024 			mtx_lock(&lun->lun_lock);
3025 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3026 					     (uintmax_t)lun->lun);
3027 
3028 			/*
3029 			 * Bail out as soon as we see that we've overfilled
3030 			 * the buffer.
3031 			 */
3032 			if (retval != 0)
3033 				break;
3034 
3035 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3036 					     "</backend_type>\n",
3037 					     (lun->backend == NULL) ?  "none" :
3038 					     lun->backend->name);
3039 
3040 			if (retval != 0)
3041 				break;
3042 
3043 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3044 					     lun->be_lun->lun_type);
3045 
3046 			if (retval != 0)
3047 				break;
3048 
3049 			if (lun->backend == NULL) {
3050 				retval = sbuf_printf(sb, "</lun>\n");
3051 				if (retval != 0)
3052 					break;
3053 				continue;
3054 			}
3055 
3056 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3057 					     (lun->be_lun->maxlba > 0) ?
3058 					     lun->be_lun->maxlba + 1 : 0);
3059 
3060 			if (retval != 0)
3061 				break;
3062 
3063 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3064 					     lun->be_lun->blocksize);
3065 
3066 			if (retval != 0)
3067 				break;
3068 
3069 			retval = sbuf_printf(sb, "\t<serial_number>");
3070 
3071 			if (retval != 0)
3072 				break;
3073 
3074 			retval = ctl_sbuf_printf_esc(sb,
3075 			    lun->be_lun->serial_num,
3076 			    sizeof(lun->be_lun->serial_num));
3077 
3078 			if (retval != 0)
3079 				break;
3080 
3081 			retval = sbuf_printf(sb, "</serial_number>\n");
3082 
3083 			if (retval != 0)
3084 				break;
3085 
3086 			retval = sbuf_printf(sb, "\t<device_id>");
3087 
3088 			if (retval != 0)
3089 				break;
3090 
3091 			retval = ctl_sbuf_printf_esc(sb,
3092 			    lun->be_lun->device_id,
3093 			    sizeof(lun->be_lun->device_id));
3094 
3095 			if (retval != 0)
3096 				break;
3097 
3098 			retval = sbuf_printf(sb, "</device_id>\n");
3099 
3100 			if (retval != 0)
3101 				break;
3102 
3103 			if (lun->backend->lun_info != NULL) {
3104 				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3105 				if (retval != 0)
3106 					break;
3107 			}
3108 			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3109 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3110 				    opt->name, opt->value, opt->name);
3111 				if (retval != 0)
3112 					break;
3113 			}
3114 
3115 			retval = sbuf_printf(sb, "</lun>\n");
3116 
3117 			if (retval != 0)
3118 				break;
3119 			mtx_unlock(&lun->lun_lock);
3120 		}
3121 		if (lun != NULL)
3122 			mtx_unlock(&lun->lun_lock);
3123 		mtx_unlock(&softc->ctl_lock);
3124 
3125 		if ((retval != 0)
3126 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3127 			retval = 0;
3128 			sbuf_delete(sb);
3129 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3130 			snprintf(list->error_str, sizeof(list->error_str),
3131 				 "Out of space, %d bytes is too small",
3132 				 list->alloc_len);
3133 			break;
3134 		}
3135 
3136 		sbuf_finish(sb);
3137 
3138 		retval = copyout(sbuf_data(sb), list->lun_xml,
3139 				 sbuf_len(sb) + 1);
3140 
3141 		list->fill_len = sbuf_len(sb) + 1;
3142 		list->status = CTL_LUN_LIST_OK;
3143 		sbuf_delete(sb);
3144 		break;
3145 	}
3146 	case CTL_ISCSI: {
3147 		struct ctl_iscsi *ci;
3148 		struct ctl_frontend *fe;
3149 
3150 		ci = (struct ctl_iscsi *)addr;
3151 
3152 		fe = ctl_frontend_find("iscsi");
3153 		if (fe == NULL) {
3154 			ci->status = CTL_ISCSI_ERROR;
3155 			snprintf(ci->error_str, sizeof(ci->error_str),
3156 			    "Frontend \"iscsi\" not found.");
3157 			break;
3158 		}
3159 
3160 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3161 		break;
3162 	}
3163 	case CTL_PORT_REQ: {
3164 		struct ctl_req *req;
3165 		struct ctl_frontend *fe;
3166 
3167 		req = (struct ctl_req *)addr;
3168 
3169 		fe = ctl_frontend_find(req->driver);
3170 		if (fe == NULL) {
3171 			req->status = CTL_LUN_ERROR;
3172 			snprintf(req->error_str, sizeof(req->error_str),
3173 			    "Frontend \"%s\" not found.", req->driver);
3174 			break;
3175 		}
3176 		if (req->num_args > 0) {
3177 			req->kern_args = ctl_copyin_args(req->num_args,
3178 			    req->args, req->error_str, sizeof(req->error_str));
3179 			if (req->kern_args == NULL) {
3180 				req->status = CTL_LUN_ERROR;
3181 				break;
3182 			}
3183 		}
3184 
3185 		if (fe->ioctl)
3186 			retval = fe->ioctl(dev, cmd, addr, flag, td);
3187 		else
3188 			retval = ENODEV;
3189 
3190 		if (req->num_args > 0) {
3191 			ctl_copyout_args(req->num_args, req->kern_args);
3192 			ctl_free_args(req->num_args, req->kern_args);
3193 		}
3194 		break;
3195 	}
3196 	case CTL_PORT_LIST: {
3197 		struct sbuf *sb;
3198 		struct ctl_port *port;
3199 		struct ctl_lun_list *list;
3200 		struct ctl_option *opt;
3201 		int j;
3202 		uint32_t plun;
3203 
3204 		list = (struct ctl_lun_list *)addr;
3205 
3206 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3207 		if (sb == NULL) {
3208 			list->status = CTL_LUN_LIST_ERROR;
3209 			snprintf(list->error_str, sizeof(list->error_str),
3210 				 "Unable to allocate %d bytes for LUN list",
3211 				 list->alloc_len);
3212 			break;
3213 		}
3214 
3215 		sbuf_printf(sb, "<ctlportlist>\n");
3216 
3217 		mtx_lock(&softc->ctl_lock);
3218 		STAILQ_FOREACH(port, &softc->port_list, links) {
3219 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3220 					     (uintmax_t)port->targ_port);
3221 
3222 			/*
3223 			 * Bail out as soon as we see that we've overfilled
3224 			 * the buffer.
3225 			 */
3226 			if (retval != 0)
3227 				break;
3228 
3229 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3230 			    "</frontend_type>\n", port->frontend->name);
3231 			if (retval != 0)
3232 				break;
3233 
3234 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3235 					     port->port_type);
3236 			if (retval != 0)
3237 				break;
3238 
3239 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3240 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3241 			if (retval != 0)
3242 				break;
3243 
3244 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3245 			    port->port_name);
3246 			if (retval != 0)
3247 				break;
3248 
3249 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3250 			    port->physical_port);
3251 			if (retval != 0)
3252 				break;
3253 
3254 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3255 			    port->virtual_port);
3256 			if (retval != 0)
3257 				break;
3258 
3259 			if (port->target_devid != NULL) {
3260 				sbuf_printf(sb, "\t<target>");
3261 				ctl_id_sbuf(port->target_devid, sb);
3262 				sbuf_printf(sb, "</target>\n");
3263 			}
3264 
3265 			if (port->port_devid != NULL) {
3266 				sbuf_printf(sb, "\t<port>");
3267 				ctl_id_sbuf(port->port_devid, sb);
3268 				sbuf_printf(sb, "</port>\n");
3269 			}
3270 
3271 			if (port->port_info != NULL) {
3272 				retval = port->port_info(port->onoff_arg, sb);
3273 				if (retval != 0)
3274 					break;
3275 			}
3276 			STAILQ_FOREACH(opt, &port->options, links) {
3277 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3278 				    opt->name, opt->value, opt->name);
3279 				if (retval != 0)
3280 					break;
3281 			}
3282 
3283 			if (port->lun_map != NULL) {
3284 				sbuf_printf(sb, "\t<lun_map>on</lun_map>\n");
3285 				for (j = 0; j < CTL_MAX_LUNS; j++) {
3286 					plun = ctl_lun_map_from_port(port, j);
3287 					if (plun >= CTL_MAX_LUNS)
3288 						continue;
3289 					sbuf_printf(sb,
3290 					    "\t<lun id=\"%u\">%u</lun>\n",
3291 					    j, plun);
3292 				}
3293 			}
3294 
3295 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3296 				if (port->wwpn_iid[j].in_use == 0 ||
3297 				    (port->wwpn_iid[j].wwpn == 0 &&
3298 				     port->wwpn_iid[j].name == NULL))
3299 					continue;
3300 
3301 				if (port->wwpn_iid[j].name != NULL)
3302 					retval = sbuf_printf(sb,
3303 					    "\t<initiator id=\"%u\">%s</initiator>\n",
3304 					    j, port->wwpn_iid[j].name);
3305 				else
3306 					retval = sbuf_printf(sb,
3307 					    "\t<initiator id=\"%u\">naa.%08jx</initiator>\n",
3308 					    j, port->wwpn_iid[j].wwpn);
3309 				if (retval != 0)
3310 					break;
3311 			}
3312 			if (retval != 0)
3313 				break;
3314 
3315 			retval = sbuf_printf(sb, "</targ_port>\n");
3316 			if (retval != 0)
3317 				break;
3318 		}
3319 		mtx_unlock(&softc->ctl_lock);
3320 
3321 		if ((retval != 0)
3322 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3323 			retval = 0;
3324 			sbuf_delete(sb);
3325 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3326 			snprintf(list->error_str, sizeof(list->error_str),
3327 				 "Out of space, %d bytes is too small",
3328 				 list->alloc_len);
3329 			break;
3330 		}
3331 
3332 		sbuf_finish(sb);
3333 
3334 		retval = copyout(sbuf_data(sb), list->lun_xml,
3335 				 sbuf_len(sb) + 1);
3336 
3337 		list->fill_len = sbuf_len(sb) + 1;
3338 		list->status = CTL_LUN_LIST_OK;
3339 		sbuf_delete(sb);
3340 		break;
3341 	}
3342 	case CTL_LUN_MAP: {
3343 		struct ctl_lun_map *lm  = (struct ctl_lun_map *)addr;
3344 		struct ctl_port *port;
3345 
3346 		mtx_lock(&softc->ctl_lock);
3347 		if (lm->port < softc->port_min ||
3348 		    lm->port >= softc->port_max ||
3349 		    (port = softc->ctl_ports[lm->port]) == NULL) {
3350 			mtx_unlock(&softc->ctl_lock);
3351 			return (ENXIO);
3352 		}
3353 		if (port->status & CTL_PORT_STATUS_ONLINE) {
3354 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
3355 				if (ctl_lun_map_to_port(port, lun->lun) >=
3356 				    CTL_MAX_LUNS)
3357 					continue;
3358 				mtx_lock(&lun->lun_lock);
3359 				ctl_est_ua_port(lun, lm->port, -1,
3360 				    CTL_UA_LUN_CHANGE);
3361 				mtx_unlock(&lun->lun_lock);
3362 			}
3363 		}
3364 		mtx_unlock(&softc->ctl_lock); // XXX: port_enable sleeps
3365 		if (lm->plun < CTL_MAX_LUNS) {
3366 			if (lm->lun == UINT32_MAX)
3367 				retval = ctl_lun_map_unset(port, lm->plun);
3368 			else if (lm->lun < CTL_MAX_LUNS &&
3369 			    softc->ctl_luns[lm->lun] != NULL)
3370 				retval = ctl_lun_map_set(port, lm->plun, lm->lun);
3371 			else
3372 				return (ENXIO);
3373 		} else if (lm->plun == UINT32_MAX) {
3374 			if (lm->lun == UINT32_MAX)
3375 				retval = ctl_lun_map_deinit(port);
3376 			else
3377 				retval = ctl_lun_map_init(port);
3378 		} else
3379 			return (ENXIO);
3380 		if (port->status & CTL_PORT_STATUS_ONLINE)
3381 			ctl_isc_announce_port(port);
3382 		break;
3383 	}
3384 	default: {
3385 		/* XXX KDM should we fix this? */
3386 #if 0
3387 		struct ctl_backend_driver *backend;
3388 		unsigned int type;
3389 		int found;
3390 
3391 		found = 0;
3392 
3393 		/*
3394 		 * We encode the backend type as the ioctl type for backend
3395 		 * ioctls.  So parse it out here, and then search for a
3396 		 * backend of this type.
3397 		 */
3398 		type = _IOC_TYPE(cmd);
3399 
3400 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3401 			if (backend->type == type) {
3402 				found = 1;
3403 				break;
3404 			}
3405 		}
3406 		if (found == 0) {
3407 			printf("ctl: unknown ioctl command %#lx or backend "
3408 			       "%d\n", cmd, type);
3409 			retval = EINVAL;
3410 			break;
3411 		}
3412 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3413 #endif
3414 		retval = ENOTTY;
3415 		break;
3416 	}
3417 	}
3418 	return (retval);
3419 }
3420 
3421 uint32_t
3422 ctl_get_initindex(struct ctl_nexus *nexus)
3423 {
3424 	return (nexus->initid + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3425 }
3426 
3427 int
3428 ctl_lun_map_init(struct ctl_port *port)
3429 {
3430 	struct ctl_softc *softc = port->ctl_softc;
3431 	struct ctl_lun *lun;
3432 	uint32_t i;
3433 
3434 	if (port->lun_map == NULL)
3435 		port->lun_map = malloc(sizeof(uint32_t) * CTL_MAX_LUNS,
3436 		    M_CTL, M_NOWAIT);
3437 	if (port->lun_map == NULL)
3438 		return (ENOMEM);
3439 	for (i = 0; i < CTL_MAX_LUNS; i++)
3440 		port->lun_map[i] = UINT32_MAX;
3441 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3442 		if (port->lun_disable != NULL) {
3443 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3444 				port->lun_disable(port->targ_lun_arg, lun->lun);
3445 		}
3446 		ctl_isc_announce_port(port);
3447 	}
3448 	return (0);
3449 }
3450 
3451 int
3452 ctl_lun_map_deinit(struct ctl_port *port)
3453 {
3454 	struct ctl_softc *softc = port->ctl_softc;
3455 	struct ctl_lun *lun;
3456 
3457 	if (port->lun_map == NULL)
3458 		return (0);
3459 	free(port->lun_map, M_CTL);
3460 	port->lun_map = NULL;
3461 	if (port->status & CTL_PORT_STATUS_ONLINE) {
3462 		if (port->lun_enable != NULL) {
3463 			STAILQ_FOREACH(lun, &softc->lun_list, links)
3464 				port->lun_enable(port->targ_lun_arg, lun->lun);
3465 		}
3466 		ctl_isc_announce_port(port);
3467 	}
3468 	return (0);
3469 }
3470 
3471 int
3472 ctl_lun_map_set(struct ctl_port *port, uint32_t plun, uint32_t glun)
3473 {
3474 	int status;
3475 	uint32_t old;
3476 
3477 	if (port->lun_map == NULL) {
3478 		status = ctl_lun_map_init(port);
3479 		if (status != 0)
3480 			return (status);
3481 	}
3482 	old = port->lun_map[plun];
3483 	port->lun_map[plun] = glun;
3484 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old >= CTL_MAX_LUNS) {
3485 		if (port->lun_enable != NULL)
3486 			port->lun_enable(port->targ_lun_arg, plun);
3487 		ctl_isc_announce_port(port);
3488 	}
3489 	return (0);
3490 }
3491 
3492 int
3493 ctl_lun_map_unset(struct ctl_port *port, uint32_t plun)
3494 {
3495 	uint32_t old;
3496 
3497 	if (port->lun_map == NULL)
3498 		return (0);
3499 	old = port->lun_map[plun];
3500 	port->lun_map[plun] = UINT32_MAX;
3501 	if ((port->status & CTL_PORT_STATUS_ONLINE) && old < CTL_MAX_LUNS) {
3502 		if (port->lun_disable != NULL)
3503 			port->lun_disable(port->targ_lun_arg, plun);
3504 		ctl_isc_announce_port(port);
3505 	}
3506 	return (0);
3507 }
3508 
3509 uint32_t
3510 ctl_lun_map_from_port(struct ctl_port *port, uint32_t lun_id)
3511 {
3512 
3513 	if (port == NULL)
3514 		return (UINT32_MAX);
3515 	if (port->lun_map == NULL || lun_id >= CTL_MAX_LUNS)
3516 		return (lun_id);
3517 	return (port->lun_map[lun_id]);
3518 }
3519 
3520 uint32_t
3521 ctl_lun_map_to_port(struct ctl_port *port, uint32_t lun_id)
3522 {
3523 	uint32_t i;
3524 
3525 	if (port == NULL)
3526 		return (UINT32_MAX);
3527 	if (port->lun_map == NULL)
3528 		return (lun_id);
3529 	for (i = 0; i < CTL_MAX_LUNS; i++) {
3530 		if (port->lun_map[i] == lun_id)
3531 			return (i);
3532 	}
3533 	return (UINT32_MAX);
3534 }
3535 
3536 static struct ctl_port *
3537 ctl_io_port(struct ctl_io_hdr *io_hdr)
3538 {
3539 
3540 	return (control_softc->ctl_ports[io_hdr->nexus.targ_port]);
3541 }
3542 
3543 int
3544 ctl_ffz(uint32_t *mask, uint32_t first, uint32_t last)
3545 {
3546 	int i;
3547 
3548 	for (i = first; i < last; i++) {
3549 		if ((mask[i / 32] & (1 << (i % 32))) == 0)
3550 			return (i);
3551 	}
3552 	return (-1);
3553 }
3554 
3555 int
3556 ctl_set_mask(uint32_t *mask, uint32_t bit)
3557 {
3558 	uint32_t chunk, piece;
3559 
3560 	chunk = bit >> 5;
3561 	piece = bit % (sizeof(uint32_t) * 8);
3562 
3563 	if ((mask[chunk] & (1 << piece)) != 0)
3564 		return (-1);
3565 	else
3566 		mask[chunk] |= (1 << piece);
3567 
3568 	return (0);
3569 }
3570 
3571 int
3572 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3573 {
3574 	uint32_t chunk, piece;
3575 
3576 	chunk = bit >> 5;
3577 	piece = bit % (sizeof(uint32_t) * 8);
3578 
3579 	if ((mask[chunk] & (1 << piece)) == 0)
3580 		return (-1);
3581 	else
3582 		mask[chunk] &= ~(1 << piece);
3583 
3584 	return (0);
3585 }
3586 
3587 int
3588 ctl_is_set(uint32_t *mask, uint32_t bit)
3589 {
3590 	uint32_t chunk, piece;
3591 
3592 	chunk = bit >> 5;
3593 	piece = bit % (sizeof(uint32_t) * 8);
3594 
3595 	if ((mask[chunk] & (1 << piece)) == 0)
3596 		return (0);
3597 	else
3598 		return (1);
3599 }
3600 
3601 static uint64_t
3602 ctl_get_prkey(struct ctl_lun *lun, uint32_t residx)
3603 {
3604 	uint64_t *t;
3605 
3606 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3607 	if (t == NULL)
3608 		return (0);
3609 	return (t[residx % CTL_MAX_INIT_PER_PORT]);
3610 }
3611 
3612 static void
3613 ctl_clr_prkey(struct ctl_lun *lun, uint32_t residx)
3614 {
3615 	uint64_t *t;
3616 
3617 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3618 	if (t == NULL)
3619 		return;
3620 	t[residx % CTL_MAX_INIT_PER_PORT] = 0;
3621 }
3622 
3623 static void
3624 ctl_alloc_prkey(struct ctl_lun *lun, uint32_t residx)
3625 {
3626 	uint64_t *p;
3627 	u_int i;
3628 
3629 	i = residx/CTL_MAX_INIT_PER_PORT;
3630 	if (lun->pr_keys[i] != NULL)
3631 		return;
3632 	mtx_unlock(&lun->lun_lock);
3633 	p = malloc(sizeof(uint64_t) * CTL_MAX_INIT_PER_PORT, M_CTL,
3634 	    M_WAITOK | M_ZERO);
3635 	mtx_lock(&lun->lun_lock);
3636 	if (lun->pr_keys[i] == NULL)
3637 		lun->pr_keys[i] = p;
3638 	else
3639 		free(p, M_CTL);
3640 }
3641 
3642 static void
3643 ctl_set_prkey(struct ctl_lun *lun, uint32_t residx, uint64_t key)
3644 {
3645 	uint64_t *t;
3646 
3647 	t = lun->pr_keys[residx/CTL_MAX_INIT_PER_PORT];
3648 	KASSERT(t != NULL, ("prkey %d is not allocated", residx));
3649 	t[residx % CTL_MAX_INIT_PER_PORT] = key;
3650 }
3651 
3652 /*
3653  * ctl_softc, pool_name, total_ctl_io are passed in.
3654  * npool is passed out.
3655  */
3656 int
3657 ctl_pool_create(struct ctl_softc *ctl_softc, const char *pool_name,
3658 		uint32_t total_ctl_io, void **npool)
3659 {
3660 #ifdef IO_POOLS
3661 	struct ctl_io_pool *pool;
3662 
3663 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3664 					    M_NOWAIT | M_ZERO);
3665 	if (pool == NULL)
3666 		return (ENOMEM);
3667 
3668 	snprintf(pool->name, sizeof(pool->name), "CTL IO %s", pool_name);
3669 	pool->ctl_softc = ctl_softc;
3670 	pool->zone = uma_zsecond_create(pool->name, NULL,
3671 	    NULL, NULL, NULL, ctl_softc->io_zone);
3672 	/* uma_prealloc(pool->zone, total_ctl_io); */
3673 
3674 	*npool = pool;
3675 #else
3676 	*npool = ctl_softc->io_zone;
3677 #endif
3678 	return (0);
3679 }
3680 
3681 void
3682 ctl_pool_free(struct ctl_io_pool *pool)
3683 {
3684 
3685 	if (pool == NULL)
3686 		return;
3687 
3688 #ifdef IO_POOLS
3689 	uma_zdestroy(pool->zone);
3690 	free(pool, M_CTL);
3691 #endif
3692 }
3693 
3694 union ctl_io *
3695 ctl_alloc_io(void *pool_ref)
3696 {
3697 	union ctl_io *io;
3698 #ifdef IO_POOLS
3699 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3700 
3701 	io = uma_zalloc(pool->zone, M_WAITOK);
3702 #else
3703 	io = uma_zalloc((uma_zone_t)pool_ref, M_WAITOK);
3704 #endif
3705 	if (io != NULL)
3706 		io->io_hdr.pool = pool_ref;
3707 	return (io);
3708 }
3709 
3710 union ctl_io *
3711 ctl_alloc_io_nowait(void *pool_ref)
3712 {
3713 	union ctl_io *io;
3714 #ifdef IO_POOLS
3715 	struct ctl_io_pool *pool = (struct ctl_io_pool *)pool_ref;
3716 
3717 	io = uma_zalloc(pool->zone, M_NOWAIT);
3718 #else
3719 	io = uma_zalloc((uma_zone_t)pool_ref, M_NOWAIT);
3720 #endif
3721 	if (io != NULL)
3722 		io->io_hdr.pool = pool_ref;
3723 	return (io);
3724 }
3725 
3726 void
3727 ctl_free_io(union ctl_io *io)
3728 {
3729 #ifdef IO_POOLS
3730 	struct ctl_io_pool *pool;
3731 #endif
3732 
3733 	if (io == NULL)
3734 		return;
3735 
3736 #ifdef IO_POOLS
3737 	pool = (struct ctl_io_pool *)io->io_hdr.pool;
3738 	uma_zfree(pool->zone, io);
3739 #else
3740 	uma_zfree((uma_zone_t)io->io_hdr.pool, io);
3741 #endif
3742 }
3743 
3744 void
3745 ctl_zero_io(union ctl_io *io)
3746 {
3747 	void *pool_ref;
3748 
3749 	if (io == NULL)
3750 		return;
3751 
3752 	/*
3753 	 * May need to preserve linked list pointers at some point too.
3754 	 */
3755 	pool_ref = io->io_hdr.pool;
3756 	memset(io, 0, sizeof(*io));
3757 	io->io_hdr.pool = pool_ref;
3758 }
3759 
3760 int
3761 ctl_expand_number(const char *buf, uint64_t *num)
3762 {
3763 	char *endptr;
3764 	uint64_t number;
3765 	unsigned shift;
3766 
3767 	number = strtoq(buf, &endptr, 0);
3768 
3769 	switch (tolower((unsigned char)*endptr)) {
3770 	case 'e':
3771 		shift = 60;
3772 		break;
3773 	case 'p':
3774 		shift = 50;
3775 		break;
3776 	case 't':
3777 		shift = 40;
3778 		break;
3779 	case 'g':
3780 		shift = 30;
3781 		break;
3782 	case 'm':
3783 		shift = 20;
3784 		break;
3785 	case 'k':
3786 		shift = 10;
3787 		break;
3788 	case 'b':
3789 	case '\0': /* No unit. */
3790 		*num = number;
3791 		return (0);
3792 	default:
3793 		/* Unrecognized unit. */
3794 		return (-1);
3795 	}
3796 
3797 	if ((number << shift) >> shift != number) {
3798 		/* Overflow */
3799 		return (-1);
3800 	}
3801 	*num = number << shift;
3802 	return (0);
3803 }
3804 
3805 
3806 /*
3807  * This routine could be used in the future to load default and/or saved
3808  * mode page parameters for a particuar lun.
3809  */
3810 static int
3811 ctl_init_page_index(struct ctl_lun *lun)
3812 {
3813 	int i, page_code;
3814 	struct ctl_page_index *page_index;
3815 	const char *value;
3816 	uint64_t ival;
3817 
3818 	memcpy(&lun->mode_pages.index, page_index_template,
3819 	       sizeof(page_index_template));
3820 
3821 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
3822 
3823 		page_index = &lun->mode_pages.index[i];
3824 		if (lun->be_lun->lun_type == T_DIRECT &&
3825 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
3826 			continue;
3827 		if (lun->be_lun->lun_type == T_PROCESSOR &&
3828 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
3829 			continue;
3830 		if (lun->be_lun->lun_type == T_CDROM &&
3831 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
3832 			continue;
3833 
3834 		page_code = page_index->page_code & SMPH_PC_MASK;
3835 		switch (page_code) {
3836 		case SMS_RW_ERROR_RECOVERY_PAGE: {
3837 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3838 			    ("subpage %#x for page %#x is incorrect!",
3839 			    page_index->subpage, page_code));
3840 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT],
3841 			       &rw_er_page_default,
3842 			       sizeof(rw_er_page_default));
3843 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_CHANGEABLE],
3844 			       &rw_er_page_changeable,
3845 			       sizeof(rw_er_page_changeable));
3846 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_DEFAULT],
3847 			       &rw_er_page_default,
3848 			       sizeof(rw_er_page_default));
3849 			memcpy(&lun->mode_pages.rw_er_page[CTL_PAGE_SAVED],
3850 			       &rw_er_page_default,
3851 			       sizeof(rw_er_page_default));
3852 			page_index->page_data =
3853 				(uint8_t *)lun->mode_pages.rw_er_page;
3854 			break;
3855 		}
3856 		case SMS_FORMAT_DEVICE_PAGE: {
3857 			struct scsi_format_page *format_page;
3858 
3859 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3860 			    ("subpage %#x for page %#x is incorrect!",
3861 			    page_index->subpage, page_code));
3862 
3863 			/*
3864 			 * Sectors per track are set above.  Bytes per
3865 			 * sector need to be set here on a per-LUN basis.
3866 			 */
3867 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
3868 			       &format_page_default,
3869 			       sizeof(format_page_default));
3870 			memcpy(&lun->mode_pages.format_page[
3871 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
3872 			       sizeof(format_page_changeable));
3873 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
3874 			       &format_page_default,
3875 			       sizeof(format_page_default));
3876 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
3877 			       &format_page_default,
3878 			       sizeof(format_page_default));
3879 
3880 			format_page = &lun->mode_pages.format_page[
3881 				CTL_PAGE_CURRENT];
3882 			scsi_ulto2b(lun->be_lun->blocksize,
3883 				    format_page->bytes_per_sector);
3884 
3885 			format_page = &lun->mode_pages.format_page[
3886 				CTL_PAGE_DEFAULT];
3887 			scsi_ulto2b(lun->be_lun->blocksize,
3888 				    format_page->bytes_per_sector);
3889 
3890 			format_page = &lun->mode_pages.format_page[
3891 				CTL_PAGE_SAVED];
3892 			scsi_ulto2b(lun->be_lun->blocksize,
3893 				    format_page->bytes_per_sector);
3894 
3895 			page_index->page_data =
3896 				(uint8_t *)lun->mode_pages.format_page;
3897 			break;
3898 		}
3899 		case SMS_RIGID_DISK_PAGE: {
3900 			struct scsi_rigid_disk_page *rigid_disk_page;
3901 			uint32_t sectors_per_cylinder;
3902 			uint64_t cylinders;
3903 #ifndef	__XSCALE__
3904 			int shift;
3905 #endif /* !__XSCALE__ */
3906 
3907 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3908 			    ("subpage %#x for page %#x is incorrect!",
3909 			    page_index->subpage, page_code));
3910 
3911 			/*
3912 			 * Rotation rate and sectors per track are set
3913 			 * above.  We calculate the cylinders here based on
3914 			 * capacity.  Due to the number of heads and
3915 			 * sectors per track we're using, smaller arrays
3916 			 * may turn out to have 0 cylinders.  Linux and
3917 			 * FreeBSD don't pay attention to these mode pages
3918 			 * to figure out capacity, but Solaris does.  It
3919 			 * seems to deal with 0 cylinders just fine, and
3920 			 * works out a fake geometry based on the capacity.
3921 			 */
3922 			memcpy(&lun->mode_pages.rigid_disk_page[
3923 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
3924 			       sizeof(rigid_disk_page_default));
3925 			memcpy(&lun->mode_pages.rigid_disk_page[
3926 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
3927 			       sizeof(rigid_disk_page_changeable));
3928 
3929 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
3930 				CTL_DEFAULT_HEADS;
3931 
3932 			/*
3933 			 * The divide method here will be more accurate,
3934 			 * probably, but results in floating point being
3935 			 * used in the kernel on i386 (__udivdi3()).  On the
3936 			 * XScale, though, __udivdi3() is implemented in
3937 			 * software.
3938 			 *
3939 			 * The shift method for cylinder calculation is
3940 			 * accurate if sectors_per_cylinder is a power of
3941 			 * 2.  Otherwise it might be slightly off -- you
3942 			 * might have a bit of a truncation problem.
3943 			 */
3944 #ifdef	__XSCALE__
3945 			cylinders = (lun->be_lun->maxlba + 1) /
3946 				sectors_per_cylinder;
3947 #else
3948 			for (shift = 31; shift > 0; shift--) {
3949 				if (sectors_per_cylinder & (1 << shift))
3950 					break;
3951 			}
3952 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
3953 #endif
3954 
3955 			/*
3956 			 * We've basically got 3 bytes, or 24 bits for the
3957 			 * cylinder size in the mode page.  If we're over,
3958 			 * just round down to 2^24.
3959 			 */
3960 			if (cylinders > 0xffffff)
3961 				cylinders = 0xffffff;
3962 
3963 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
3964 				CTL_PAGE_DEFAULT];
3965 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
3966 
3967 			if ((value = ctl_get_opt(&lun->be_lun->options,
3968 			    "rpm")) != NULL) {
3969 				scsi_ulto2b(strtol(value, NULL, 0),
3970 				     rigid_disk_page->rotation_rate);
3971 			}
3972 
3973 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_CURRENT],
3974 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3975 			       sizeof(rigid_disk_page_default));
3976 			memcpy(&lun->mode_pages.rigid_disk_page[CTL_PAGE_SAVED],
3977 			       &lun->mode_pages.rigid_disk_page[CTL_PAGE_DEFAULT],
3978 			       sizeof(rigid_disk_page_default));
3979 
3980 			page_index->page_data =
3981 				(uint8_t *)lun->mode_pages.rigid_disk_page;
3982 			break;
3983 		}
3984 		case SMS_CACHING_PAGE: {
3985 			struct scsi_caching_page *caching_page;
3986 
3987 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
3988 			    ("subpage %#x for page %#x is incorrect!",
3989 			    page_index->subpage, page_code));
3990 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
3991 			       &caching_page_default,
3992 			       sizeof(caching_page_default));
3993 			memcpy(&lun->mode_pages.caching_page[
3994 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
3995 			       sizeof(caching_page_changeable));
3996 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
3997 			       &caching_page_default,
3998 			       sizeof(caching_page_default));
3999 			caching_page = &lun->mode_pages.caching_page[
4000 			    CTL_PAGE_SAVED];
4001 			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4002 			if (value != NULL && strcmp(value, "off") == 0)
4003 				caching_page->flags1 &= ~SCP_WCE;
4004 			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4005 			if (value != NULL && strcmp(value, "off") == 0)
4006 				caching_page->flags1 |= SCP_RCD;
4007 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4008 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4009 			       sizeof(caching_page_default));
4010 			page_index->page_data =
4011 				(uint8_t *)lun->mode_pages.caching_page;
4012 			break;
4013 		}
4014 		case SMS_CONTROL_MODE_PAGE: {
4015 			switch (page_index->subpage) {
4016 			case SMS_SUBPAGE_PAGE_0: {
4017 				struct scsi_control_page *control_page;
4018 
4019 				memcpy(&lun->mode_pages.control_page[
4020 				    CTL_PAGE_DEFAULT],
4021 				       &control_page_default,
4022 				       sizeof(control_page_default));
4023 				memcpy(&lun->mode_pages.control_page[
4024 				    CTL_PAGE_CHANGEABLE],
4025 				       &control_page_changeable,
4026 				       sizeof(control_page_changeable));
4027 				memcpy(&lun->mode_pages.control_page[
4028 				    CTL_PAGE_SAVED],
4029 				       &control_page_default,
4030 				       sizeof(control_page_default));
4031 				control_page = &lun->mode_pages.control_page[
4032 				    CTL_PAGE_SAVED];
4033 				value = ctl_get_opt(&lun->be_lun->options,
4034 				    "reordering");
4035 				if (value != NULL &&
4036 				    strcmp(value, "unrestricted") == 0) {
4037 					control_page->queue_flags &=
4038 					    ~SCP_QUEUE_ALG_MASK;
4039 					control_page->queue_flags |=
4040 					    SCP_QUEUE_ALG_UNRESTRICTED;
4041 				}
4042 				memcpy(&lun->mode_pages.control_page[
4043 				    CTL_PAGE_CURRENT],
4044 				       &lun->mode_pages.control_page[
4045 				    CTL_PAGE_SAVED],
4046 				       sizeof(control_page_default));
4047 				page_index->page_data =
4048 				    (uint8_t *)lun->mode_pages.control_page;
4049 				break;
4050 			}
4051 			case 0x01:
4052 				memcpy(&lun->mode_pages.control_ext_page[
4053 				    CTL_PAGE_DEFAULT],
4054 				       &control_ext_page_default,
4055 				       sizeof(control_ext_page_default));
4056 				memcpy(&lun->mode_pages.control_ext_page[
4057 				    CTL_PAGE_CHANGEABLE],
4058 				       &control_ext_page_changeable,
4059 				       sizeof(control_ext_page_changeable));
4060 				memcpy(&lun->mode_pages.control_ext_page[
4061 				    CTL_PAGE_SAVED],
4062 				       &control_ext_page_default,
4063 				       sizeof(control_ext_page_default));
4064 				memcpy(&lun->mode_pages.control_ext_page[
4065 				    CTL_PAGE_CURRENT],
4066 				       &lun->mode_pages.control_ext_page[
4067 				    CTL_PAGE_SAVED],
4068 				       sizeof(control_ext_page_default));
4069 				page_index->page_data =
4070 				    (uint8_t *)lun->mode_pages.control_ext_page;
4071 				break;
4072 			default:
4073 				panic("subpage %#x for page %#x is incorrect!",
4074 				      page_index->subpage, page_code);
4075 			}
4076 			break;
4077 		}
4078 		case SMS_INFO_EXCEPTIONS_PAGE: {
4079 			switch (page_index->subpage) {
4080 			case SMS_SUBPAGE_PAGE_0:
4081 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_CURRENT],
4082 				       &ie_page_default,
4083 				       sizeof(ie_page_default));
4084 				memcpy(&lun->mode_pages.ie_page[
4085 				       CTL_PAGE_CHANGEABLE], &ie_page_changeable,
4086 				       sizeof(ie_page_changeable));
4087 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_DEFAULT],
4088 				       &ie_page_default,
4089 				       sizeof(ie_page_default));
4090 				memcpy(&lun->mode_pages.ie_page[CTL_PAGE_SAVED],
4091 				       &ie_page_default,
4092 				       sizeof(ie_page_default));
4093 				page_index->page_data =
4094 					(uint8_t *)lun->mode_pages.ie_page;
4095 				break;
4096 			case 0x02: {
4097 				struct ctl_logical_block_provisioning_page *page;
4098 
4099 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_DEFAULT],
4100 				       &lbp_page_default,
4101 				       sizeof(lbp_page_default));
4102 				memcpy(&lun->mode_pages.lbp_page[
4103 				       CTL_PAGE_CHANGEABLE], &lbp_page_changeable,
4104 				       sizeof(lbp_page_changeable));
4105 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4106 				       &lbp_page_default,
4107 				       sizeof(lbp_page_default));
4108 				page = &lun->mode_pages.lbp_page[CTL_PAGE_SAVED];
4109 				value = ctl_get_opt(&lun->be_lun->options,
4110 				    "avail-threshold");
4111 				if (value != NULL &&
4112 				    ctl_expand_number(value, &ival) == 0) {
4113 					page->descr[0].flags |= SLBPPD_ENABLED |
4114 					    SLBPPD_ARMING_DEC;
4115 					if (lun->be_lun->blocksize)
4116 						ival /= lun->be_lun->blocksize;
4117 					else
4118 						ival /= 512;
4119 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4120 					    page->descr[0].count);
4121 				}
4122 				value = ctl_get_opt(&lun->be_lun->options,
4123 				    "used-threshold");
4124 				if (value != NULL &&
4125 				    ctl_expand_number(value, &ival) == 0) {
4126 					page->descr[1].flags |= SLBPPD_ENABLED |
4127 					    SLBPPD_ARMING_INC;
4128 					if (lun->be_lun->blocksize)
4129 						ival /= lun->be_lun->blocksize;
4130 					else
4131 						ival /= 512;
4132 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4133 					    page->descr[1].count);
4134 				}
4135 				value = ctl_get_opt(&lun->be_lun->options,
4136 				    "pool-avail-threshold");
4137 				if (value != NULL &&
4138 				    ctl_expand_number(value, &ival) == 0) {
4139 					page->descr[2].flags |= SLBPPD_ENABLED |
4140 					    SLBPPD_ARMING_DEC;
4141 					if (lun->be_lun->blocksize)
4142 						ival /= lun->be_lun->blocksize;
4143 					else
4144 						ival /= 512;
4145 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4146 					    page->descr[2].count);
4147 				}
4148 				value = ctl_get_opt(&lun->be_lun->options,
4149 				    "pool-used-threshold");
4150 				if (value != NULL &&
4151 				    ctl_expand_number(value, &ival) == 0) {
4152 					page->descr[3].flags |= SLBPPD_ENABLED |
4153 					    SLBPPD_ARMING_INC;
4154 					if (lun->be_lun->blocksize)
4155 						ival /= lun->be_lun->blocksize;
4156 					else
4157 						ival /= 512;
4158 					scsi_ulto4b(ival >> CTL_LBP_EXPONENT,
4159 					    page->descr[3].count);
4160 				}
4161 				memcpy(&lun->mode_pages.lbp_page[CTL_PAGE_CURRENT],
4162 				       &lun->mode_pages.lbp_page[CTL_PAGE_SAVED],
4163 				       sizeof(lbp_page_default));
4164 				page_index->page_data =
4165 					(uint8_t *)lun->mode_pages.lbp_page;
4166 				break;
4167 			}
4168 			default:
4169 				panic("subpage %#x for page %#x is incorrect!",
4170 				      page_index->subpage, page_code);
4171 			}
4172 			break;
4173 		}
4174 		case SMS_CDDVD_CAPS_PAGE:{
4175 			KASSERT(page_index->subpage == SMS_SUBPAGE_PAGE_0,
4176 			    ("subpage %#x for page %#x is incorrect!",
4177 			    page_index->subpage, page_code));
4178 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_DEFAULT],
4179 			       &cddvd_page_default,
4180 			       sizeof(cddvd_page_default));
4181 			memcpy(&lun->mode_pages.cddvd_page[
4182 			       CTL_PAGE_CHANGEABLE], &cddvd_page_changeable,
4183 			       sizeof(cddvd_page_changeable));
4184 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4185 			       &cddvd_page_default,
4186 			       sizeof(cddvd_page_default));
4187 			memcpy(&lun->mode_pages.cddvd_page[CTL_PAGE_CURRENT],
4188 			       &lun->mode_pages.cddvd_page[CTL_PAGE_SAVED],
4189 			       sizeof(cddvd_page_default));
4190 			page_index->page_data =
4191 				(uint8_t *)lun->mode_pages.cddvd_page;
4192 			break;
4193 		}
4194 		case SMS_VENDOR_SPECIFIC_PAGE:{
4195 			switch (page_index->subpage) {
4196 			case DBGCNF_SUBPAGE_CODE: {
4197 				memcpy(&lun->mode_pages.debugconf_subpage[
4198 				       CTL_PAGE_CURRENT],
4199 				       &debugconf_page_default,
4200 				       sizeof(debugconf_page_default));
4201 				memcpy(&lun->mode_pages.debugconf_subpage[
4202 				       CTL_PAGE_CHANGEABLE],
4203 				       &debugconf_page_changeable,
4204 				       sizeof(debugconf_page_changeable));
4205 				memcpy(&lun->mode_pages.debugconf_subpage[
4206 				       CTL_PAGE_DEFAULT],
4207 				       &debugconf_page_default,
4208 				       sizeof(debugconf_page_default));
4209 				memcpy(&lun->mode_pages.debugconf_subpage[
4210 				       CTL_PAGE_SAVED],
4211 				       &debugconf_page_default,
4212 				       sizeof(debugconf_page_default));
4213 				page_index->page_data =
4214 				    (uint8_t *)lun->mode_pages.debugconf_subpage;
4215 				break;
4216 			}
4217 			default:
4218 				panic("subpage %#x for page %#x is incorrect!",
4219 				      page_index->subpage, page_code);
4220 			}
4221 			break;
4222 		}
4223 		default:
4224 			panic("invalid page code value %#x", page_code);
4225 		}
4226 	}
4227 
4228 	return (CTL_RETVAL_COMPLETE);
4229 }
4230 
4231 static int
4232 ctl_init_log_page_index(struct ctl_lun *lun)
4233 {
4234 	struct ctl_page_index *page_index;
4235 	int i, j, k, prev;
4236 
4237 	memcpy(&lun->log_pages.index, log_page_index_template,
4238 	       sizeof(log_page_index_template));
4239 
4240 	prev = -1;
4241 	for (i = 0, j = 0, k = 0; i < CTL_NUM_LOG_PAGES; i++) {
4242 
4243 		page_index = &lun->log_pages.index[i];
4244 		if (lun->be_lun->lun_type == T_DIRECT &&
4245 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
4246 			continue;
4247 		if (lun->be_lun->lun_type == T_PROCESSOR &&
4248 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
4249 			continue;
4250 		if (lun->be_lun->lun_type == T_CDROM &&
4251 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
4252 			continue;
4253 
4254 		if (page_index->page_code == SLS_LOGICAL_BLOCK_PROVISIONING &&
4255 		    lun->backend->lun_attr == NULL)
4256 			continue;
4257 
4258 		if (page_index->page_code != prev) {
4259 			lun->log_pages.pages_page[j] = page_index->page_code;
4260 			prev = page_index->page_code;
4261 			j++;
4262 		}
4263 		lun->log_pages.subpages_page[k*2] = page_index->page_code;
4264 		lun->log_pages.subpages_page[k*2+1] = page_index->subpage;
4265 		k++;
4266 	}
4267 	lun->log_pages.index[0].page_data = &lun->log_pages.pages_page[0];
4268 	lun->log_pages.index[0].page_len = j;
4269 	lun->log_pages.index[1].page_data = &lun->log_pages.subpages_page[0];
4270 	lun->log_pages.index[1].page_len = k * 2;
4271 	lun->log_pages.index[2].page_data = &lun->log_pages.lbp_page[0];
4272 	lun->log_pages.index[2].page_len = 12*CTL_NUM_LBP_PARAMS;
4273 	lun->log_pages.index[3].page_data = (uint8_t *)&lun->log_pages.stat_page;
4274 	lun->log_pages.index[3].page_len = sizeof(lun->log_pages.stat_page);
4275 
4276 	return (CTL_RETVAL_COMPLETE);
4277 }
4278 
4279 static int
4280 hex2bin(const char *str, uint8_t *buf, int buf_size)
4281 {
4282 	int i;
4283 	u_char c;
4284 
4285 	memset(buf, 0, buf_size);
4286 	while (isspace(str[0]))
4287 		str++;
4288 	if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X'))
4289 		str += 2;
4290 	buf_size *= 2;
4291 	for (i = 0; str[i] != 0 && i < buf_size; i++) {
4292 		c = str[i];
4293 		if (isdigit(c))
4294 			c -= '0';
4295 		else if (isalpha(c))
4296 			c -= isupper(c) ? 'A' - 10 : 'a' - 10;
4297 		else
4298 			break;
4299 		if (c >= 16)
4300 			break;
4301 		if ((i & 1) == 0)
4302 			buf[i / 2] |= (c << 4);
4303 		else
4304 			buf[i / 2] |= c;
4305 	}
4306 	return ((i + 1) / 2);
4307 }
4308 
4309 /*
4310  * LUN allocation.
4311  *
4312  * Requirements:
4313  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4314  *   wants us to allocate the LUN and he can block.
4315  * - ctl_softc is always set
4316  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4317  *
4318  * Returns 0 for success, non-zero (errno) for failure.
4319  */
4320 static int
4321 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4322 	      struct ctl_be_lun *const be_lun)
4323 {
4324 	struct ctl_lun *nlun, *lun;
4325 	struct scsi_vpd_id_descriptor *desc;
4326 	struct scsi_vpd_id_t10 *t10id;
4327 	const char *eui, *naa, *scsiname, *vendor, *value;
4328 	int lun_number, i, lun_malloced;
4329 	int devidlen, idlen1, idlen2 = 0, len;
4330 
4331 	if (be_lun == NULL)
4332 		return (EINVAL);
4333 
4334 	/*
4335 	 * We currently only support Direct Access or Processor LUN types.
4336 	 */
4337 	switch (be_lun->lun_type) {
4338 	case T_DIRECT:
4339 	case T_PROCESSOR:
4340 	case T_CDROM:
4341 		break;
4342 	case T_SEQUENTIAL:
4343 	case T_CHANGER:
4344 	default:
4345 		be_lun->lun_config_status(be_lun->be_lun,
4346 					  CTL_LUN_CONFIG_FAILURE);
4347 		break;
4348 	}
4349 	if (ctl_lun == NULL) {
4350 		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4351 		lun_malloced = 1;
4352 	} else {
4353 		lun_malloced = 0;
4354 		lun = ctl_lun;
4355 	}
4356 
4357 	memset(lun, 0, sizeof(*lun));
4358 	if (lun_malloced)
4359 		lun->flags = CTL_LUN_MALLOCED;
4360 
4361 	/* Generate LUN ID. */
4362 	devidlen = max(CTL_DEVID_MIN_LEN,
4363 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4364 	idlen1 = sizeof(*t10id) + devidlen;
4365 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4366 	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4367 	if (scsiname != NULL) {
4368 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4369 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4370 	}
4371 	eui = ctl_get_opt(&be_lun->options, "eui");
4372 	if (eui != NULL) {
4373 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4374 	}
4375 	naa = ctl_get_opt(&be_lun->options, "naa");
4376 	if (naa != NULL) {
4377 		len += sizeof(struct scsi_vpd_id_descriptor) + 16;
4378 	}
4379 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4380 	    M_CTL, M_WAITOK | M_ZERO);
4381 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4382 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4383 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4384 	desc->length = idlen1;
4385 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4386 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4387 	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4388 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4389 	} else {
4390 		strncpy(t10id->vendor, vendor,
4391 		    min(sizeof(t10id->vendor), strlen(vendor)));
4392 	}
4393 	strncpy((char *)t10id->vendor_spec_id,
4394 	    (char *)be_lun->device_id, devidlen);
4395 	if (scsiname != NULL) {
4396 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4397 		    desc->length);
4398 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4399 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4400 		    SVPD_ID_TYPE_SCSI_NAME;
4401 		desc->length = idlen2;
4402 		strlcpy(desc->identifier, scsiname, idlen2);
4403 	}
4404 	if (eui != NULL) {
4405 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4406 		    desc->length);
4407 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4408 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4409 		    SVPD_ID_TYPE_EUI64;
4410 		desc->length = hex2bin(eui, desc->identifier, 16);
4411 		desc->length = desc->length > 12 ? 16 :
4412 		    (desc->length > 8 ? 12 : 8);
4413 		len -= 16 - desc->length;
4414 	}
4415 	if (naa != NULL) {
4416 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4417 		    desc->length);
4418 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4419 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4420 		    SVPD_ID_TYPE_NAA;
4421 		desc->length = hex2bin(naa, desc->identifier, 16);
4422 		desc->length = desc->length > 8 ? 16 : 8;
4423 		len -= 16 - desc->length;
4424 	}
4425 	lun->lun_devid->len = len;
4426 
4427 	mtx_lock(&ctl_softc->ctl_lock);
4428 	/*
4429 	 * See if the caller requested a particular LUN number.  If so, see
4430 	 * if it is available.  Otherwise, allocate the first available LUN.
4431 	 */
4432 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4433 		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4434 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4435 			mtx_unlock(&ctl_softc->ctl_lock);
4436 			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4437 				printf("ctl: requested LUN ID %d is higher "
4438 				       "than CTL_MAX_LUNS - 1 (%d)\n",
4439 				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4440 			} else {
4441 				/*
4442 				 * XXX KDM return an error, or just assign
4443 				 * another LUN ID in this case??
4444 				 */
4445 				printf("ctl: requested LUN ID %d is already "
4446 				       "in use\n", be_lun->req_lun_id);
4447 			}
4448 			if (lun->flags & CTL_LUN_MALLOCED)
4449 				free(lun, M_CTL);
4450 			be_lun->lun_config_status(be_lun->be_lun,
4451 						  CTL_LUN_CONFIG_FAILURE);
4452 			return (ENOSPC);
4453 		}
4454 		lun_number = be_lun->req_lun_id;
4455 	} else {
4456 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, 0, CTL_MAX_LUNS);
4457 		if (lun_number == -1) {
4458 			mtx_unlock(&ctl_softc->ctl_lock);
4459 			printf("ctl: can't allocate LUN, out of LUNs\n");
4460 			if (lun->flags & CTL_LUN_MALLOCED)
4461 				free(lun, M_CTL);
4462 			be_lun->lun_config_status(be_lun->be_lun,
4463 						  CTL_LUN_CONFIG_FAILURE);
4464 			return (ENOSPC);
4465 		}
4466 	}
4467 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4468 
4469 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4470 	lun->lun = lun_number;
4471 	lun->be_lun = be_lun;
4472 	/*
4473 	 * The processor LUN is always enabled.  Disk LUNs come on line
4474 	 * disabled, and must be enabled by the backend.
4475 	 */
4476 	lun->flags |= CTL_LUN_DISABLED;
4477 	lun->backend = be_lun->be;
4478 	be_lun->ctl_lun = lun;
4479 	be_lun->lun_id = lun_number;
4480 	atomic_add_int(&be_lun->be->num_luns, 1);
4481 	if (be_lun->flags & CTL_LUN_FLAG_EJECTED)
4482 		lun->flags |= CTL_LUN_EJECTED;
4483 	if (be_lun->flags & CTL_LUN_FLAG_NO_MEDIA)
4484 		lun->flags |= CTL_LUN_NO_MEDIA;
4485 	if (be_lun->flags & CTL_LUN_FLAG_STOPPED)
4486 		lun->flags |= CTL_LUN_STOPPED;
4487 
4488 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4489 		lun->flags |= CTL_LUN_PRIMARY_SC;
4490 
4491 	value = ctl_get_opt(&be_lun->options, "removable");
4492 	if (value != NULL) {
4493 		if (strcmp(value, "on") == 0)
4494 			lun->flags |= CTL_LUN_REMOVABLE;
4495 	} else if (be_lun->lun_type == T_CDROM)
4496 		lun->flags |= CTL_LUN_REMOVABLE;
4497 
4498 	lun->ctl_softc = ctl_softc;
4499 #ifdef CTL_TIME_IO
4500 	lun->last_busy = getsbinuptime();
4501 #endif
4502 	TAILQ_INIT(&lun->ooa_queue);
4503 	TAILQ_INIT(&lun->blocked_queue);
4504 	STAILQ_INIT(&lun->error_list);
4505 	ctl_tpc_lun_init(lun);
4506 
4507 	/*
4508 	 * Initialize the mode and log page index.
4509 	 */
4510 	ctl_init_page_index(lun);
4511 	ctl_init_log_page_index(lun);
4512 
4513 	/*
4514 	 * Now, before we insert this lun on the lun list, set the lun
4515 	 * inventory changed UA for all other luns.
4516 	 */
4517 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4518 		mtx_lock(&nlun->lun_lock);
4519 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4520 		mtx_unlock(&nlun->lun_lock);
4521 	}
4522 
4523 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4524 
4525 	ctl_softc->ctl_luns[lun_number] = lun;
4526 
4527 	ctl_softc->num_luns++;
4528 
4529 	/* Setup statistics gathering */
4530 	lun->stats.device_type = be_lun->lun_type;
4531 	lun->stats.lun_number = lun_number;
4532 	lun->stats.blocksize = be_lun->blocksize;
4533 	if (be_lun->blocksize == 0)
4534 		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4535 	for (i = 0;i < CTL_MAX_PORTS;i++)
4536 		lun->stats.ports[i].targ_port = i;
4537 
4538 	mtx_unlock(&ctl_softc->ctl_lock);
4539 
4540 	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4541 	return (0);
4542 }
4543 
4544 /*
4545  * Delete a LUN.
4546  * Assumptions:
4547  * - LUN has already been marked invalid and any pending I/O has been taken
4548  *   care of.
4549  */
4550 static int
4551 ctl_free_lun(struct ctl_lun *lun)
4552 {
4553 	struct ctl_softc *softc;
4554 	struct ctl_lun *nlun;
4555 	int i;
4556 
4557 	softc = lun->ctl_softc;
4558 
4559 	mtx_assert(&softc->ctl_lock, MA_OWNED);
4560 
4561 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4562 
4563 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4564 
4565 	softc->ctl_luns[lun->lun] = NULL;
4566 
4567 	if (!TAILQ_EMPTY(&lun->ooa_queue))
4568 		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4569 
4570 	softc->num_luns--;
4571 
4572 	/*
4573 	 * Tell the backend to free resources, if this LUN has a backend.
4574 	 */
4575 	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4576 	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4577 
4578 	ctl_tpc_lun_shutdown(lun);
4579 	mtx_destroy(&lun->lun_lock);
4580 	free(lun->lun_devid, M_CTL);
4581 	for (i = 0; i < CTL_MAX_PORTS; i++)
4582 		free(lun->pending_ua[i], M_CTL);
4583 	for (i = 0; i < CTL_MAX_PORTS; i++)
4584 		free(lun->pr_keys[i], M_CTL);
4585 	free(lun->write_buffer, M_CTL);
4586 	if (lun->flags & CTL_LUN_MALLOCED)
4587 		free(lun, M_CTL);
4588 
4589 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4590 		mtx_lock(&nlun->lun_lock);
4591 		ctl_est_ua_all(nlun, -1, CTL_UA_LUN_CHANGE);
4592 		mtx_unlock(&nlun->lun_lock);
4593 	}
4594 
4595 	return (0);
4596 }
4597 
4598 static void
4599 ctl_create_lun(struct ctl_be_lun *be_lun)
4600 {
4601 
4602 	/*
4603 	 * ctl_alloc_lun() should handle all potential failure cases.
4604 	 */
4605 	ctl_alloc_lun(control_softc, NULL, be_lun);
4606 }
4607 
4608 int
4609 ctl_add_lun(struct ctl_be_lun *be_lun)
4610 {
4611 	struct ctl_softc *softc = control_softc;
4612 
4613 	mtx_lock(&softc->ctl_lock);
4614 	STAILQ_INSERT_TAIL(&softc->pending_lun_queue, be_lun, links);
4615 	mtx_unlock(&softc->ctl_lock);
4616 	wakeup(&softc->pending_lun_queue);
4617 
4618 	return (0);
4619 }
4620 
4621 int
4622 ctl_enable_lun(struct ctl_be_lun *be_lun)
4623 {
4624 	struct ctl_softc *softc;
4625 	struct ctl_port *port, *nport;
4626 	struct ctl_lun *lun;
4627 	int retval;
4628 
4629 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4630 	softc = lun->ctl_softc;
4631 
4632 	mtx_lock(&softc->ctl_lock);
4633 	mtx_lock(&lun->lun_lock);
4634 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4635 		/*
4636 		 * eh?  Why did we get called if the LUN is already
4637 		 * enabled?
4638 		 */
4639 		mtx_unlock(&lun->lun_lock);
4640 		mtx_unlock(&softc->ctl_lock);
4641 		return (0);
4642 	}
4643 	lun->flags &= ~CTL_LUN_DISABLED;
4644 	mtx_unlock(&lun->lun_lock);
4645 
4646 	STAILQ_FOREACH_SAFE(port, &softc->port_list, links, nport) {
4647 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4648 		    port->lun_map != NULL || port->lun_enable == NULL)
4649 			continue;
4650 
4651 		/*
4652 		 * Drop the lock while we call the FETD's enable routine.
4653 		 * This can lead to a callback into CTL (at least in the
4654 		 * case of the internal initiator frontend.
4655 		 */
4656 		mtx_unlock(&softc->ctl_lock);
4657 		retval = port->lun_enable(port->targ_lun_arg, lun->lun);
4658 		mtx_lock(&softc->ctl_lock);
4659 		if (retval != 0) {
4660 			printf("%s: FETD %s port %d returned error "
4661 			       "%d for lun_enable on lun %jd\n",
4662 			       __func__, port->port_name, port->targ_port,
4663 			       retval, (intmax_t)lun->lun);
4664 		}
4665 	}
4666 
4667 	mtx_unlock(&softc->ctl_lock);
4668 	ctl_isc_announce_lun(lun);
4669 
4670 	return (0);
4671 }
4672 
4673 int
4674 ctl_disable_lun(struct ctl_be_lun *be_lun)
4675 {
4676 	struct ctl_softc *softc;
4677 	struct ctl_port *port;
4678 	struct ctl_lun *lun;
4679 	int retval;
4680 
4681 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4682 	softc = lun->ctl_softc;
4683 
4684 	mtx_lock(&softc->ctl_lock);
4685 	mtx_lock(&lun->lun_lock);
4686 	if (lun->flags & CTL_LUN_DISABLED) {
4687 		mtx_unlock(&lun->lun_lock);
4688 		mtx_unlock(&softc->ctl_lock);
4689 		return (0);
4690 	}
4691 	lun->flags |= CTL_LUN_DISABLED;
4692 	mtx_unlock(&lun->lun_lock);
4693 
4694 	STAILQ_FOREACH(port, &softc->port_list, links) {
4695 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0 ||
4696 		    port->lun_map != NULL || port->lun_disable == NULL)
4697 			continue;
4698 
4699 		/*
4700 		 * Drop the lock before we call the frontend's disable
4701 		 * routine, to avoid lock order reversals.
4702 		 *
4703 		 * XXX KDM what happens if the frontend list changes while
4704 		 * we're traversing it?  It's unlikely, but should be handled.
4705 		 */
4706 		mtx_unlock(&softc->ctl_lock);
4707 		retval = port->lun_disable(port->targ_lun_arg, lun->lun);
4708 		mtx_lock(&softc->ctl_lock);
4709 		if (retval != 0) {
4710 			printf("%s: FETD %s port %d returned error "
4711 			       "%d for lun_disable on lun %jd\n",
4712 			       __func__, port->port_name, port->targ_port,
4713 			       retval, (intmax_t)lun->lun);
4714 		}
4715 	}
4716 
4717 	mtx_unlock(&softc->ctl_lock);
4718 	ctl_isc_announce_lun(lun);
4719 
4720 	return (0);
4721 }
4722 
4723 int
4724 ctl_start_lun(struct ctl_be_lun *be_lun)
4725 {
4726 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4727 
4728 	mtx_lock(&lun->lun_lock);
4729 	lun->flags &= ~CTL_LUN_STOPPED;
4730 	mtx_unlock(&lun->lun_lock);
4731 	return (0);
4732 }
4733 
4734 int
4735 ctl_stop_lun(struct ctl_be_lun *be_lun)
4736 {
4737 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4738 
4739 	mtx_lock(&lun->lun_lock);
4740 	lun->flags |= CTL_LUN_STOPPED;
4741 	mtx_unlock(&lun->lun_lock);
4742 	return (0);
4743 }
4744 
4745 int
4746 ctl_lun_no_media(struct ctl_be_lun *be_lun)
4747 {
4748 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4749 
4750 	mtx_lock(&lun->lun_lock);
4751 	lun->flags |= CTL_LUN_NO_MEDIA;
4752 	mtx_unlock(&lun->lun_lock);
4753 	return (0);
4754 }
4755 
4756 int
4757 ctl_lun_has_media(struct ctl_be_lun *be_lun)
4758 {
4759 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4760 	union ctl_ha_msg msg;
4761 
4762 	mtx_lock(&lun->lun_lock);
4763 	lun->flags &= ~(CTL_LUN_NO_MEDIA | CTL_LUN_EJECTED);
4764 	if (lun->flags & CTL_LUN_REMOVABLE)
4765 		ctl_est_ua_all(lun, -1, CTL_UA_MEDIUM_CHANGE);
4766 	mtx_unlock(&lun->lun_lock);
4767 	if ((lun->flags & CTL_LUN_REMOVABLE) &&
4768 	    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4769 		bzero(&msg.ua, sizeof(msg.ua));
4770 		msg.hdr.msg_type = CTL_MSG_UA;
4771 		msg.hdr.nexus.initid = -1;
4772 		msg.hdr.nexus.targ_port = -1;
4773 		msg.hdr.nexus.targ_lun = lun->lun;
4774 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4775 		msg.ua.ua_all = 1;
4776 		msg.ua.ua_set = 1;
4777 		msg.ua.ua_type = CTL_UA_MEDIUM_CHANGE;
4778 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4779 		    M_WAITOK);
4780 	}
4781 	return (0);
4782 }
4783 
4784 int
4785 ctl_lun_ejected(struct ctl_be_lun *be_lun)
4786 {
4787 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4788 
4789 	mtx_lock(&lun->lun_lock);
4790 	lun->flags |= CTL_LUN_EJECTED;
4791 	mtx_unlock(&lun->lun_lock);
4792 	return (0);
4793 }
4794 
4795 int
4796 ctl_lun_primary(struct ctl_be_lun *be_lun)
4797 {
4798 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4799 
4800 	mtx_lock(&lun->lun_lock);
4801 	lun->flags |= CTL_LUN_PRIMARY_SC;
4802 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4803 	mtx_unlock(&lun->lun_lock);
4804 	ctl_isc_announce_lun(lun);
4805 	return (0);
4806 }
4807 
4808 int
4809 ctl_lun_secondary(struct ctl_be_lun *be_lun)
4810 {
4811 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4812 
4813 	mtx_lock(&lun->lun_lock);
4814 	lun->flags &= ~CTL_LUN_PRIMARY_SC;
4815 	ctl_est_ua_all(lun, -1, CTL_UA_ASYM_ACC_CHANGE);
4816 	mtx_unlock(&lun->lun_lock);
4817 	ctl_isc_announce_lun(lun);
4818 	return (0);
4819 }
4820 
4821 int
4822 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4823 {
4824 	struct ctl_softc *softc;
4825 	struct ctl_lun *lun;
4826 
4827 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4828 	softc = lun->ctl_softc;
4829 
4830 	mtx_lock(&lun->lun_lock);
4831 
4832 	/*
4833 	 * The LUN needs to be disabled before it can be marked invalid.
4834 	 */
4835 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4836 		mtx_unlock(&lun->lun_lock);
4837 		return (-1);
4838 	}
4839 	/*
4840 	 * Mark the LUN invalid.
4841 	 */
4842 	lun->flags |= CTL_LUN_INVALID;
4843 
4844 	/*
4845 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
4846 	 * If we have something in the OOA queue, we'll free it when the
4847 	 * last I/O completes.
4848 	 */
4849 	if (TAILQ_EMPTY(&lun->ooa_queue)) {
4850 		mtx_unlock(&lun->lun_lock);
4851 		mtx_lock(&softc->ctl_lock);
4852 		ctl_free_lun(lun);
4853 		mtx_unlock(&softc->ctl_lock);
4854 	} else
4855 		mtx_unlock(&lun->lun_lock);
4856 
4857 	return (0);
4858 }
4859 
4860 void
4861 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
4862 {
4863 	struct ctl_lun *lun = (struct ctl_lun *)be_lun->ctl_lun;
4864 	union ctl_ha_msg msg;
4865 
4866 	mtx_lock(&lun->lun_lock);
4867 	ctl_est_ua_all(lun, -1, CTL_UA_CAPACITY_CHANGE);
4868 	mtx_unlock(&lun->lun_lock);
4869 	if (lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
4870 		/* Send msg to other side. */
4871 		bzero(&msg.ua, sizeof(msg.ua));
4872 		msg.hdr.msg_type = CTL_MSG_UA;
4873 		msg.hdr.nexus.initid = -1;
4874 		msg.hdr.nexus.targ_port = -1;
4875 		msg.hdr.nexus.targ_lun = lun->lun;
4876 		msg.hdr.nexus.targ_mapped_lun = lun->lun;
4877 		msg.ua.ua_all = 1;
4878 		msg.ua.ua_set = 1;
4879 		msg.ua.ua_type = CTL_UA_CAPACITY_CHANGE;
4880 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg.ua),
4881 		    M_WAITOK);
4882 	}
4883 }
4884 
4885 /*
4886  * Backend "memory move is complete" callback for requests that never
4887  * make it down to say RAIDCore's configuration code.
4888  */
4889 int
4890 ctl_config_move_done(union ctl_io *io)
4891 {
4892 	int retval;
4893 
4894 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
4895 	KASSERT(io->io_hdr.io_type == CTL_IO_SCSI,
4896 	    ("Config I/O type isn't CTL_IO_SCSI (%d)!", io->io_hdr.io_type));
4897 
4898 	if ((io->io_hdr.port_status != 0) &&
4899 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4900 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4901 		/*
4902 		 * For hardware error sense keys, the sense key
4903 		 * specific value is defined to be a retry count,
4904 		 * but we use it to pass back an internal FETD
4905 		 * error code.  XXX KDM  Hopefully the FETD is only
4906 		 * using 16 bits for an error code, since that's
4907 		 * all the space we have in the sks field.
4908 		 */
4909 		ctl_set_internal_failure(&io->scsiio,
4910 					 /*sks_valid*/ 1,
4911 					 /*retry_count*/
4912 					 io->io_hdr.port_status);
4913 	}
4914 
4915 	if (ctl_debug & CTL_DEBUG_CDB_DATA)
4916 		ctl_data_print(io);
4917 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN) ||
4918 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
4919 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) ||
4920 	    ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
4921 		/*
4922 		 * XXX KDM just assuming a single pointer here, and not a
4923 		 * S/G list.  If we start using S/G lists for config data,
4924 		 * we'll need to know how to clean them up here as well.
4925 		 */
4926 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
4927 			free(io->scsiio.kern_data_ptr, M_CTL);
4928 		ctl_done(io);
4929 		retval = CTL_RETVAL_COMPLETE;
4930 	} else {
4931 		/*
4932 		 * XXX KDM now we need to continue data movement.  Some
4933 		 * options:
4934 		 * - call ctl_scsiio() again?  We don't do this for data
4935 		 *   writes, because for those at least we know ahead of
4936 		 *   time where the write will go and how long it is.  For
4937 		 *   config writes, though, that information is largely
4938 		 *   contained within the write itself, thus we need to
4939 		 *   parse out the data again.
4940 		 *
4941 		 * - Call some other function once the data is in?
4942 		 */
4943 
4944 		/*
4945 		 * XXX KDM call ctl_scsiio() again for now, and check flag
4946 		 * bits to see whether we're allocated or not.
4947 		 */
4948 		retval = ctl_scsiio(&io->scsiio);
4949 	}
4950 	return (retval);
4951 }
4952 
4953 /*
4954  * This gets called by a backend driver when it is done with a
4955  * data_submit method.
4956  */
4957 void
4958 ctl_data_submit_done(union ctl_io *io)
4959 {
4960 	/*
4961 	 * If the IO_CONT flag is set, we need to call the supplied
4962 	 * function to continue processing the I/O, instead of completing
4963 	 * the I/O just yet.
4964 	 *
4965 	 * If there is an error, though, we don't want to keep processing.
4966 	 * Instead, just send status back to the initiator.
4967 	 */
4968 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4969 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4970 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4971 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4972 		io->scsiio.io_cont(io);
4973 		return;
4974 	}
4975 	ctl_done(io);
4976 }
4977 
4978 /*
4979  * This gets called by a backend driver when it is done with a
4980  * configuration write.
4981  */
4982 void
4983 ctl_config_write_done(union ctl_io *io)
4984 {
4985 	uint8_t *buf;
4986 
4987 	/*
4988 	 * If the IO_CONT flag is set, we need to call the supplied
4989 	 * function to continue processing the I/O, instead of completing
4990 	 * the I/O just yet.
4991 	 *
4992 	 * If there is an error, though, we don't want to keep processing.
4993 	 * Instead, just send status back to the initiator.
4994 	 */
4995 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
4996 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
4997 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
4998 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
4999 		io->scsiio.io_cont(io);
5000 		return;
5001 	}
5002 	/*
5003 	 * Since a configuration write can be done for commands that actually
5004 	 * have data allocated, like write buffer, and commands that have
5005 	 * no data, like start/stop unit, we need to check here.
5006 	 */
5007 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5008 		buf = io->scsiio.kern_data_ptr;
5009 	else
5010 		buf = NULL;
5011 	ctl_done(io);
5012 	if (buf)
5013 		free(buf, M_CTL);
5014 }
5015 
5016 void
5017 ctl_config_read_done(union ctl_io *io)
5018 {
5019 	uint8_t *buf;
5020 
5021 	/*
5022 	 * If there is some error -- we are done, skip data transfer.
5023 	 */
5024 	if ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0 ||
5025 	    ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
5026 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)) {
5027 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5028 			buf = io->scsiio.kern_data_ptr;
5029 		else
5030 			buf = NULL;
5031 		ctl_done(io);
5032 		if (buf)
5033 			free(buf, M_CTL);
5034 		return;
5035 	}
5036 
5037 	/*
5038 	 * If the IO_CONT flag is set, we need to call the supplied
5039 	 * function to continue processing the I/O, instead of completing
5040 	 * the I/O just yet.
5041 	 */
5042 	if (io->io_hdr.flags & CTL_FLAG_IO_CONT) {
5043 		io->scsiio.io_cont(io);
5044 		return;
5045 	}
5046 
5047 	ctl_datamove(io);
5048 }
5049 
5050 /*
5051  * SCSI release command.
5052  */
5053 int
5054 ctl_scsi_release(struct ctl_scsiio *ctsio)
5055 {
5056 	struct ctl_lun *lun;
5057 	uint32_t residx;
5058 
5059 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5060 
5061 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5062 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5063 
5064 	/*
5065 	 * XXX KDM right now, we only support LUN reservation.  We don't
5066 	 * support 3rd party reservations, or extent reservations, which
5067 	 * might actually need the parameter list.  If we've gotten this
5068 	 * far, we've got a LUN reservation.  Anything else got kicked out
5069 	 * above.  So, according to SPC, ignore the length.
5070 	 */
5071 
5072 	mtx_lock(&lun->lun_lock);
5073 
5074 	/*
5075 	 * According to SPC, it is not an error for an intiator to attempt
5076 	 * to release a reservation on a LUN that isn't reserved, or that
5077 	 * is reserved by another initiator.  The reservation can only be
5078 	 * released, though, by the initiator who made it or by one of
5079 	 * several reset type events.
5080 	 */
5081 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5082 			lun->flags &= ~CTL_LUN_RESERVED;
5083 
5084 	mtx_unlock(&lun->lun_lock);
5085 
5086 	ctl_set_success(ctsio);
5087 	ctl_done((union ctl_io *)ctsio);
5088 	return (CTL_RETVAL_COMPLETE);
5089 }
5090 
5091 int
5092 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5093 {
5094 	struct ctl_lun *lun;
5095 	uint32_t residx;
5096 
5097 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5098 
5099 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5100 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5101 
5102 	/*
5103 	 * XXX KDM right now, we only support LUN reservation.  We don't
5104 	 * support 3rd party reservations, or extent reservations, which
5105 	 * might actually need the parameter list.  If we've gotten this
5106 	 * far, we've got a LUN reservation.  Anything else got kicked out
5107 	 * above.  So, according to SPC, ignore the length.
5108 	 */
5109 
5110 	mtx_lock(&lun->lun_lock);
5111 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5112 		ctl_set_reservation_conflict(ctsio);
5113 		goto bailout;
5114 	}
5115 
5116 	/* SPC-3 exceptions to SPC-2 RESERVE and RELEASE behavior. */
5117 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5118 		ctl_set_success(ctsio);
5119 		goto bailout;
5120 	}
5121 
5122 	lun->flags |= CTL_LUN_RESERVED;
5123 	lun->res_idx = residx;
5124 	ctl_set_success(ctsio);
5125 
5126 bailout:
5127 	mtx_unlock(&lun->lun_lock);
5128 	ctl_done((union ctl_io *)ctsio);
5129 	return (CTL_RETVAL_COMPLETE);
5130 }
5131 
5132 int
5133 ctl_start_stop(struct ctl_scsiio *ctsio)
5134 {
5135 	struct scsi_start_stop_unit *cdb;
5136 	struct ctl_lun *lun;
5137 	int retval;
5138 
5139 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5140 
5141 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5142 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5143 
5144 	if ((cdb->how & SSS_PC_MASK) == 0) {
5145 		if ((lun->flags & CTL_LUN_PR_RESERVED) &&
5146 		    (cdb->how & SSS_START) == 0) {
5147 			uint32_t residx;
5148 
5149 			residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5150 			if (ctl_get_prkey(lun, residx) == 0 ||
5151 			    (lun->pr_res_idx != residx && lun->pr_res_type < 4)) {
5152 
5153 				ctl_set_reservation_conflict(ctsio);
5154 				ctl_done((union ctl_io *)ctsio);
5155 				return (CTL_RETVAL_COMPLETE);
5156 			}
5157 		}
5158 
5159 		if ((cdb->how & SSS_LOEJ) &&
5160 		    (lun->flags & CTL_LUN_REMOVABLE) == 0) {
5161 			ctl_set_invalid_field(ctsio,
5162 					      /*sks_valid*/ 1,
5163 					      /*command*/ 1,
5164 					      /*field*/ 4,
5165 					      /*bit_valid*/ 1,
5166 					      /*bit*/ 1);
5167 			ctl_done((union ctl_io *)ctsio);
5168 			return (CTL_RETVAL_COMPLETE);
5169 		}
5170 
5171 		if ((cdb->how & SSS_START) == 0 && (cdb->how & SSS_LOEJ) &&
5172 		    lun->prevent_count > 0) {
5173 			/* "Medium removal prevented" */
5174 			ctl_set_sense(ctsio, /*current_error*/ 1,
5175 			    /*sense_key*/(lun->flags & CTL_LUN_NO_MEDIA) ?
5176 			     SSD_KEY_NOT_READY : SSD_KEY_ILLEGAL_REQUEST,
5177 			    /*asc*/ 0x53, /*ascq*/ 0x02, SSD_ELEM_NONE);
5178 			ctl_done((union ctl_io *)ctsio);
5179 			return (CTL_RETVAL_COMPLETE);
5180 		}
5181 	}
5182 
5183 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5184 	return (retval);
5185 }
5186 
5187 int
5188 ctl_prevent_allow(struct ctl_scsiio *ctsio)
5189 {
5190 	struct ctl_lun *lun;
5191 	struct scsi_prevent *cdb;
5192 	int retval;
5193 	uint32_t initidx;
5194 
5195 	CTL_DEBUG_PRINT(("ctl_prevent_allow\n"));
5196 
5197 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5198 	cdb = (struct scsi_prevent *)ctsio->cdb;
5199 
5200 	if ((lun->flags & CTL_LUN_REMOVABLE) == 0) {
5201 		ctl_set_invalid_opcode(ctsio);
5202 		ctl_done((union ctl_io *)ctsio);
5203 		return (CTL_RETVAL_COMPLETE);
5204 	}
5205 
5206 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5207 	mtx_lock(&lun->lun_lock);
5208 	if ((cdb->how & PR_PREVENT) &&
5209 	    ctl_is_set(lun->prevent, initidx) == 0) {
5210 		ctl_set_mask(lun->prevent, initidx);
5211 		lun->prevent_count++;
5212 	} else if ((cdb->how & PR_PREVENT) == 0 &&
5213 	    ctl_is_set(lun->prevent, initidx)) {
5214 		ctl_clear_mask(lun->prevent, initidx);
5215 		lun->prevent_count--;
5216 	}
5217 	mtx_unlock(&lun->lun_lock);
5218 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5219 	return (retval);
5220 }
5221 
5222 /*
5223  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5224  * we don't really do anything with the LBA and length fields if the user
5225  * passes them in.  Instead we'll just flush out the cache for the entire
5226  * LUN.
5227  */
5228 int
5229 ctl_sync_cache(struct ctl_scsiio *ctsio)
5230 {
5231 	struct ctl_lun *lun;
5232 	struct ctl_softc *softc;
5233 	struct ctl_lba_len_flags *lbalen;
5234 	uint64_t starting_lba;
5235 	uint32_t block_count;
5236 	int retval;
5237 	uint8_t byte2;
5238 
5239 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5240 
5241 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5242 	softc = lun->ctl_softc;
5243 	retval = 0;
5244 
5245 	switch (ctsio->cdb[0]) {
5246 	case SYNCHRONIZE_CACHE: {
5247 		struct scsi_sync_cache *cdb;
5248 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5249 
5250 		starting_lba = scsi_4btoul(cdb->begin_lba);
5251 		block_count = scsi_2btoul(cdb->lb_count);
5252 		byte2 = cdb->byte2;
5253 		break;
5254 	}
5255 	case SYNCHRONIZE_CACHE_16: {
5256 		struct scsi_sync_cache_16 *cdb;
5257 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5258 
5259 		starting_lba = scsi_8btou64(cdb->begin_lba);
5260 		block_count = scsi_4btoul(cdb->lb_count);
5261 		byte2 = cdb->byte2;
5262 		break;
5263 	}
5264 	default:
5265 		ctl_set_invalid_opcode(ctsio);
5266 		ctl_done((union ctl_io *)ctsio);
5267 		goto bailout;
5268 		break; /* NOTREACHED */
5269 	}
5270 
5271 	/*
5272 	 * We check the LBA and length, but don't do anything with them.
5273 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5274 	 * get flushed.  This check will just help satisfy anyone who wants
5275 	 * to see an error for an out of range LBA.
5276 	 */
5277 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5278 		ctl_set_lba_out_of_range(ctsio);
5279 		ctl_done((union ctl_io *)ctsio);
5280 		goto bailout;
5281 	}
5282 
5283 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5284 	lbalen->lba = starting_lba;
5285 	lbalen->len = block_count;
5286 	lbalen->flags = byte2;
5287 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5288 
5289 bailout:
5290 	return (retval);
5291 }
5292 
5293 int
5294 ctl_format(struct ctl_scsiio *ctsio)
5295 {
5296 	struct scsi_format *cdb;
5297 	struct ctl_lun *lun;
5298 	int length, defect_list_len;
5299 
5300 	CTL_DEBUG_PRINT(("ctl_format\n"));
5301 
5302 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5303 
5304 	cdb = (struct scsi_format *)ctsio->cdb;
5305 
5306 	length = 0;
5307 	if (cdb->byte2 & SF_FMTDATA) {
5308 		if (cdb->byte2 & SF_LONGLIST)
5309 			length = sizeof(struct scsi_format_header_long);
5310 		else
5311 			length = sizeof(struct scsi_format_header_short);
5312 	}
5313 
5314 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5315 	 && (length > 0)) {
5316 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5317 		ctsio->kern_data_len = length;
5318 		ctsio->kern_total_len = length;
5319 		ctsio->kern_data_resid = 0;
5320 		ctsio->kern_rel_offset = 0;
5321 		ctsio->kern_sg_entries = 0;
5322 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5323 		ctsio->be_move_done = ctl_config_move_done;
5324 		ctl_datamove((union ctl_io *)ctsio);
5325 
5326 		return (CTL_RETVAL_COMPLETE);
5327 	}
5328 
5329 	defect_list_len = 0;
5330 
5331 	if (cdb->byte2 & SF_FMTDATA) {
5332 		if (cdb->byte2 & SF_LONGLIST) {
5333 			struct scsi_format_header_long *header;
5334 
5335 			header = (struct scsi_format_header_long *)
5336 				ctsio->kern_data_ptr;
5337 
5338 			defect_list_len = scsi_4btoul(header->defect_list_len);
5339 			if (defect_list_len != 0) {
5340 				ctl_set_invalid_field(ctsio,
5341 						      /*sks_valid*/ 1,
5342 						      /*command*/ 0,
5343 						      /*field*/ 2,
5344 						      /*bit_valid*/ 0,
5345 						      /*bit*/ 0);
5346 				goto bailout;
5347 			}
5348 		} else {
5349 			struct scsi_format_header_short *header;
5350 
5351 			header = (struct scsi_format_header_short *)
5352 				ctsio->kern_data_ptr;
5353 
5354 			defect_list_len = scsi_2btoul(header->defect_list_len);
5355 			if (defect_list_len != 0) {
5356 				ctl_set_invalid_field(ctsio,
5357 						      /*sks_valid*/ 1,
5358 						      /*command*/ 0,
5359 						      /*field*/ 2,
5360 						      /*bit_valid*/ 0,
5361 						      /*bit*/ 0);
5362 				goto bailout;
5363 			}
5364 		}
5365 	}
5366 
5367 	ctl_set_success(ctsio);
5368 bailout:
5369 
5370 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5371 		free(ctsio->kern_data_ptr, M_CTL);
5372 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5373 	}
5374 
5375 	ctl_done((union ctl_io *)ctsio);
5376 	return (CTL_RETVAL_COMPLETE);
5377 }
5378 
5379 int
5380 ctl_read_buffer(struct ctl_scsiio *ctsio)
5381 {
5382 	struct ctl_lun *lun;
5383 	uint64_t buffer_offset;
5384 	uint32_t len;
5385 	uint8_t byte2;
5386 	static uint8_t descr[4];
5387 	static uint8_t echo_descr[4] = { 0 };
5388 
5389 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5390 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5391 	switch (ctsio->cdb[0]) {
5392 	case READ_BUFFER: {
5393 		struct scsi_read_buffer *cdb;
5394 
5395 		cdb = (struct scsi_read_buffer *)ctsio->cdb;
5396 		buffer_offset = scsi_3btoul(cdb->offset);
5397 		len = scsi_3btoul(cdb->length);
5398 		byte2 = cdb->byte2;
5399 		break;
5400 	}
5401 	case READ_BUFFER_16: {
5402 		struct scsi_read_buffer_16 *cdb;
5403 
5404 		cdb = (struct scsi_read_buffer_16 *)ctsio->cdb;
5405 		buffer_offset = scsi_8btou64(cdb->offset);
5406 		len = scsi_4btoul(cdb->length);
5407 		byte2 = cdb->byte2;
5408 		break;
5409 	}
5410 	default: /* This shouldn't happen. */
5411 		ctl_set_invalid_opcode(ctsio);
5412 		ctl_done((union ctl_io *)ctsio);
5413 		return (CTL_RETVAL_COMPLETE);
5414 	}
5415 
5416 	if ((byte2 & RWB_MODE) != RWB_MODE_DATA &&
5417 	    (byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5418 	    (byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5419 		ctl_set_invalid_field(ctsio,
5420 				      /*sks_valid*/ 1,
5421 				      /*command*/ 1,
5422 				      /*field*/ 1,
5423 				      /*bit_valid*/ 1,
5424 				      /*bit*/ 4);
5425 		ctl_done((union ctl_io *)ctsio);
5426 		return (CTL_RETVAL_COMPLETE);
5427 	}
5428 
5429 	if (buffer_offset > CTL_WRITE_BUFFER_SIZE ||
5430 	    buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5431 		ctl_set_invalid_field(ctsio,
5432 				      /*sks_valid*/ 1,
5433 				      /*command*/ 1,
5434 				      /*field*/ 6,
5435 				      /*bit_valid*/ 0,
5436 				      /*bit*/ 0);
5437 		ctl_done((union ctl_io *)ctsio);
5438 		return (CTL_RETVAL_COMPLETE);
5439 	}
5440 
5441 	if ((byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5442 		descr[0] = 0;
5443 		scsi_ulto3b(CTL_WRITE_BUFFER_SIZE, &descr[1]);
5444 		ctsio->kern_data_ptr = descr;
5445 		len = min(len, sizeof(descr));
5446 	} else if ((byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5447 		ctsio->kern_data_ptr = echo_descr;
5448 		len = min(len, sizeof(echo_descr));
5449 	} else {
5450 		if (lun->write_buffer == NULL) {
5451 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5452 			    M_CTL, M_WAITOK);
5453 		}
5454 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5455 	}
5456 	ctsio->kern_data_len = len;
5457 	ctsio->kern_total_len = len;
5458 	ctsio->kern_data_resid = 0;
5459 	ctsio->kern_rel_offset = 0;
5460 	ctsio->kern_sg_entries = 0;
5461 	ctl_set_success(ctsio);
5462 	ctsio->be_move_done = ctl_config_move_done;
5463 	ctl_datamove((union ctl_io *)ctsio);
5464 	return (CTL_RETVAL_COMPLETE);
5465 }
5466 
5467 int
5468 ctl_write_buffer(struct ctl_scsiio *ctsio)
5469 {
5470 	struct scsi_write_buffer *cdb;
5471 	struct ctl_lun *lun;
5472 	int buffer_offset, len;
5473 
5474 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5475 
5476 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5477 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5478 
5479 	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5480 		ctl_set_invalid_field(ctsio,
5481 				      /*sks_valid*/ 1,
5482 				      /*command*/ 1,
5483 				      /*field*/ 1,
5484 				      /*bit_valid*/ 1,
5485 				      /*bit*/ 4);
5486 		ctl_done((union ctl_io *)ctsio);
5487 		return (CTL_RETVAL_COMPLETE);
5488 	}
5489 
5490 	len = scsi_3btoul(cdb->length);
5491 	buffer_offset = scsi_3btoul(cdb->offset);
5492 
5493 	if (buffer_offset + len > CTL_WRITE_BUFFER_SIZE) {
5494 		ctl_set_invalid_field(ctsio,
5495 				      /*sks_valid*/ 1,
5496 				      /*command*/ 1,
5497 				      /*field*/ 6,
5498 				      /*bit_valid*/ 0,
5499 				      /*bit*/ 0);
5500 		ctl_done((union ctl_io *)ctsio);
5501 		return (CTL_RETVAL_COMPLETE);
5502 	}
5503 
5504 	/*
5505 	 * If we've got a kernel request that hasn't been malloced yet,
5506 	 * malloc it and tell the caller the data buffer is here.
5507 	 */
5508 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5509 		if (lun->write_buffer == NULL) {
5510 			lun->write_buffer = malloc(CTL_WRITE_BUFFER_SIZE,
5511 			    M_CTL, M_WAITOK);
5512 		}
5513 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5514 		ctsio->kern_data_len = len;
5515 		ctsio->kern_total_len = len;
5516 		ctsio->kern_data_resid = 0;
5517 		ctsio->kern_rel_offset = 0;
5518 		ctsio->kern_sg_entries = 0;
5519 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5520 		ctsio->be_move_done = ctl_config_move_done;
5521 		ctl_datamove((union ctl_io *)ctsio);
5522 
5523 		return (CTL_RETVAL_COMPLETE);
5524 	}
5525 
5526 	ctl_set_success(ctsio);
5527 	ctl_done((union ctl_io *)ctsio);
5528 	return (CTL_RETVAL_COMPLETE);
5529 }
5530 
5531 int
5532 ctl_write_same(struct ctl_scsiio *ctsio)
5533 {
5534 	struct ctl_lun *lun;
5535 	struct ctl_lba_len_flags *lbalen;
5536 	uint64_t lba;
5537 	uint32_t num_blocks;
5538 	int len, retval;
5539 	uint8_t byte2;
5540 
5541 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5542 
5543 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5544 
5545 	switch (ctsio->cdb[0]) {
5546 	case WRITE_SAME_10: {
5547 		struct scsi_write_same_10 *cdb;
5548 
5549 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5550 
5551 		lba = scsi_4btoul(cdb->addr);
5552 		num_blocks = scsi_2btoul(cdb->length);
5553 		byte2 = cdb->byte2;
5554 		break;
5555 	}
5556 	case WRITE_SAME_16: {
5557 		struct scsi_write_same_16 *cdb;
5558 
5559 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5560 
5561 		lba = scsi_8btou64(cdb->addr);
5562 		num_blocks = scsi_4btoul(cdb->length);
5563 		byte2 = cdb->byte2;
5564 		break;
5565 	}
5566 	default:
5567 		/*
5568 		 * We got a command we don't support.  This shouldn't
5569 		 * happen, commands should be filtered out above us.
5570 		 */
5571 		ctl_set_invalid_opcode(ctsio);
5572 		ctl_done((union ctl_io *)ctsio);
5573 
5574 		return (CTL_RETVAL_COMPLETE);
5575 		break; /* NOTREACHED */
5576 	}
5577 
5578 	/* ANCHOR flag can be used only together with UNMAP */
5579 	if ((byte2 & SWS_UNMAP) == 0 && (byte2 & SWS_ANCHOR) != 0) {
5580 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5581 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5582 		ctl_done((union ctl_io *)ctsio);
5583 		return (CTL_RETVAL_COMPLETE);
5584 	}
5585 
5586 	/*
5587 	 * The first check is to make sure we're in bounds, the second
5588 	 * check is to catch wrap-around problems.  If the lba + num blocks
5589 	 * is less than the lba, then we've wrapped around and the block
5590 	 * range is invalid anyway.
5591 	 */
5592 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5593 	 || ((lba + num_blocks) < lba)) {
5594 		ctl_set_lba_out_of_range(ctsio);
5595 		ctl_done((union ctl_io *)ctsio);
5596 		return (CTL_RETVAL_COMPLETE);
5597 	}
5598 
5599 	/* Zero number of blocks means "to the last logical block" */
5600 	if (num_blocks == 0) {
5601 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
5602 			ctl_set_invalid_field(ctsio,
5603 					      /*sks_valid*/ 0,
5604 					      /*command*/ 1,
5605 					      /*field*/ 0,
5606 					      /*bit_valid*/ 0,
5607 					      /*bit*/ 0);
5608 			ctl_done((union ctl_io *)ctsio);
5609 			return (CTL_RETVAL_COMPLETE);
5610 		}
5611 		num_blocks = (lun->be_lun->maxlba + 1) - lba;
5612 	}
5613 
5614 	len = lun->be_lun->blocksize;
5615 
5616 	/*
5617 	 * If we've got a kernel request that hasn't been malloced yet,
5618 	 * malloc it and tell the caller the data buffer is here.
5619 	 */
5620 	if ((byte2 & SWS_NDOB) == 0 &&
5621 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5622 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5623 		ctsio->kern_data_len = len;
5624 		ctsio->kern_total_len = len;
5625 		ctsio->kern_data_resid = 0;
5626 		ctsio->kern_rel_offset = 0;
5627 		ctsio->kern_sg_entries = 0;
5628 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5629 		ctsio->be_move_done = ctl_config_move_done;
5630 		ctl_datamove((union ctl_io *)ctsio);
5631 
5632 		return (CTL_RETVAL_COMPLETE);
5633 	}
5634 
5635 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5636 	lbalen->lba = lba;
5637 	lbalen->len = num_blocks;
5638 	lbalen->flags = byte2;
5639 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5640 
5641 	return (retval);
5642 }
5643 
5644 int
5645 ctl_unmap(struct ctl_scsiio *ctsio)
5646 {
5647 	struct ctl_lun *lun;
5648 	struct scsi_unmap *cdb;
5649 	struct ctl_ptr_len_flags *ptrlen;
5650 	struct scsi_unmap_header *hdr;
5651 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
5652 	uint64_t lba;
5653 	uint32_t num_blocks;
5654 	int len, retval;
5655 	uint8_t byte2;
5656 
5657 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
5658 
5659 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5660 	cdb = (struct scsi_unmap *)ctsio->cdb;
5661 
5662 	len = scsi_2btoul(cdb->length);
5663 	byte2 = cdb->byte2;
5664 
5665 	/*
5666 	 * If we've got a kernel request that hasn't been malloced yet,
5667 	 * malloc it and tell the caller the data buffer is here.
5668 	 */
5669 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5670 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
5671 		ctsio->kern_data_len = len;
5672 		ctsio->kern_total_len = len;
5673 		ctsio->kern_data_resid = 0;
5674 		ctsio->kern_rel_offset = 0;
5675 		ctsio->kern_sg_entries = 0;
5676 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5677 		ctsio->be_move_done = ctl_config_move_done;
5678 		ctl_datamove((union ctl_io *)ctsio);
5679 
5680 		return (CTL_RETVAL_COMPLETE);
5681 	}
5682 
5683 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
5684 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
5685 	if (len < sizeof (*hdr) ||
5686 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
5687 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
5688 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
5689 		ctl_set_invalid_field(ctsio,
5690 				      /*sks_valid*/ 0,
5691 				      /*command*/ 0,
5692 				      /*field*/ 0,
5693 				      /*bit_valid*/ 0,
5694 				      /*bit*/ 0);
5695 		goto done;
5696 	}
5697 	len = scsi_2btoul(hdr->desc_length);
5698 	buf = (struct scsi_unmap_desc *)(hdr + 1);
5699 	end = buf + len / sizeof(*buf);
5700 
5701 	endnz = buf;
5702 	for (range = buf; range < end; range++) {
5703 		lba = scsi_8btou64(range->lba);
5704 		num_blocks = scsi_4btoul(range->length);
5705 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
5706 		 || ((lba + num_blocks) < lba)) {
5707 			ctl_set_lba_out_of_range(ctsio);
5708 			ctl_done((union ctl_io *)ctsio);
5709 			return (CTL_RETVAL_COMPLETE);
5710 		}
5711 		if (num_blocks != 0)
5712 			endnz = range + 1;
5713 	}
5714 
5715 	/*
5716 	 * Block backend can not handle zero last range.
5717 	 * Filter it out and return if there is nothing left.
5718 	 */
5719 	len = (uint8_t *)endnz - (uint8_t *)buf;
5720 	if (len == 0) {
5721 		ctl_set_success(ctsio);
5722 		goto done;
5723 	}
5724 
5725 	mtx_lock(&lun->lun_lock);
5726 	ptrlen = (struct ctl_ptr_len_flags *)
5727 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
5728 	ptrlen->ptr = (void *)buf;
5729 	ptrlen->len = len;
5730 	ptrlen->flags = byte2;
5731 	ctl_check_blocked(lun);
5732 	mtx_unlock(&lun->lun_lock);
5733 
5734 	retval = lun->backend->config_write((union ctl_io *)ctsio);
5735 	return (retval);
5736 
5737 done:
5738 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5739 		free(ctsio->kern_data_ptr, M_CTL);
5740 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5741 	}
5742 	ctl_done((union ctl_io *)ctsio);
5743 	return (CTL_RETVAL_COMPLETE);
5744 }
5745 
5746 /*
5747  * Note that this function currently doesn't actually do anything inside
5748  * CTL to enforce things if the DQue bit is turned on.
5749  *
5750  * Also note that this function can't be used in the default case, because
5751  * the DQue bit isn't set in the changeable mask for the control mode page
5752  * anyway.  This is just here as an example for how to implement a page
5753  * handler, and a placeholder in case we want to allow the user to turn
5754  * tagged queueing on and off.
5755  *
5756  * The D_SENSE bit handling is functional, however, and will turn
5757  * descriptor sense on and off for a given LUN.
5758  */
5759 int
5760 ctl_control_page_handler(struct ctl_scsiio *ctsio,
5761 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
5762 {
5763 	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
5764 	struct ctl_lun *lun;
5765 	int set_ua;
5766 	uint32_t initidx;
5767 
5768 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5769 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5770 	set_ua = 0;
5771 
5772 	user_cp = (struct scsi_control_page *)page_ptr;
5773 	current_cp = (struct scsi_control_page *)
5774 		(page_index->page_data + (page_index->page_len *
5775 		CTL_PAGE_CURRENT));
5776 	saved_cp = (struct scsi_control_page *)
5777 		(page_index->page_data + (page_index->page_len *
5778 		CTL_PAGE_SAVED));
5779 
5780 	mtx_lock(&lun->lun_lock);
5781 	if (((current_cp->rlec & SCP_DSENSE) == 0)
5782 	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
5783 		/*
5784 		 * Descriptor sense is currently turned off and the user
5785 		 * wants to turn it on.
5786 		 */
5787 		current_cp->rlec |= SCP_DSENSE;
5788 		saved_cp->rlec |= SCP_DSENSE;
5789 		lun->flags |= CTL_LUN_SENSE_DESC;
5790 		set_ua = 1;
5791 	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
5792 		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
5793 		/*
5794 		 * Descriptor sense is currently turned on, and the user
5795 		 * wants to turn it off.
5796 		 */
5797 		current_cp->rlec &= ~SCP_DSENSE;
5798 		saved_cp->rlec &= ~SCP_DSENSE;
5799 		lun->flags &= ~CTL_LUN_SENSE_DESC;
5800 		set_ua = 1;
5801 	}
5802 	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
5803 	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
5804 		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5805 		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5806 		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
5807 		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
5808 		set_ua = 1;
5809 	}
5810 	if ((current_cp->eca_and_aen & SCP_SWP) !=
5811 	    (user_cp->eca_and_aen & SCP_SWP)) {
5812 		current_cp->eca_and_aen &= ~SCP_SWP;
5813 		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5814 		saved_cp->eca_and_aen &= ~SCP_SWP;
5815 		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
5816 		set_ua = 1;
5817 	}
5818 	if (set_ua != 0)
5819 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5820 	mtx_unlock(&lun->lun_lock);
5821 	if (set_ua) {
5822 		ctl_isc_announce_mode(lun,
5823 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5824 		    page_index->page_code, page_index->subpage);
5825 	}
5826 	return (0);
5827 }
5828 
5829 int
5830 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
5831 		     struct ctl_page_index *page_index, uint8_t *page_ptr)
5832 {
5833 	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
5834 	struct ctl_lun *lun;
5835 	int set_ua;
5836 	uint32_t initidx;
5837 
5838 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5839 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
5840 	set_ua = 0;
5841 
5842 	user_cp = (struct scsi_caching_page *)page_ptr;
5843 	current_cp = (struct scsi_caching_page *)
5844 		(page_index->page_data + (page_index->page_len *
5845 		CTL_PAGE_CURRENT));
5846 	saved_cp = (struct scsi_caching_page *)
5847 		(page_index->page_data + (page_index->page_len *
5848 		CTL_PAGE_SAVED));
5849 
5850 	mtx_lock(&lun->lun_lock);
5851 	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
5852 	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
5853 		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5854 		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5855 		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
5856 		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
5857 		set_ua = 1;
5858 	}
5859 	if (set_ua != 0)
5860 		ctl_est_ua_all(lun, initidx, CTL_UA_MODE_CHANGE);
5861 	mtx_unlock(&lun->lun_lock);
5862 	if (set_ua) {
5863 		ctl_isc_announce_mode(lun,
5864 		    ctl_get_initindex(&ctsio->io_hdr.nexus),
5865 		    page_index->page_code, page_index->subpage);
5866 	}
5867 	return (0);
5868 }
5869 
5870 int
5871 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
5872 				struct ctl_page_index *page_index,
5873 				uint8_t *page_ptr)
5874 {
5875 	uint8_t *c;
5876 	int i;
5877 
5878 	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
5879 	ctl_time_io_secs =
5880 		(c[0] << 8) |
5881 		(c[1] << 0) |
5882 		0;
5883 	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
5884 	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
5885 	printf("page data:");
5886 	for (i=0; i<8; i++)
5887 		printf(" %.2x",page_ptr[i]);
5888 	printf("\n");
5889 	return (0);
5890 }
5891 
5892 int
5893 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
5894 			       struct ctl_page_index *page_index,
5895 			       int pc)
5896 {
5897 	struct copan_debugconf_subpage *page;
5898 
5899 	page = (struct copan_debugconf_subpage *)page_index->page_data +
5900 		(page_index->page_len * pc);
5901 
5902 	switch (pc) {
5903 	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
5904 	case SMS_PAGE_CTRL_DEFAULT >> 6:
5905 	case SMS_PAGE_CTRL_SAVED >> 6:
5906 		/*
5907 		 * We don't update the changable or default bits for this page.
5908 		 */
5909 		break;
5910 	case SMS_PAGE_CTRL_CURRENT >> 6:
5911 		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
5912 		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
5913 		break;
5914 	default:
5915 		break;
5916 	}
5917 	return (0);
5918 }
5919 
5920 
5921 static int
5922 ctl_do_mode_select(union ctl_io *io)
5923 {
5924 	struct scsi_mode_page_header *page_header;
5925 	struct ctl_page_index *page_index;
5926 	struct ctl_scsiio *ctsio;
5927 	int page_len, page_len_offset, page_len_size;
5928 	union ctl_modepage_info *modepage_info;
5929 	struct ctl_lun *lun;
5930 	int *len_left, *len_used;
5931 	int retval, i;
5932 
5933 	ctsio = &io->scsiio;
5934 	page_index = NULL;
5935 	page_len = 0;
5936 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5937 
5938 	modepage_info = (union ctl_modepage_info *)
5939 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
5940 	len_left = &modepage_info->header.len_left;
5941 	len_used = &modepage_info->header.len_used;
5942 
5943 do_next_page:
5944 
5945 	page_header = (struct scsi_mode_page_header *)
5946 		(ctsio->kern_data_ptr + *len_used);
5947 
5948 	if (*len_left == 0) {
5949 		free(ctsio->kern_data_ptr, M_CTL);
5950 		ctl_set_success(ctsio);
5951 		ctl_done((union ctl_io *)ctsio);
5952 		return (CTL_RETVAL_COMPLETE);
5953 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
5954 
5955 		free(ctsio->kern_data_ptr, M_CTL);
5956 		ctl_set_param_len_error(ctsio);
5957 		ctl_done((union ctl_io *)ctsio);
5958 		return (CTL_RETVAL_COMPLETE);
5959 
5960 	} else if ((page_header->page_code & SMPH_SPF)
5961 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
5962 
5963 		free(ctsio->kern_data_ptr, M_CTL);
5964 		ctl_set_param_len_error(ctsio);
5965 		ctl_done((union ctl_io *)ctsio);
5966 		return (CTL_RETVAL_COMPLETE);
5967 	}
5968 
5969 
5970 	/*
5971 	 * XXX KDM should we do something with the block descriptor?
5972 	 */
5973 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5974 		page_index = &lun->mode_pages.index[i];
5975 		if (lun->be_lun->lun_type == T_DIRECT &&
5976 		    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
5977 			continue;
5978 		if (lun->be_lun->lun_type == T_PROCESSOR &&
5979 		    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
5980 			continue;
5981 		if (lun->be_lun->lun_type == T_CDROM &&
5982 		    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
5983 			continue;
5984 
5985 		if ((page_index->page_code & SMPH_PC_MASK) !=
5986 		    (page_header->page_code & SMPH_PC_MASK))
5987 			continue;
5988 
5989 		/*
5990 		 * If neither page has a subpage code, then we've got a
5991 		 * match.
5992 		 */
5993 		if (((page_index->page_code & SMPH_SPF) == 0)
5994 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
5995 			page_len = page_header->page_length;
5996 			break;
5997 		}
5998 
5999 		/*
6000 		 * If both pages have subpages, then the subpage numbers
6001 		 * have to match.
6002 		 */
6003 		if ((page_index->page_code & SMPH_SPF)
6004 		  && (page_header->page_code & SMPH_SPF)) {
6005 			struct scsi_mode_page_header_sp *sph;
6006 
6007 			sph = (struct scsi_mode_page_header_sp *)page_header;
6008 			if (page_index->subpage == sph->subpage) {
6009 				page_len = scsi_2btoul(sph->page_length);
6010 				break;
6011 			}
6012 		}
6013 	}
6014 
6015 	/*
6016 	 * If we couldn't find the page, or if we don't have a mode select
6017 	 * handler for it, send back an error to the user.
6018 	 */
6019 	if ((i >= CTL_NUM_MODE_PAGES)
6020 	 || (page_index->select_handler == NULL)) {
6021 		ctl_set_invalid_field(ctsio,
6022 				      /*sks_valid*/ 1,
6023 				      /*command*/ 0,
6024 				      /*field*/ *len_used,
6025 				      /*bit_valid*/ 0,
6026 				      /*bit*/ 0);
6027 		free(ctsio->kern_data_ptr, M_CTL);
6028 		ctl_done((union ctl_io *)ctsio);
6029 		return (CTL_RETVAL_COMPLETE);
6030 	}
6031 
6032 	if (page_index->page_code & SMPH_SPF) {
6033 		page_len_offset = 2;
6034 		page_len_size = 2;
6035 	} else {
6036 		page_len_size = 1;
6037 		page_len_offset = 1;
6038 	}
6039 
6040 	/*
6041 	 * If the length the initiator gives us isn't the one we specify in
6042 	 * the mode page header, or if they didn't specify enough data in
6043 	 * the CDB to avoid truncating this page, kick out the request.
6044 	 */
6045 	if ((page_len != (page_index->page_len - page_len_offset -
6046 			  page_len_size))
6047 	 || (*len_left < page_index->page_len)) {
6048 
6049 
6050 		ctl_set_invalid_field(ctsio,
6051 				      /*sks_valid*/ 1,
6052 				      /*command*/ 0,
6053 				      /*field*/ *len_used + page_len_offset,
6054 				      /*bit_valid*/ 0,
6055 				      /*bit*/ 0);
6056 		free(ctsio->kern_data_ptr, M_CTL);
6057 		ctl_done((union ctl_io *)ctsio);
6058 		return (CTL_RETVAL_COMPLETE);
6059 	}
6060 
6061 	/*
6062 	 * Run through the mode page, checking to make sure that the bits
6063 	 * the user changed are actually legal for him to change.
6064 	 */
6065 	for (i = 0; i < page_index->page_len; i++) {
6066 		uint8_t *user_byte, *change_mask, *current_byte;
6067 		int bad_bit;
6068 		int j;
6069 
6070 		user_byte = (uint8_t *)page_header + i;
6071 		change_mask = page_index->page_data +
6072 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6073 		current_byte = page_index->page_data +
6074 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6075 
6076 		/*
6077 		 * Check to see whether the user set any bits in this byte
6078 		 * that he is not allowed to set.
6079 		 */
6080 		if ((*user_byte & ~(*change_mask)) ==
6081 		    (*current_byte & ~(*change_mask)))
6082 			continue;
6083 
6084 		/*
6085 		 * Go through bit by bit to determine which one is illegal.
6086 		 */
6087 		bad_bit = 0;
6088 		for (j = 7; j >= 0; j--) {
6089 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6090 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6091 				bad_bit = i;
6092 				break;
6093 			}
6094 		}
6095 		ctl_set_invalid_field(ctsio,
6096 				      /*sks_valid*/ 1,
6097 				      /*command*/ 0,
6098 				      /*field*/ *len_used + i,
6099 				      /*bit_valid*/ 1,
6100 				      /*bit*/ bad_bit);
6101 		free(ctsio->kern_data_ptr, M_CTL);
6102 		ctl_done((union ctl_io *)ctsio);
6103 		return (CTL_RETVAL_COMPLETE);
6104 	}
6105 
6106 	/*
6107 	 * Decrement these before we call the page handler, since we may
6108 	 * end up getting called back one way or another before the handler
6109 	 * returns to this context.
6110 	 */
6111 	*len_left -= page_index->page_len;
6112 	*len_used += page_index->page_len;
6113 
6114 	retval = page_index->select_handler(ctsio, page_index,
6115 					    (uint8_t *)page_header);
6116 
6117 	/*
6118 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6119 	 * wait until this queued command completes to finish processing
6120 	 * the mode page.  If it returns anything other than
6121 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6122 	 * already set the sense information, freed the data pointer, and
6123 	 * completed the io for us.
6124 	 */
6125 	if (retval != CTL_RETVAL_COMPLETE)
6126 		goto bailout_no_done;
6127 
6128 	/*
6129 	 * If the initiator sent us more than one page, parse the next one.
6130 	 */
6131 	if (*len_left > 0)
6132 		goto do_next_page;
6133 
6134 	ctl_set_success(ctsio);
6135 	free(ctsio->kern_data_ptr, M_CTL);
6136 	ctl_done((union ctl_io *)ctsio);
6137 
6138 bailout_no_done:
6139 
6140 	return (CTL_RETVAL_COMPLETE);
6141 
6142 }
6143 
6144 int
6145 ctl_mode_select(struct ctl_scsiio *ctsio)
6146 {
6147 	int param_len, pf, sp;
6148 	int header_size, bd_len;
6149 	union ctl_modepage_info *modepage_info;
6150 
6151 	switch (ctsio->cdb[0]) {
6152 	case MODE_SELECT_6: {
6153 		struct scsi_mode_select_6 *cdb;
6154 
6155 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6156 
6157 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6158 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6159 		param_len = cdb->length;
6160 		header_size = sizeof(struct scsi_mode_header_6);
6161 		break;
6162 	}
6163 	case MODE_SELECT_10: {
6164 		struct scsi_mode_select_10 *cdb;
6165 
6166 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6167 
6168 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6169 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6170 		param_len = scsi_2btoul(cdb->length);
6171 		header_size = sizeof(struct scsi_mode_header_10);
6172 		break;
6173 	}
6174 	default:
6175 		ctl_set_invalid_opcode(ctsio);
6176 		ctl_done((union ctl_io *)ctsio);
6177 		return (CTL_RETVAL_COMPLETE);
6178 	}
6179 
6180 	/*
6181 	 * From SPC-3:
6182 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6183 	 * shall be empty. This condition shall not be considered as an error."
6184 	 */
6185 	if (param_len == 0) {
6186 		ctl_set_success(ctsio);
6187 		ctl_done((union ctl_io *)ctsio);
6188 		return (CTL_RETVAL_COMPLETE);
6189 	}
6190 
6191 	/*
6192 	 * Since we'll hit this the first time through, prior to
6193 	 * allocation, we don't need to free a data buffer here.
6194 	 */
6195 	if (param_len < header_size) {
6196 		ctl_set_param_len_error(ctsio);
6197 		ctl_done((union ctl_io *)ctsio);
6198 		return (CTL_RETVAL_COMPLETE);
6199 	}
6200 
6201 	/*
6202 	 * Allocate the data buffer and grab the user's data.  In theory,
6203 	 * we shouldn't have to sanity check the parameter list length here
6204 	 * because the maximum size is 64K.  We should be able to malloc
6205 	 * that much without too many problems.
6206 	 */
6207 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6208 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6209 		ctsio->kern_data_len = param_len;
6210 		ctsio->kern_total_len = param_len;
6211 		ctsio->kern_data_resid = 0;
6212 		ctsio->kern_rel_offset = 0;
6213 		ctsio->kern_sg_entries = 0;
6214 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6215 		ctsio->be_move_done = ctl_config_move_done;
6216 		ctl_datamove((union ctl_io *)ctsio);
6217 
6218 		return (CTL_RETVAL_COMPLETE);
6219 	}
6220 
6221 	switch (ctsio->cdb[0]) {
6222 	case MODE_SELECT_6: {
6223 		struct scsi_mode_header_6 *mh6;
6224 
6225 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6226 		bd_len = mh6->blk_desc_len;
6227 		break;
6228 	}
6229 	case MODE_SELECT_10: {
6230 		struct scsi_mode_header_10 *mh10;
6231 
6232 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6233 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6234 		break;
6235 	}
6236 	default:
6237 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6238 	}
6239 
6240 	if (param_len < (header_size + bd_len)) {
6241 		free(ctsio->kern_data_ptr, M_CTL);
6242 		ctl_set_param_len_error(ctsio);
6243 		ctl_done((union ctl_io *)ctsio);
6244 		return (CTL_RETVAL_COMPLETE);
6245 	}
6246 
6247 	/*
6248 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6249 	 * ctl_config_write_done(), it'll get passed back to
6250 	 * ctl_do_mode_select() for further processing, or completion if
6251 	 * we're all done.
6252 	 */
6253 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6254 	ctsio->io_cont = ctl_do_mode_select;
6255 
6256 	modepage_info = (union ctl_modepage_info *)
6257 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6258 	memset(modepage_info, 0, sizeof(*modepage_info));
6259 	modepage_info->header.len_left = param_len - header_size - bd_len;
6260 	modepage_info->header.len_used = header_size + bd_len;
6261 
6262 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6263 }
6264 
6265 int
6266 ctl_mode_sense(struct ctl_scsiio *ctsio)
6267 {
6268 	struct ctl_lun *lun;
6269 	int pc, page_code, dbd, llba, subpage;
6270 	int alloc_len, page_len, header_len, total_len;
6271 	struct scsi_mode_block_descr *block_desc;
6272 	struct ctl_page_index *page_index;
6273 
6274 	dbd = 0;
6275 	llba = 0;
6276 	block_desc = NULL;
6277 
6278 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6279 
6280 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6281 	switch (ctsio->cdb[0]) {
6282 	case MODE_SENSE_6: {
6283 		struct scsi_mode_sense_6 *cdb;
6284 
6285 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6286 
6287 		header_len = sizeof(struct scsi_mode_hdr_6);
6288 		if (cdb->byte2 & SMS_DBD)
6289 			dbd = 1;
6290 		else
6291 			header_len += sizeof(struct scsi_mode_block_descr);
6292 
6293 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6294 		page_code = cdb->page & SMS_PAGE_CODE;
6295 		subpage = cdb->subpage;
6296 		alloc_len = cdb->length;
6297 		break;
6298 	}
6299 	case MODE_SENSE_10: {
6300 		struct scsi_mode_sense_10 *cdb;
6301 
6302 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6303 
6304 		header_len = sizeof(struct scsi_mode_hdr_10);
6305 
6306 		if (cdb->byte2 & SMS_DBD)
6307 			dbd = 1;
6308 		else
6309 			header_len += sizeof(struct scsi_mode_block_descr);
6310 		if (cdb->byte2 & SMS10_LLBAA)
6311 			llba = 1;
6312 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6313 		page_code = cdb->page & SMS_PAGE_CODE;
6314 		subpage = cdb->subpage;
6315 		alloc_len = scsi_2btoul(cdb->length);
6316 		break;
6317 	}
6318 	default:
6319 		ctl_set_invalid_opcode(ctsio);
6320 		ctl_done((union ctl_io *)ctsio);
6321 		return (CTL_RETVAL_COMPLETE);
6322 		break; /* NOTREACHED */
6323 	}
6324 
6325 	/*
6326 	 * We have to make a first pass through to calculate the size of
6327 	 * the pages that match the user's query.  Then we allocate enough
6328 	 * memory to hold it, and actually copy the data into the buffer.
6329 	 */
6330 	switch (page_code) {
6331 	case SMS_ALL_PAGES_PAGE: {
6332 		int i;
6333 
6334 		page_len = 0;
6335 
6336 		/*
6337 		 * At the moment, values other than 0 and 0xff here are
6338 		 * reserved according to SPC-3.
6339 		 */
6340 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6341 		 && (subpage != SMS_SUBPAGE_ALL)) {
6342 			ctl_set_invalid_field(ctsio,
6343 					      /*sks_valid*/ 1,
6344 					      /*command*/ 1,
6345 					      /*field*/ 3,
6346 					      /*bit_valid*/ 0,
6347 					      /*bit*/ 0);
6348 			ctl_done((union ctl_io *)ctsio);
6349 			return (CTL_RETVAL_COMPLETE);
6350 		}
6351 
6352 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6353 			page_index = &lun->mode_pages.index[i];
6354 
6355 			/* Make sure the page is supported for this dev type */
6356 			if (lun->be_lun->lun_type == T_DIRECT &&
6357 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6358 				continue;
6359 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6360 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6361 				continue;
6362 			if (lun->be_lun->lun_type == T_CDROM &&
6363 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6364 				continue;
6365 
6366 			/*
6367 			 * We don't use this subpage if the user didn't
6368 			 * request all subpages.
6369 			 */
6370 			if ((page_index->subpage != 0)
6371 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6372 				continue;
6373 
6374 #if 0
6375 			printf("found page %#x len %d\n",
6376 			       page_index->page_code & SMPH_PC_MASK,
6377 			       page_index->page_len);
6378 #endif
6379 			page_len += page_index->page_len;
6380 		}
6381 		break;
6382 	}
6383 	default: {
6384 		int i;
6385 
6386 		page_len = 0;
6387 
6388 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6389 			page_index = &lun->mode_pages.index[i];
6390 
6391 			/* Make sure the page is supported for this dev type */
6392 			if (lun->be_lun->lun_type == T_DIRECT &&
6393 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6394 				continue;
6395 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6396 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6397 				continue;
6398 			if (lun->be_lun->lun_type == T_CDROM &&
6399 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6400 				continue;
6401 
6402 			/* Look for the right page code */
6403 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6404 				continue;
6405 
6406 			/* Look for the right subpage or the subpage wildcard*/
6407 			if ((page_index->subpage != subpage)
6408 			 && (subpage != SMS_SUBPAGE_ALL))
6409 				continue;
6410 
6411 #if 0
6412 			printf("found page %#x len %d\n",
6413 			       page_index->page_code & SMPH_PC_MASK,
6414 			       page_index->page_len);
6415 #endif
6416 
6417 			page_len += page_index->page_len;
6418 		}
6419 
6420 		if (page_len == 0) {
6421 			ctl_set_invalid_field(ctsio,
6422 					      /*sks_valid*/ 1,
6423 					      /*command*/ 1,
6424 					      /*field*/ 2,
6425 					      /*bit_valid*/ 1,
6426 					      /*bit*/ 5);
6427 			ctl_done((union ctl_io *)ctsio);
6428 			return (CTL_RETVAL_COMPLETE);
6429 		}
6430 		break;
6431 	}
6432 	}
6433 
6434 	total_len = header_len + page_len;
6435 #if 0
6436 	printf("header_len = %d, page_len = %d, total_len = %d\n",
6437 	       header_len, page_len, total_len);
6438 #endif
6439 
6440 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6441 	ctsio->kern_sg_entries = 0;
6442 	ctsio->kern_data_resid = 0;
6443 	ctsio->kern_rel_offset = 0;
6444 	if (total_len < alloc_len) {
6445 		ctsio->residual = alloc_len - total_len;
6446 		ctsio->kern_data_len = total_len;
6447 		ctsio->kern_total_len = total_len;
6448 	} else {
6449 		ctsio->residual = 0;
6450 		ctsio->kern_data_len = alloc_len;
6451 		ctsio->kern_total_len = alloc_len;
6452 	}
6453 
6454 	switch (ctsio->cdb[0]) {
6455 	case MODE_SENSE_6: {
6456 		struct scsi_mode_hdr_6 *header;
6457 
6458 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
6459 
6460 		header->datalen = MIN(total_len - 1, 254);
6461 		if (lun->be_lun->lun_type == T_DIRECT) {
6462 			header->dev_specific = 0x10; /* DPOFUA */
6463 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6464 			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6465 			    .eca_and_aen & SCP_SWP) != 0)
6466 				    header->dev_specific |= 0x80; /* WP */
6467 		}
6468 		if (dbd)
6469 			header->block_descr_len = 0;
6470 		else
6471 			header->block_descr_len =
6472 				sizeof(struct scsi_mode_block_descr);
6473 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6474 		break;
6475 	}
6476 	case MODE_SENSE_10: {
6477 		struct scsi_mode_hdr_10 *header;
6478 		int datalen;
6479 
6480 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
6481 
6482 		datalen = MIN(total_len - 2, 65533);
6483 		scsi_ulto2b(datalen, header->datalen);
6484 		if (lun->be_lun->lun_type == T_DIRECT) {
6485 			header->dev_specific = 0x10; /* DPOFUA */
6486 			if ((lun->be_lun->flags & CTL_LUN_FLAG_READONLY) ||
6487 			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
6488 			    .eca_and_aen & SCP_SWP) != 0)
6489 				    header->dev_specific |= 0x80; /* WP */
6490 		}
6491 		if (dbd)
6492 			scsi_ulto2b(0, header->block_descr_len);
6493 		else
6494 			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
6495 				    header->block_descr_len);
6496 		block_desc = (struct scsi_mode_block_descr *)&header[1];
6497 		break;
6498 	}
6499 	default:
6500 		panic("%s: Invalid CDB type %#x", __func__, ctsio->cdb[0]);
6501 	}
6502 
6503 	/*
6504 	 * If we've got a disk, use its blocksize in the block
6505 	 * descriptor.  Otherwise, just set it to 0.
6506 	 */
6507 	if (dbd == 0) {
6508 		if (lun->be_lun->lun_type == T_DIRECT)
6509 			scsi_ulto3b(lun->be_lun->blocksize,
6510 				    block_desc->block_len);
6511 		else
6512 			scsi_ulto3b(0, block_desc->block_len);
6513 	}
6514 
6515 	switch (page_code) {
6516 	case SMS_ALL_PAGES_PAGE: {
6517 		int i, data_used;
6518 
6519 		data_used = header_len;
6520 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6521 			struct ctl_page_index *page_index;
6522 
6523 			page_index = &lun->mode_pages.index[i];
6524 			if (lun->be_lun->lun_type == T_DIRECT &&
6525 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6526 				continue;
6527 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6528 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6529 				continue;
6530 			if (lun->be_lun->lun_type == T_CDROM &&
6531 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6532 				continue;
6533 
6534 			/*
6535 			 * We don't use this subpage if the user didn't
6536 			 * request all subpages.  We already checked (above)
6537 			 * to make sure the user only specified a subpage
6538 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
6539 			 */
6540 			if ((page_index->subpage != 0)
6541 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6542 				continue;
6543 
6544 			/*
6545 			 * Call the handler, if it exists, to update the
6546 			 * page to the latest values.
6547 			 */
6548 			if (page_index->sense_handler != NULL)
6549 				page_index->sense_handler(ctsio, page_index,pc);
6550 
6551 			memcpy(ctsio->kern_data_ptr + data_used,
6552 			       page_index->page_data +
6553 			       (page_index->page_len * pc),
6554 			       page_index->page_len);
6555 			data_used += page_index->page_len;
6556 		}
6557 		break;
6558 	}
6559 	default: {
6560 		int i, data_used;
6561 
6562 		data_used = header_len;
6563 
6564 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6565 			struct ctl_page_index *page_index;
6566 
6567 			page_index = &lun->mode_pages.index[i];
6568 
6569 			/* Look for the right page code */
6570 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
6571 				continue;
6572 
6573 			/* Look for the right subpage or the subpage wildcard*/
6574 			if ((page_index->subpage != subpage)
6575 			 && (subpage != SMS_SUBPAGE_ALL))
6576 				continue;
6577 
6578 			/* Make sure the page is supported for this dev type */
6579 			if (lun->be_lun->lun_type == T_DIRECT &&
6580 			    (page_index->page_flags & CTL_PAGE_FLAG_DIRECT) == 0)
6581 				continue;
6582 			if (lun->be_lun->lun_type == T_PROCESSOR &&
6583 			    (page_index->page_flags & CTL_PAGE_FLAG_PROC) == 0)
6584 				continue;
6585 			if (lun->be_lun->lun_type == T_CDROM &&
6586 			    (page_index->page_flags & CTL_PAGE_FLAG_CDROM) == 0)
6587 				continue;
6588 
6589 			/*
6590 			 * Call the handler, if it exists, to update the
6591 			 * page to the latest values.
6592 			 */
6593 			if (page_index->sense_handler != NULL)
6594 				page_index->sense_handler(ctsio, page_index,pc);
6595 
6596 			memcpy(ctsio->kern_data_ptr + data_used,
6597 			       page_index->page_data +
6598 			       (page_index->page_len * pc),
6599 			       page_index->page_len);
6600 			data_used += page_index->page_len;
6601 		}
6602 		break;
6603 	}
6604 	}
6605 
6606 	ctl_set_success(ctsio);
6607 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6608 	ctsio->be_move_done = ctl_config_move_done;
6609 	ctl_datamove((union ctl_io *)ctsio);
6610 	return (CTL_RETVAL_COMPLETE);
6611 }
6612 
6613 int
6614 ctl_lbp_log_sense_handler(struct ctl_scsiio *ctsio,
6615 			       struct ctl_page_index *page_index,
6616 			       int pc)
6617 {
6618 	struct ctl_lun *lun;
6619 	struct scsi_log_param_header *phdr;
6620 	uint8_t *data;
6621 	uint64_t val;
6622 
6623 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6624 	data = page_index->page_data;
6625 
6626 	if (lun->backend->lun_attr != NULL &&
6627 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksavail"))
6628 	     != UINT64_MAX) {
6629 		phdr = (struct scsi_log_param_header *)data;
6630 		scsi_ulto2b(0x0001, phdr->param_code);
6631 		phdr->param_control = SLP_LBIN | SLP_LP;
6632 		phdr->param_len = 8;
6633 		data = (uint8_t *)(phdr + 1);
6634 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6635 		data[4] = 0x02; /* per-pool */
6636 		data += phdr->param_len;
6637 	}
6638 
6639 	if (lun->backend->lun_attr != NULL &&
6640 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "blocksused"))
6641 	     != UINT64_MAX) {
6642 		phdr = (struct scsi_log_param_header *)data;
6643 		scsi_ulto2b(0x0002, phdr->param_code);
6644 		phdr->param_control = SLP_LBIN | SLP_LP;
6645 		phdr->param_len = 8;
6646 		data = (uint8_t *)(phdr + 1);
6647 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6648 		data[4] = 0x01; /* per-LUN */
6649 		data += phdr->param_len;
6650 	}
6651 
6652 	if (lun->backend->lun_attr != NULL &&
6653 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksavail"))
6654 	     != UINT64_MAX) {
6655 		phdr = (struct scsi_log_param_header *)data;
6656 		scsi_ulto2b(0x00f1, phdr->param_code);
6657 		phdr->param_control = SLP_LBIN | SLP_LP;
6658 		phdr->param_len = 8;
6659 		data = (uint8_t *)(phdr + 1);
6660 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6661 		data[4] = 0x02; /* per-pool */
6662 		data += phdr->param_len;
6663 	}
6664 
6665 	if (lun->backend->lun_attr != NULL &&
6666 	    (val = lun->backend->lun_attr(lun->be_lun->be_lun, "poolblocksused"))
6667 	     != UINT64_MAX) {
6668 		phdr = (struct scsi_log_param_header *)data;
6669 		scsi_ulto2b(0x00f2, phdr->param_code);
6670 		phdr->param_control = SLP_LBIN | SLP_LP;
6671 		phdr->param_len = 8;
6672 		data = (uint8_t *)(phdr + 1);
6673 		scsi_ulto4b(val >> CTL_LBP_EXPONENT, data);
6674 		data[4] = 0x02; /* per-pool */
6675 		data += phdr->param_len;
6676 	}
6677 
6678 	page_index->page_len = data - page_index->page_data;
6679 	return (0);
6680 }
6681 
6682 int
6683 ctl_sap_log_sense_handler(struct ctl_scsiio *ctsio,
6684 			       struct ctl_page_index *page_index,
6685 			       int pc)
6686 {
6687 	struct ctl_lun *lun;
6688 	struct stat_page *data;
6689 	uint64_t rn, wn, rb, wb;
6690 	struct bintime rt, wt;
6691 	int i;
6692 
6693 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6694 	data = (struct stat_page *)page_index->page_data;
6695 
6696 	scsi_ulto2b(SLP_SAP, data->sap.hdr.param_code);
6697 	data->sap.hdr.param_control = SLP_LBIN;
6698 	data->sap.hdr.param_len = sizeof(struct scsi_log_stat_and_perf) -
6699 	    sizeof(struct scsi_log_param_header);
6700 	rn = wn = rb = wb = 0;
6701 	bintime_clear(&rt);
6702 	bintime_clear(&wt);
6703 	for (i = 0; i < CTL_MAX_PORTS; i++) {
6704 		rn += lun->stats.ports[i].operations[CTL_STATS_READ];
6705 		wn += lun->stats.ports[i].operations[CTL_STATS_WRITE];
6706 		rb += lun->stats.ports[i].bytes[CTL_STATS_READ];
6707 		wb += lun->stats.ports[i].bytes[CTL_STATS_WRITE];
6708 		bintime_add(&rt, &lun->stats.ports[i].time[CTL_STATS_READ]);
6709 		bintime_add(&wt, &lun->stats.ports[i].time[CTL_STATS_WRITE]);
6710 	}
6711 	scsi_u64to8b(rn, data->sap.read_num);
6712 	scsi_u64to8b(wn, data->sap.write_num);
6713 	if (lun->stats.blocksize > 0) {
6714 		scsi_u64to8b(wb / lun->stats.blocksize,
6715 		    data->sap.recvieved_lba);
6716 		scsi_u64to8b(rb / lun->stats.blocksize,
6717 		    data->sap.transmitted_lba);
6718 	}
6719 	scsi_u64to8b((uint64_t)rt.sec * 1000 + rt.frac / (UINT64_MAX / 1000),
6720 	    data->sap.read_int);
6721 	scsi_u64to8b((uint64_t)wt.sec * 1000 + wt.frac / (UINT64_MAX / 1000),
6722 	    data->sap.write_int);
6723 	scsi_u64to8b(0, data->sap.weighted_num);
6724 	scsi_u64to8b(0, data->sap.weighted_int);
6725 	scsi_ulto2b(SLP_IT, data->it.hdr.param_code);
6726 	data->it.hdr.param_control = SLP_LBIN;
6727 	data->it.hdr.param_len = sizeof(struct scsi_log_idle_time) -
6728 	    sizeof(struct scsi_log_param_header);
6729 #ifdef CTL_TIME_IO
6730 	scsi_u64to8b(lun->idle_time / SBT_1MS, data->it.idle_int);
6731 #endif
6732 	scsi_ulto2b(SLP_TI, data->ti.hdr.param_code);
6733 	data->it.hdr.param_control = SLP_LBIN;
6734 	data->ti.hdr.param_len = sizeof(struct scsi_log_time_interval) -
6735 	    sizeof(struct scsi_log_param_header);
6736 	scsi_ulto4b(3, data->ti.exponent);
6737 	scsi_ulto4b(1, data->ti.integer);
6738 
6739 	page_index->page_len = sizeof(*data);
6740 	return (0);
6741 }
6742 
6743 int
6744 ctl_log_sense(struct ctl_scsiio *ctsio)
6745 {
6746 	struct ctl_lun *lun;
6747 	int i, pc, page_code, subpage;
6748 	int alloc_len, total_len;
6749 	struct ctl_page_index *page_index;
6750 	struct scsi_log_sense *cdb;
6751 	struct scsi_log_header *header;
6752 
6753 	CTL_DEBUG_PRINT(("ctl_log_sense\n"));
6754 
6755 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6756 	cdb = (struct scsi_log_sense *)ctsio->cdb;
6757 	pc = (cdb->page & SLS_PAGE_CTRL_MASK) >> 6;
6758 	page_code = cdb->page & SLS_PAGE_CODE;
6759 	subpage = cdb->subpage;
6760 	alloc_len = scsi_2btoul(cdb->length);
6761 
6762 	page_index = NULL;
6763 	for (i = 0; i < CTL_NUM_LOG_PAGES; i++) {
6764 		page_index = &lun->log_pages.index[i];
6765 
6766 		/* Look for the right page code */
6767 		if ((page_index->page_code & SL_PAGE_CODE) != page_code)
6768 			continue;
6769 
6770 		/* Look for the right subpage or the subpage wildcard*/
6771 		if (page_index->subpage != subpage)
6772 			continue;
6773 
6774 		break;
6775 	}
6776 	if (i >= CTL_NUM_LOG_PAGES) {
6777 		ctl_set_invalid_field(ctsio,
6778 				      /*sks_valid*/ 1,
6779 				      /*command*/ 1,
6780 				      /*field*/ 2,
6781 				      /*bit_valid*/ 0,
6782 				      /*bit*/ 0);
6783 		ctl_done((union ctl_io *)ctsio);
6784 		return (CTL_RETVAL_COMPLETE);
6785 	}
6786 
6787 	total_len = sizeof(struct scsi_log_header) + page_index->page_len;
6788 
6789 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6790 	ctsio->kern_sg_entries = 0;
6791 	ctsio->kern_data_resid = 0;
6792 	ctsio->kern_rel_offset = 0;
6793 	if (total_len < alloc_len) {
6794 		ctsio->residual = alloc_len - total_len;
6795 		ctsio->kern_data_len = total_len;
6796 		ctsio->kern_total_len = total_len;
6797 	} else {
6798 		ctsio->residual = 0;
6799 		ctsio->kern_data_len = alloc_len;
6800 		ctsio->kern_total_len = alloc_len;
6801 	}
6802 
6803 	header = (struct scsi_log_header *)ctsio->kern_data_ptr;
6804 	header->page = page_index->page_code;
6805 	if (page_index->subpage) {
6806 		header->page |= SL_SPF;
6807 		header->subpage = page_index->subpage;
6808 	}
6809 	scsi_ulto2b(page_index->page_len, header->datalen);
6810 
6811 	/*
6812 	 * Call the handler, if it exists, to update the
6813 	 * page to the latest values.
6814 	 */
6815 	if (page_index->sense_handler != NULL)
6816 		page_index->sense_handler(ctsio, page_index, pc);
6817 
6818 	memcpy(header + 1, page_index->page_data, page_index->page_len);
6819 
6820 	ctl_set_success(ctsio);
6821 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6822 	ctsio->be_move_done = ctl_config_move_done;
6823 	ctl_datamove((union ctl_io *)ctsio);
6824 	return (CTL_RETVAL_COMPLETE);
6825 }
6826 
6827 int
6828 ctl_read_capacity(struct ctl_scsiio *ctsio)
6829 {
6830 	struct scsi_read_capacity *cdb;
6831 	struct scsi_read_capacity_data *data;
6832 	struct ctl_lun *lun;
6833 	uint32_t lba;
6834 
6835 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
6836 
6837 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
6838 
6839 	lba = scsi_4btoul(cdb->addr);
6840 	if (((cdb->pmi & SRC_PMI) == 0)
6841 	 && (lba != 0)) {
6842 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6843 				      /*sks_valid*/ 1,
6844 				      /*command*/ 1,
6845 				      /*field*/ 2,
6846 				      /*bit_valid*/ 0,
6847 				      /*bit*/ 0);
6848 		ctl_done((union ctl_io *)ctsio);
6849 		return (CTL_RETVAL_COMPLETE);
6850 	}
6851 
6852 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6853 
6854 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6855 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
6856 	ctsio->residual = 0;
6857 	ctsio->kern_data_len = sizeof(*data);
6858 	ctsio->kern_total_len = sizeof(*data);
6859 	ctsio->kern_data_resid = 0;
6860 	ctsio->kern_rel_offset = 0;
6861 	ctsio->kern_sg_entries = 0;
6862 
6863 	/*
6864 	 * If the maximum LBA is greater than 0xfffffffe, the user must
6865 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
6866 	 * serivce action set.
6867 	 */
6868 	if (lun->be_lun->maxlba > 0xfffffffe)
6869 		scsi_ulto4b(0xffffffff, data->addr);
6870 	else
6871 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
6872 
6873 	/*
6874 	 * XXX KDM this may not be 512 bytes...
6875 	 */
6876 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6877 
6878 	ctl_set_success(ctsio);
6879 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6880 	ctsio->be_move_done = ctl_config_move_done;
6881 	ctl_datamove((union ctl_io *)ctsio);
6882 	return (CTL_RETVAL_COMPLETE);
6883 }
6884 
6885 int
6886 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
6887 {
6888 	struct scsi_read_capacity_16 *cdb;
6889 	struct scsi_read_capacity_data_long *data;
6890 	struct ctl_lun *lun;
6891 	uint64_t lba;
6892 	uint32_t alloc_len;
6893 
6894 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
6895 
6896 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
6897 
6898 	alloc_len = scsi_4btoul(cdb->alloc_len);
6899 	lba = scsi_8btou64(cdb->addr);
6900 
6901 	if ((cdb->reladr & SRC16_PMI)
6902 	 && (lba != 0)) {
6903 		ctl_set_invalid_field(/*ctsio*/ ctsio,
6904 				      /*sks_valid*/ 1,
6905 				      /*command*/ 1,
6906 				      /*field*/ 2,
6907 				      /*bit_valid*/ 0,
6908 				      /*bit*/ 0);
6909 		ctl_done((union ctl_io *)ctsio);
6910 		return (CTL_RETVAL_COMPLETE);
6911 	}
6912 
6913 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6914 
6915 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
6916 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
6917 
6918 	if (sizeof(*data) < alloc_len) {
6919 		ctsio->residual = alloc_len - sizeof(*data);
6920 		ctsio->kern_data_len = sizeof(*data);
6921 		ctsio->kern_total_len = sizeof(*data);
6922 	} else {
6923 		ctsio->residual = 0;
6924 		ctsio->kern_data_len = alloc_len;
6925 		ctsio->kern_total_len = alloc_len;
6926 	}
6927 	ctsio->kern_data_resid = 0;
6928 	ctsio->kern_rel_offset = 0;
6929 	ctsio->kern_sg_entries = 0;
6930 
6931 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
6932 	/* XXX KDM this may not be 512 bytes... */
6933 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
6934 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
6935 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
6936 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
6937 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
6938 
6939 	ctl_set_success(ctsio);
6940 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6941 	ctsio->be_move_done = ctl_config_move_done;
6942 	ctl_datamove((union ctl_io *)ctsio);
6943 	return (CTL_RETVAL_COMPLETE);
6944 }
6945 
6946 int
6947 ctl_get_lba_status(struct ctl_scsiio *ctsio)
6948 {
6949 	struct scsi_get_lba_status *cdb;
6950 	struct scsi_get_lba_status_data *data;
6951 	struct ctl_lun *lun;
6952 	struct ctl_lba_len_flags *lbalen;
6953 	uint64_t lba;
6954 	uint32_t alloc_len, total_len;
6955 	int retval;
6956 
6957 	CTL_DEBUG_PRINT(("ctl_get_lba_status\n"));
6958 
6959 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6960 	cdb = (struct scsi_get_lba_status *)ctsio->cdb;
6961 	lba = scsi_8btou64(cdb->addr);
6962 	alloc_len = scsi_4btoul(cdb->alloc_len);
6963 
6964 	if (lba > lun->be_lun->maxlba) {
6965 		ctl_set_lba_out_of_range(ctsio);
6966 		ctl_done((union ctl_io *)ctsio);
6967 		return (CTL_RETVAL_COMPLETE);
6968 	}
6969 
6970 	total_len = sizeof(*data) + sizeof(data->descr[0]);
6971 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
6972 	data = (struct scsi_get_lba_status_data *)ctsio->kern_data_ptr;
6973 
6974 	if (total_len < alloc_len) {
6975 		ctsio->residual = alloc_len - total_len;
6976 		ctsio->kern_data_len = total_len;
6977 		ctsio->kern_total_len = total_len;
6978 	} else {
6979 		ctsio->residual = 0;
6980 		ctsio->kern_data_len = alloc_len;
6981 		ctsio->kern_total_len = alloc_len;
6982 	}
6983 	ctsio->kern_data_resid = 0;
6984 	ctsio->kern_rel_offset = 0;
6985 	ctsio->kern_sg_entries = 0;
6986 
6987 	/* Fill dummy data in case backend can't tell anything. */
6988 	scsi_ulto4b(4 + sizeof(data->descr[0]), data->length);
6989 	scsi_u64to8b(lba, data->descr[0].addr);
6990 	scsi_ulto4b(MIN(UINT32_MAX, lun->be_lun->maxlba + 1 - lba),
6991 	    data->descr[0].length);
6992 	data->descr[0].status = 0; /* Mapped or unknown. */
6993 
6994 	ctl_set_success(ctsio);
6995 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6996 	ctsio->be_move_done = ctl_config_move_done;
6997 
6998 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6999 	lbalen->lba = lba;
7000 	lbalen->len = total_len;
7001 	lbalen->flags = 0;
7002 	retval = lun->backend->config_read((union ctl_io *)ctsio);
7003 	return (CTL_RETVAL_COMPLETE);
7004 }
7005 
7006 int
7007 ctl_read_defect(struct ctl_scsiio *ctsio)
7008 {
7009 	struct scsi_read_defect_data_10 *ccb10;
7010 	struct scsi_read_defect_data_12 *ccb12;
7011 	struct scsi_read_defect_data_hdr_10 *data10;
7012 	struct scsi_read_defect_data_hdr_12 *data12;
7013 	uint32_t alloc_len, data_len;
7014 	uint8_t format;
7015 
7016 	CTL_DEBUG_PRINT(("ctl_read_defect\n"));
7017 
7018 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7019 		ccb10 = (struct scsi_read_defect_data_10 *)&ctsio->cdb;
7020 		format = ccb10->format;
7021 		alloc_len = scsi_2btoul(ccb10->alloc_length);
7022 		data_len = sizeof(*data10);
7023 	} else {
7024 		ccb12 = (struct scsi_read_defect_data_12 *)&ctsio->cdb;
7025 		format = ccb12->format;
7026 		alloc_len = scsi_4btoul(ccb12->alloc_length);
7027 		data_len = sizeof(*data12);
7028 	}
7029 	if (alloc_len == 0) {
7030 		ctl_set_success(ctsio);
7031 		ctl_done((union ctl_io *)ctsio);
7032 		return (CTL_RETVAL_COMPLETE);
7033 	}
7034 
7035 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
7036 	if (data_len < alloc_len) {
7037 		ctsio->residual = alloc_len - data_len;
7038 		ctsio->kern_data_len = data_len;
7039 		ctsio->kern_total_len = data_len;
7040 	} else {
7041 		ctsio->residual = 0;
7042 		ctsio->kern_data_len = alloc_len;
7043 		ctsio->kern_total_len = alloc_len;
7044 	}
7045 	ctsio->kern_data_resid = 0;
7046 	ctsio->kern_rel_offset = 0;
7047 	ctsio->kern_sg_entries = 0;
7048 
7049 	if (ctsio->cdb[0] == READ_DEFECT_DATA_10) {
7050 		data10 = (struct scsi_read_defect_data_hdr_10 *)
7051 		    ctsio->kern_data_ptr;
7052 		data10->format = format;
7053 		scsi_ulto2b(0, data10->length);
7054 	} else {
7055 		data12 = (struct scsi_read_defect_data_hdr_12 *)
7056 		    ctsio->kern_data_ptr;
7057 		data12->format = format;
7058 		scsi_ulto2b(0, data12->generation);
7059 		scsi_ulto4b(0, data12->length);
7060 	}
7061 
7062 	ctl_set_success(ctsio);
7063 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7064 	ctsio->be_move_done = ctl_config_move_done;
7065 	ctl_datamove((union ctl_io *)ctsio);
7066 	return (CTL_RETVAL_COMPLETE);
7067 }
7068 
7069 int
7070 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7071 {
7072 	struct scsi_maintenance_in *cdb;
7073 	int retval;
7074 	int alloc_len, ext, total_len = 0, g, pc, pg, gs, os;
7075 	int num_target_port_groups, num_target_ports;
7076 	struct ctl_lun *lun;
7077 	struct ctl_softc *softc;
7078 	struct ctl_port *port;
7079 	struct scsi_target_group_data *rtg_ptr;
7080 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7081 	struct scsi_target_port_group_descriptor *tpg_desc;
7082 
7083 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7084 
7085 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7086 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7087 	softc = lun->ctl_softc;
7088 
7089 	retval = CTL_RETVAL_COMPLETE;
7090 
7091 	switch (cdb->byte2 & STG_PDF_MASK) {
7092 	case STG_PDF_LENGTH:
7093 		ext = 0;
7094 		break;
7095 	case STG_PDF_EXTENDED:
7096 		ext = 1;
7097 		break;
7098 	default:
7099 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7100 				      /*sks_valid*/ 1,
7101 				      /*command*/ 1,
7102 				      /*field*/ 2,
7103 				      /*bit_valid*/ 1,
7104 				      /*bit*/ 5);
7105 		ctl_done((union ctl_io *)ctsio);
7106 		return(retval);
7107 	}
7108 
7109 	if (softc->is_single)
7110 		num_target_port_groups = 1;
7111 	else
7112 		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7113 	num_target_ports = 0;
7114 	mtx_lock(&softc->ctl_lock);
7115 	STAILQ_FOREACH(port, &softc->port_list, links) {
7116 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7117 			continue;
7118 		if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7119 			continue;
7120 		num_target_ports++;
7121 	}
7122 	mtx_unlock(&softc->ctl_lock);
7123 
7124 	if (ext)
7125 		total_len = sizeof(struct scsi_target_group_data_extended);
7126 	else
7127 		total_len = sizeof(struct scsi_target_group_data);
7128 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7129 		num_target_port_groups +
7130 	    sizeof(struct scsi_target_port_descriptor) * num_target_ports;
7131 
7132 	alloc_len = scsi_4btoul(cdb->length);
7133 
7134 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7135 
7136 	ctsio->kern_sg_entries = 0;
7137 
7138 	if (total_len < alloc_len) {
7139 		ctsio->residual = alloc_len - total_len;
7140 		ctsio->kern_data_len = total_len;
7141 		ctsio->kern_total_len = total_len;
7142 	} else {
7143 		ctsio->residual = 0;
7144 		ctsio->kern_data_len = alloc_len;
7145 		ctsio->kern_total_len = alloc_len;
7146 	}
7147 	ctsio->kern_data_resid = 0;
7148 	ctsio->kern_rel_offset = 0;
7149 
7150 	if (ext) {
7151 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7152 		    ctsio->kern_data_ptr;
7153 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7154 		rtg_ext_ptr->format_type = 0x10;
7155 		rtg_ext_ptr->implicit_transition_time = 0;
7156 		tpg_desc = &rtg_ext_ptr->groups[0];
7157 	} else {
7158 		rtg_ptr = (struct scsi_target_group_data *)
7159 		    ctsio->kern_data_ptr;
7160 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7161 		tpg_desc = &rtg_ptr->groups[0];
7162 	}
7163 
7164 	mtx_lock(&softc->ctl_lock);
7165 	pg = softc->port_min / softc->port_cnt;
7166 	if (softc->ha_link == CTL_HA_LINK_OFFLINE)
7167 		gs = TPG_ASYMMETRIC_ACCESS_UNAVAILABLE;
7168 	else if (softc->ha_link == CTL_HA_LINK_UNKNOWN)
7169 		gs = TPG_ASYMMETRIC_ACCESS_TRANSITIONING;
7170 	else if (softc->ha_mode == CTL_HA_MODE_ACT_STBY)
7171 		gs = TPG_ASYMMETRIC_ACCESS_STANDBY;
7172 	else
7173 		gs = TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7174 	if (lun->flags & CTL_LUN_PRIMARY_SC) {
7175 		os = gs;
7176 		gs = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7177 	} else
7178 		os = TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7179 	for (g = 0; g < num_target_port_groups; g++) {
7180 		tpg_desc->pref_state = (g == pg) ? gs : os;
7181 		tpg_desc->support = TPG_AO_SUP | TPG_AN_SUP | TPG_S_SUP |
7182 		    TPG_U_SUP | TPG_T_SUP;
7183 		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7184 		tpg_desc->status = TPG_IMPLICIT;
7185 		pc = 0;
7186 		STAILQ_FOREACH(port, &softc->port_list, links) {
7187 			if (port->targ_port < g * softc->port_cnt ||
7188 			    port->targ_port >= (g + 1) * softc->port_cnt)
7189 				continue;
7190 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7191 				continue;
7192 			if (ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
7193 				continue;
7194 			scsi_ulto2b(port->targ_port, tpg_desc->descriptors[pc].
7195 			    relative_target_port_identifier);
7196 			pc++;
7197 		}
7198 		tpg_desc->target_port_count = pc;
7199 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7200 		    &tpg_desc->descriptors[pc];
7201 	}
7202 	mtx_unlock(&softc->ctl_lock);
7203 
7204 	ctl_set_success(ctsio);
7205 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7206 	ctsio->be_move_done = ctl_config_move_done;
7207 	ctl_datamove((union ctl_io *)ctsio);
7208 	return(retval);
7209 }
7210 
7211 int
7212 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7213 {
7214 	struct ctl_lun *lun;
7215 	struct scsi_report_supported_opcodes *cdb;
7216 	const struct ctl_cmd_entry *entry, *sentry;
7217 	struct scsi_report_supported_opcodes_all *all;
7218 	struct scsi_report_supported_opcodes_descr *descr;
7219 	struct scsi_report_supported_opcodes_one *one;
7220 	int retval;
7221 	int alloc_len, total_len;
7222 	int opcode, service_action, i, j, num;
7223 
7224 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7225 
7226 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7227 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7228 
7229 	retval = CTL_RETVAL_COMPLETE;
7230 
7231 	opcode = cdb->requested_opcode;
7232 	service_action = scsi_2btoul(cdb->requested_service_action);
7233 	switch (cdb->options & RSO_OPTIONS_MASK) {
7234 	case RSO_OPTIONS_ALL:
7235 		num = 0;
7236 		for (i = 0; i < 256; i++) {
7237 			entry = &ctl_cmd_table[i];
7238 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7239 				for (j = 0; j < 32; j++) {
7240 					sentry = &((const struct ctl_cmd_entry *)
7241 					    entry->execute)[j];
7242 					if (ctl_cmd_applicable(
7243 					    lun->be_lun->lun_type, sentry))
7244 						num++;
7245 				}
7246 			} else {
7247 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7248 				    entry))
7249 					num++;
7250 			}
7251 		}
7252 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7253 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7254 		break;
7255 	case RSO_OPTIONS_OC:
7256 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7257 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7258 					      /*sks_valid*/ 1,
7259 					      /*command*/ 1,
7260 					      /*field*/ 2,
7261 					      /*bit_valid*/ 1,
7262 					      /*bit*/ 2);
7263 			ctl_done((union ctl_io *)ctsio);
7264 			return (CTL_RETVAL_COMPLETE);
7265 		}
7266 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7267 		break;
7268 	case RSO_OPTIONS_OC_SA:
7269 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7270 		    service_action >= 32) {
7271 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7272 					      /*sks_valid*/ 1,
7273 					      /*command*/ 1,
7274 					      /*field*/ 2,
7275 					      /*bit_valid*/ 1,
7276 					      /*bit*/ 2);
7277 			ctl_done((union ctl_io *)ctsio);
7278 			return (CTL_RETVAL_COMPLETE);
7279 		}
7280 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7281 		break;
7282 	default:
7283 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7284 				      /*sks_valid*/ 1,
7285 				      /*command*/ 1,
7286 				      /*field*/ 2,
7287 				      /*bit_valid*/ 1,
7288 				      /*bit*/ 2);
7289 		ctl_done((union ctl_io *)ctsio);
7290 		return (CTL_RETVAL_COMPLETE);
7291 	}
7292 
7293 	alloc_len = scsi_4btoul(cdb->length);
7294 
7295 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7296 
7297 	ctsio->kern_sg_entries = 0;
7298 
7299 	if (total_len < alloc_len) {
7300 		ctsio->residual = alloc_len - total_len;
7301 		ctsio->kern_data_len = total_len;
7302 		ctsio->kern_total_len = total_len;
7303 	} else {
7304 		ctsio->residual = 0;
7305 		ctsio->kern_data_len = alloc_len;
7306 		ctsio->kern_total_len = alloc_len;
7307 	}
7308 	ctsio->kern_data_resid = 0;
7309 	ctsio->kern_rel_offset = 0;
7310 
7311 	switch (cdb->options & RSO_OPTIONS_MASK) {
7312 	case RSO_OPTIONS_ALL:
7313 		all = (struct scsi_report_supported_opcodes_all *)
7314 		    ctsio->kern_data_ptr;
7315 		num = 0;
7316 		for (i = 0; i < 256; i++) {
7317 			entry = &ctl_cmd_table[i];
7318 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7319 				for (j = 0; j < 32; j++) {
7320 					sentry = &((const struct ctl_cmd_entry *)
7321 					    entry->execute)[j];
7322 					if (!ctl_cmd_applicable(
7323 					    lun->be_lun->lun_type, sentry))
7324 						continue;
7325 					descr = &all->descr[num++];
7326 					descr->opcode = i;
7327 					scsi_ulto2b(j, descr->service_action);
7328 					descr->flags = RSO_SERVACTV;
7329 					scsi_ulto2b(sentry->length,
7330 					    descr->cdb_length);
7331 				}
7332 			} else {
7333 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7334 				    entry))
7335 					continue;
7336 				descr = &all->descr[num++];
7337 				descr->opcode = i;
7338 				scsi_ulto2b(0, descr->service_action);
7339 				descr->flags = 0;
7340 				scsi_ulto2b(entry->length, descr->cdb_length);
7341 			}
7342 		}
7343 		scsi_ulto4b(
7344 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7345 		    all->length);
7346 		break;
7347 	case RSO_OPTIONS_OC:
7348 		one = (struct scsi_report_supported_opcodes_one *)
7349 		    ctsio->kern_data_ptr;
7350 		entry = &ctl_cmd_table[opcode];
7351 		goto fill_one;
7352 	case RSO_OPTIONS_OC_SA:
7353 		one = (struct scsi_report_supported_opcodes_one *)
7354 		    ctsio->kern_data_ptr;
7355 		entry = &ctl_cmd_table[opcode];
7356 		entry = &((const struct ctl_cmd_entry *)
7357 		    entry->execute)[service_action];
7358 fill_one:
7359 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7360 			one->support = 3;
7361 			scsi_ulto2b(entry->length, one->cdb_length);
7362 			one->cdb_usage[0] = opcode;
7363 			memcpy(&one->cdb_usage[1], entry->usage,
7364 			    entry->length - 1);
7365 		} else
7366 			one->support = 1;
7367 		break;
7368 	}
7369 
7370 	ctl_set_success(ctsio);
7371 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7372 	ctsio->be_move_done = ctl_config_move_done;
7373 	ctl_datamove((union ctl_io *)ctsio);
7374 	return(retval);
7375 }
7376 
7377 int
7378 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7379 {
7380 	struct scsi_report_supported_tmf *cdb;
7381 	struct scsi_report_supported_tmf_data *data;
7382 	int retval;
7383 	int alloc_len, total_len;
7384 
7385 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7386 
7387 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7388 
7389 	retval = CTL_RETVAL_COMPLETE;
7390 
7391 	total_len = sizeof(struct scsi_report_supported_tmf_data);
7392 	alloc_len = scsi_4btoul(cdb->length);
7393 
7394 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7395 
7396 	ctsio->kern_sg_entries = 0;
7397 
7398 	if (total_len < alloc_len) {
7399 		ctsio->residual = alloc_len - total_len;
7400 		ctsio->kern_data_len = total_len;
7401 		ctsio->kern_total_len = total_len;
7402 	} else {
7403 		ctsio->residual = 0;
7404 		ctsio->kern_data_len = alloc_len;
7405 		ctsio->kern_total_len = alloc_len;
7406 	}
7407 	ctsio->kern_data_resid = 0;
7408 	ctsio->kern_rel_offset = 0;
7409 
7410 	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7411 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_QTS |
7412 	    RST_TRS;
7413 	data->byte2 |= RST_QAES | RST_QTSS | RST_ITNRS;
7414 
7415 	ctl_set_success(ctsio);
7416 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7417 	ctsio->be_move_done = ctl_config_move_done;
7418 	ctl_datamove((union ctl_io *)ctsio);
7419 	return (retval);
7420 }
7421 
7422 int
7423 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7424 {
7425 	struct scsi_report_timestamp *cdb;
7426 	struct scsi_report_timestamp_data *data;
7427 	struct timeval tv;
7428 	int64_t timestamp;
7429 	int retval;
7430 	int alloc_len, total_len;
7431 
7432 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7433 
7434 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7435 
7436 	retval = CTL_RETVAL_COMPLETE;
7437 
7438 	total_len = sizeof(struct scsi_report_timestamp_data);
7439 	alloc_len = scsi_4btoul(cdb->length);
7440 
7441 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7442 
7443 	ctsio->kern_sg_entries = 0;
7444 
7445 	if (total_len < alloc_len) {
7446 		ctsio->residual = alloc_len - total_len;
7447 		ctsio->kern_data_len = total_len;
7448 		ctsio->kern_total_len = total_len;
7449 	} else {
7450 		ctsio->residual = 0;
7451 		ctsio->kern_data_len = alloc_len;
7452 		ctsio->kern_total_len = alloc_len;
7453 	}
7454 	ctsio->kern_data_resid = 0;
7455 	ctsio->kern_rel_offset = 0;
7456 
7457 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7458 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7459 	data->origin = RTS_ORIG_OUTSIDE;
7460 	getmicrotime(&tv);
7461 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7462 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7463 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7464 
7465 	ctl_set_success(ctsio);
7466 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7467 	ctsio->be_move_done = ctl_config_move_done;
7468 	ctl_datamove((union ctl_io *)ctsio);
7469 	return (retval);
7470 }
7471 
7472 int
7473 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7474 {
7475 	struct scsi_per_res_in *cdb;
7476 	int alloc_len, total_len = 0;
7477 	/* struct scsi_per_res_in_rsrv in_data; */
7478 	struct ctl_lun *lun;
7479 	struct ctl_softc *softc;
7480 	uint64_t key;
7481 
7482 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7483 
7484 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7485 
7486 	alloc_len = scsi_2btoul(cdb->length);
7487 
7488 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7489 	softc = lun->ctl_softc;
7490 
7491 retry:
7492 	mtx_lock(&lun->lun_lock);
7493 	switch (cdb->action) {
7494 	case SPRI_RK: /* read keys */
7495 		total_len = sizeof(struct scsi_per_res_in_keys) +
7496 			lun->pr_key_count *
7497 			sizeof(struct scsi_per_res_key);
7498 		break;
7499 	case SPRI_RR: /* read reservation */
7500 		if (lun->flags & CTL_LUN_PR_RESERVED)
7501 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7502 		else
7503 			total_len = sizeof(struct scsi_per_res_in_header);
7504 		break;
7505 	case SPRI_RC: /* report capabilities */
7506 		total_len = sizeof(struct scsi_per_res_cap);
7507 		break;
7508 	case SPRI_RS: /* read full status */
7509 		total_len = sizeof(struct scsi_per_res_in_header) +
7510 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7511 		    lun->pr_key_count;
7512 		break;
7513 	default:
7514 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7515 	}
7516 	mtx_unlock(&lun->lun_lock);
7517 
7518 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7519 
7520 	if (total_len < alloc_len) {
7521 		ctsio->residual = alloc_len - total_len;
7522 		ctsio->kern_data_len = total_len;
7523 		ctsio->kern_total_len = total_len;
7524 	} else {
7525 		ctsio->residual = 0;
7526 		ctsio->kern_data_len = alloc_len;
7527 		ctsio->kern_total_len = alloc_len;
7528 	}
7529 
7530 	ctsio->kern_data_resid = 0;
7531 	ctsio->kern_rel_offset = 0;
7532 	ctsio->kern_sg_entries = 0;
7533 
7534 	mtx_lock(&lun->lun_lock);
7535 	switch (cdb->action) {
7536 	case SPRI_RK: { // read keys
7537         struct scsi_per_res_in_keys *res_keys;
7538 		int i, key_count;
7539 
7540 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7541 
7542 		/*
7543 		 * We had to drop the lock to allocate our buffer, which
7544 		 * leaves time for someone to come in with another
7545 		 * persistent reservation.  (That is unlikely, though,
7546 		 * since this should be the only persistent reservation
7547 		 * command active right now.)
7548 		 */
7549 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7550 		    (lun->pr_key_count *
7551 		     sizeof(struct scsi_per_res_key)))){
7552 			mtx_unlock(&lun->lun_lock);
7553 			free(ctsio->kern_data_ptr, M_CTL);
7554 			printf("%s: reservation length changed, retrying\n",
7555 			       __func__);
7556 			goto retry;
7557 		}
7558 
7559 		scsi_ulto4b(lun->pr_generation, res_keys->header.generation);
7560 
7561 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7562 			     lun->pr_key_count, res_keys->header.length);
7563 
7564 		for (i = 0, key_count = 0; i < CTL_MAX_INITIATORS; i++) {
7565 			if ((key = ctl_get_prkey(lun, i)) == 0)
7566 				continue;
7567 
7568 			/*
7569 			 * We used lun->pr_key_count to calculate the
7570 			 * size to allocate.  If it turns out the number of
7571 			 * initiators with the registered flag set is
7572 			 * larger than that (i.e. they haven't been kept in
7573 			 * sync), we've got a problem.
7574 			 */
7575 			if (key_count >= lun->pr_key_count) {
7576 				key_count++;
7577 				continue;
7578 			}
7579 			scsi_u64to8b(key, res_keys->keys[key_count].key);
7580 			key_count++;
7581 		}
7582 		break;
7583 	}
7584 	case SPRI_RR: { // read reservation
7585 		struct scsi_per_res_in_rsrv *res;
7586 		int tmp_len, header_only;
7587 
7588 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7589 
7590 		scsi_ulto4b(lun->pr_generation, res->header.generation);
7591 
7592 		if (lun->flags & CTL_LUN_PR_RESERVED)
7593 		{
7594 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7595 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7596 				    res->header.length);
7597 			header_only = 0;
7598 		} else {
7599 			tmp_len = sizeof(struct scsi_per_res_in_header);
7600 			scsi_ulto4b(0, res->header.length);
7601 			header_only = 1;
7602 		}
7603 
7604 		/*
7605 		 * We had to drop the lock to allocate our buffer, which
7606 		 * leaves time for someone to come in with another
7607 		 * persistent reservation.  (That is unlikely, though,
7608 		 * since this should be the only persistent reservation
7609 		 * command active right now.)
7610 		 */
7611 		if (tmp_len != total_len) {
7612 			mtx_unlock(&lun->lun_lock);
7613 			free(ctsio->kern_data_ptr, M_CTL);
7614 			printf("%s: reservation status changed, retrying\n",
7615 			       __func__);
7616 			goto retry;
7617 		}
7618 
7619 		/*
7620 		 * No reservation held, so we're done.
7621 		 */
7622 		if (header_only != 0)
7623 			break;
7624 
7625 		/*
7626 		 * If the registration is an All Registrants type, the key
7627 		 * is 0, since it doesn't really matter.
7628 		 */
7629 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7630 			scsi_u64to8b(ctl_get_prkey(lun, lun->pr_res_idx),
7631 			    res->data.reservation);
7632 		}
7633 		res->data.scopetype = lun->pr_res_type;
7634 		break;
7635 	}
7636 	case SPRI_RC:     //report capabilities
7637 	{
7638 		struct scsi_per_res_cap *res_cap;
7639 		uint16_t type_mask;
7640 
7641 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7642 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7643 		res_cap->flags1 = SPRI_CRH;
7644 		res_cap->flags2 = SPRI_TMV | SPRI_ALLOW_5;
7645 		type_mask = SPRI_TM_WR_EX_AR |
7646 			    SPRI_TM_EX_AC_RO |
7647 			    SPRI_TM_WR_EX_RO |
7648 			    SPRI_TM_EX_AC |
7649 			    SPRI_TM_WR_EX |
7650 			    SPRI_TM_EX_AC_AR;
7651 		scsi_ulto2b(type_mask, res_cap->type_mask);
7652 		break;
7653 	}
7654 	case SPRI_RS: { // read full status
7655 		struct scsi_per_res_in_full *res_status;
7656 		struct scsi_per_res_in_full_desc *res_desc;
7657 		struct ctl_port *port;
7658 		int i, len;
7659 
7660 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7661 
7662 		/*
7663 		 * We had to drop the lock to allocate our buffer, which
7664 		 * leaves time for someone to come in with another
7665 		 * persistent reservation.  (That is unlikely, though,
7666 		 * since this should be the only persistent reservation
7667 		 * command active right now.)
7668 		 */
7669 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7670 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7671 		     lun->pr_key_count)){
7672 			mtx_unlock(&lun->lun_lock);
7673 			free(ctsio->kern_data_ptr, M_CTL);
7674 			printf("%s: reservation length changed, retrying\n",
7675 			       __func__);
7676 			goto retry;
7677 		}
7678 
7679 		scsi_ulto4b(lun->pr_generation, res_status->header.generation);
7680 
7681 		res_desc = &res_status->desc[0];
7682 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7683 			if ((key = ctl_get_prkey(lun, i)) == 0)
7684 				continue;
7685 
7686 			scsi_u64to8b(key, res_desc->res_key.key);
7687 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7688 			    (lun->pr_res_idx == i ||
7689 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7690 				res_desc->flags = SPRI_FULL_R_HOLDER;
7691 				res_desc->scopetype = lun->pr_res_type;
7692 			}
7693 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7694 			    res_desc->rel_trgt_port_id);
7695 			len = 0;
7696 			port = softc->ctl_ports[i / CTL_MAX_INIT_PER_PORT];
7697 			if (port != NULL)
7698 				len = ctl_create_iid(port,
7699 				    i % CTL_MAX_INIT_PER_PORT,
7700 				    res_desc->transport_id);
7701 			scsi_ulto4b(len, res_desc->additional_length);
7702 			res_desc = (struct scsi_per_res_in_full_desc *)
7703 			    &res_desc->transport_id[len];
7704 		}
7705 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7706 		    res_status->header.length);
7707 		break;
7708 	}
7709 	default:
7710 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
7711 	}
7712 	mtx_unlock(&lun->lun_lock);
7713 
7714 	ctl_set_success(ctsio);
7715 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7716 	ctsio->be_move_done = ctl_config_move_done;
7717 	ctl_datamove((union ctl_io *)ctsio);
7718 	return (CTL_RETVAL_COMPLETE);
7719 }
7720 
7721 /*
7722  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
7723  * it should return.
7724  */
7725 static int
7726 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
7727 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
7728 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
7729 		struct scsi_per_res_out_parms* param)
7730 {
7731 	union ctl_ha_msg persis_io;
7732 	int i;
7733 
7734 	mtx_lock(&lun->lun_lock);
7735 	if (sa_res_key == 0) {
7736 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
7737 			/* validate scope and type */
7738 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7739 			     SPR_LU_SCOPE) {
7740 				mtx_unlock(&lun->lun_lock);
7741 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7742 						      /*sks_valid*/ 1,
7743 						      /*command*/ 1,
7744 						      /*field*/ 2,
7745 						      /*bit_valid*/ 1,
7746 						      /*bit*/ 4);
7747 				ctl_done((union ctl_io *)ctsio);
7748 				return (1);
7749 			}
7750 
7751 		        if (type>8 || type==2 || type==4 || type==0) {
7752 				mtx_unlock(&lun->lun_lock);
7753 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7754        	           				      /*sks_valid*/ 1,
7755 						      /*command*/ 1,
7756 						      /*field*/ 2,
7757 						      /*bit_valid*/ 1,
7758 						      /*bit*/ 0);
7759 				ctl_done((union ctl_io *)ctsio);
7760 				return (1);
7761 		        }
7762 
7763 			/*
7764 			 * Unregister everybody else and build UA for
7765 			 * them
7766 			 */
7767 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7768 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7769 					continue;
7770 
7771 				ctl_clr_prkey(lun, i);
7772 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7773 			}
7774 			lun->pr_key_count = 1;
7775 			lun->pr_res_type = type;
7776 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7777 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7778 				lun->pr_res_idx = residx;
7779 			lun->pr_generation++;
7780 			mtx_unlock(&lun->lun_lock);
7781 
7782 			/* send msg to other side */
7783 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7784 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7785 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7786 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7787 			persis_io.pr.pr_info.res_type = type;
7788 			memcpy(persis_io.pr.pr_info.sa_res_key,
7789 			       param->serv_act_res_key,
7790 			       sizeof(param->serv_act_res_key));
7791 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7792 			    sizeof(persis_io.pr), M_WAITOK);
7793 		} else {
7794 			/* not all registrants */
7795 			mtx_unlock(&lun->lun_lock);
7796 			free(ctsio->kern_data_ptr, M_CTL);
7797 			ctl_set_invalid_field(ctsio,
7798 					      /*sks_valid*/ 1,
7799 					      /*command*/ 0,
7800 					      /*field*/ 8,
7801 					      /*bit_valid*/ 0,
7802 					      /*bit*/ 0);
7803 			ctl_done((union ctl_io *)ctsio);
7804 			return (1);
7805 		}
7806 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7807 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
7808 		int found = 0;
7809 
7810 		if (res_key == sa_res_key) {
7811 			/* special case */
7812 			/*
7813 			 * The spec implies this is not good but doesn't
7814 			 * say what to do. There are two choices either
7815 			 * generate a res conflict or check condition
7816 			 * with illegal field in parameter data. Since
7817 			 * that is what is done when the sa_res_key is
7818 			 * zero I'll take that approach since this has
7819 			 * to do with the sa_res_key.
7820 			 */
7821 			mtx_unlock(&lun->lun_lock);
7822 			free(ctsio->kern_data_ptr, M_CTL);
7823 			ctl_set_invalid_field(ctsio,
7824 					      /*sks_valid*/ 1,
7825 					      /*command*/ 0,
7826 					      /*field*/ 8,
7827 					      /*bit_valid*/ 0,
7828 					      /*bit*/ 0);
7829 			ctl_done((union ctl_io *)ctsio);
7830 			return (1);
7831 		}
7832 
7833 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7834 			if (ctl_get_prkey(lun, i) != sa_res_key)
7835 				continue;
7836 
7837 			found = 1;
7838 			ctl_clr_prkey(lun, i);
7839 			lun->pr_key_count--;
7840 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7841 		}
7842 		if (!found) {
7843 			mtx_unlock(&lun->lun_lock);
7844 			free(ctsio->kern_data_ptr, M_CTL);
7845 			ctl_set_reservation_conflict(ctsio);
7846 			ctl_done((union ctl_io *)ctsio);
7847 			return (CTL_RETVAL_COMPLETE);
7848 		}
7849 		lun->pr_generation++;
7850 		mtx_unlock(&lun->lun_lock);
7851 
7852 		/* send msg to other side */
7853 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7854 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7855 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7856 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
7857 		persis_io.pr.pr_info.res_type = type;
7858 		memcpy(persis_io.pr.pr_info.sa_res_key,
7859 		       param->serv_act_res_key,
7860 		       sizeof(param->serv_act_res_key));
7861 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7862 		    sizeof(persis_io.pr), M_WAITOK);
7863 	} else {
7864 		/* Reserved but not all registrants */
7865 		/* sa_res_key is res holder */
7866 		if (sa_res_key == ctl_get_prkey(lun, lun->pr_res_idx)) {
7867 			/* validate scope and type */
7868 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
7869 			     SPR_LU_SCOPE) {
7870 				mtx_unlock(&lun->lun_lock);
7871 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7872 						      /*sks_valid*/ 1,
7873 						      /*command*/ 1,
7874 						      /*field*/ 2,
7875 						      /*bit_valid*/ 1,
7876 						      /*bit*/ 4);
7877 				ctl_done((union ctl_io *)ctsio);
7878 				return (1);
7879 			}
7880 
7881 			if (type>8 || type==2 || type==4 || type==0) {
7882 				mtx_unlock(&lun->lun_lock);
7883 				ctl_set_invalid_field(/*ctsio*/ ctsio,
7884 						      /*sks_valid*/ 1,
7885 						      /*command*/ 1,
7886 						      /*field*/ 2,
7887 						      /*bit_valid*/ 1,
7888 						      /*bit*/ 0);
7889 				ctl_done((union ctl_io *)ctsio);
7890 				return (1);
7891 			}
7892 
7893 			/*
7894 			 * Do the following:
7895 			 * if sa_res_key != res_key remove all
7896 			 * registrants w/sa_res_key and generate UA
7897 			 * for these registrants(Registrations
7898 			 * Preempted) if it wasn't an exclusive
7899 			 * reservation generate UA(Reservations
7900 			 * Preempted) for all other registered nexuses
7901 			 * if the type has changed. Establish the new
7902 			 * reservation and holder. If res_key and
7903 			 * sa_res_key are the same do the above
7904 			 * except don't unregister the res holder.
7905 			 */
7906 
7907 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7908 				if (i == residx || ctl_get_prkey(lun, i) == 0)
7909 					continue;
7910 
7911 				if (sa_res_key == ctl_get_prkey(lun, i)) {
7912 					ctl_clr_prkey(lun, i);
7913 					lun->pr_key_count--;
7914 					ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7915 				} else if (type != lun->pr_res_type &&
7916 				    (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
7917 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
7918 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
7919 				}
7920 			}
7921 			lun->pr_res_type = type;
7922 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
7923 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
7924 				lun->pr_res_idx = residx;
7925 			else
7926 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
7927 			lun->pr_generation++;
7928 			mtx_unlock(&lun->lun_lock);
7929 
7930 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7931 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7932 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7933 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7934 			persis_io.pr.pr_info.res_type = type;
7935 			memcpy(persis_io.pr.pr_info.sa_res_key,
7936 			       param->serv_act_res_key,
7937 			       sizeof(param->serv_act_res_key));
7938 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7939 			    sizeof(persis_io.pr), M_WAITOK);
7940 		} else {
7941 			/*
7942 			 * sa_res_key is not the res holder just
7943 			 * remove registrants
7944 			 */
7945 			int found=0;
7946 
7947 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
7948 				if (sa_res_key != ctl_get_prkey(lun, i))
7949 					continue;
7950 
7951 				found = 1;
7952 				ctl_clr_prkey(lun, i);
7953 				lun->pr_key_count--;
7954 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
7955 			}
7956 
7957 			if (!found) {
7958 				mtx_unlock(&lun->lun_lock);
7959 				free(ctsio->kern_data_ptr, M_CTL);
7960 				ctl_set_reservation_conflict(ctsio);
7961 				ctl_done((union ctl_io *)ctsio);
7962 		        	return (1);
7963 			}
7964 			lun->pr_generation++;
7965 			mtx_unlock(&lun->lun_lock);
7966 
7967 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
7968 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
7969 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
7970 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
7971 			persis_io.pr.pr_info.res_type = type;
7972 			memcpy(persis_io.pr.pr_info.sa_res_key,
7973 			       param->serv_act_res_key,
7974 			       sizeof(param->serv_act_res_key));
7975 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
7976 			    sizeof(persis_io.pr), M_WAITOK);
7977 		}
7978 	}
7979 	return (0);
7980 }
7981 
7982 static void
7983 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
7984 {
7985 	uint64_t sa_res_key;
7986 	int i;
7987 
7988 	sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
7989 
7990 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
7991 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
7992 	 || sa_res_key != ctl_get_prkey(lun, lun->pr_res_idx)) {
7993 		if (sa_res_key == 0) {
7994 			/*
7995 			 * Unregister everybody else and build UA for
7996 			 * them
7997 			 */
7998 			for(i = 0; i < CTL_MAX_INITIATORS; i++) {
7999 				if (i == msg->pr.pr_info.residx ||
8000 				    ctl_get_prkey(lun, i) == 0)
8001 					continue;
8002 
8003 				ctl_clr_prkey(lun, i);
8004 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8005 			}
8006 
8007 			lun->pr_key_count = 1;
8008 			lun->pr_res_type = msg->pr.pr_info.res_type;
8009 			if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8010 			    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8011 				lun->pr_res_idx = msg->pr.pr_info.residx;
8012 		} else {
8013 		        for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8014 				if (sa_res_key == ctl_get_prkey(lun, i))
8015 					continue;
8016 
8017 				ctl_clr_prkey(lun, i);
8018 				lun->pr_key_count--;
8019 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8020 			}
8021 		}
8022 	} else {
8023 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8024 			if (i == msg->pr.pr_info.residx ||
8025 			    ctl_get_prkey(lun, i) == 0)
8026 				continue;
8027 
8028 			if (sa_res_key == ctl_get_prkey(lun, i)) {
8029 				ctl_clr_prkey(lun, i);
8030 				lun->pr_key_count--;
8031 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8032 			} else if (msg->pr.pr_info.res_type != lun->pr_res_type
8033 			    && (lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8034 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO)) {
8035 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8036 			}
8037 		}
8038 		lun->pr_res_type = msg->pr.pr_info.res_type;
8039 		if (lun->pr_res_type != SPR_TYPE_WR_EX_AR &&
8040 		    lun->pr_res_type != SPR_TYPE_EX_AC_AR)
8041 			lun->pr_res_idx = msg->pr.pr_info.residx;
8042 		else
8043 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8044 	}
8045 	lun->pr_generation++;
8046 
8047 }
8048 
8049 
8050 int
8051 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8052 {
8053 	int retval;
8054 	u_int32_t param_len;
8055 	struct scsi_per_res_out *cdb;
8056 	struct ctl_lun *lun;
8057 	struct scsi_per_res_out_parms* param;
8058 	struct ctl_softc *softc;
8059 	uint32_t residx;
8060 	uint64_t res_key, sa_res_key, key;
8061 	uint8_t type;
8062 	union ctl_ha_msg persis_io;
8063 	int    i;
8064 
8065 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8066 
8067 	retval = CTL_RETVAL_COMPLETE;
8068 
8069 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8070 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8071 	softc = lun->ctl_softc;
8072 
8073 	/*
8074 	 * We only support whole-LUN scope.  The scope & type are ignored for
8075 	 * register, register and ignore existing key and clear.
8076 	 * We sometimes ignore scope and type on preempts too!!
8077 	 * Verify reservation type here as well.
8078 	 */
8079 	type = cdb->scope_type & SPR_TYPE_MASK;
8080 	if ((cdb->action == SPRO_RESERVE)
8081 	 || (cdb->action == SPRO_RELEASE)) {
8082 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8083 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8084 					      /*sks_valid*/ 1,
8085 					      /*command*/ 1,
8086 					      /*field*/ 2,
8087 					      /*bit_valid*/ 1,
8088 					      /*bit*/ 4);
8089 			ctl_done((union ctl_io *)ctsio);
8090 			return (CTL_RETVAL_COMPLETE);
8091 		}
8092 
8093 		if (type>8 || type==2 || type==4 || type==0) {
8094 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8095 					      /*sks_valid*/ 1,
8096 					      /*command*/ 1,
8097 					      /*field*/ 2,
8098 					      /*bit_valid*/ 1,
8099 					      /*bit*/ 0);
8100 			ctl_done((union ctl_io *)ctsio);
8101 			return (CTL_RETVAL_COMPLETE);
8102 		}
8103 	}
8104 
8105 	param_len = scsi_4btoul(cdb->length);
8106 
8107 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8108 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8109 		ctsio->kern_data_len = param_len;
8110 		ctsio->kern_total_len = param_len;
8111 		ctsio->kern_data_resid = 0;
8112 		ctsio->kern_rel_offset = 0;
8113 		ctsio->kern_sg_entries = 0;
8114 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8115 		ctsio->be_move_done = ctl_config_move_done;
8116 		ctl_datamove((union ctl_io *)ctsio);
8117 
8118 		return (CTL_RETVAL_COMPLETE);
8119 	}
8120 
8121 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8122 
8123 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
8124 	res_key = scsi_8btou64(param->res_key.key);
8125 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8126 
8127 	/*
8128 	 * Validate the reservation key here except for SPRO_REG_IGNO
8129 	 * This must be done for all other service actions
8130 	 */
8131 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8132 		mtx_lock(&lun->lun_lock);
8133 		if ((key = ctl_get_prkey(lun, residx)) != 0) {
8134 			if (res_key != key) {
8135 				/*
8136 				 * The current key passed in doesn't match
8137 				 * the one the initiator previously
8138 				 * registered.
8139 				 */
8140 				mtx_unlock(&lun->lun_lock);
8141 				free(ctsio->kern_data_ptr, M_CTL);
8142 				ctl_set_reservation_conflict(ctsio);
8143 				ctl_done((union ctl_io *)ctsio);
8144 				return (CTL_RETVAL_COMPLETE);
8145 			}
8146 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8147 			/*
8148 			 * We are not registered
8149 			 */
8150 			mtx_unlock(&lun->lun_lock);
8151 			free(ctsio->kern_data_ptr, M_CTL);
8152 			ctl_set_reservation_conflict(ctsio);
8153 			ctl_done((union ctl_io *)ctsio);
8154 			return (CTL_RETVAL_COMPLETE);
8155 		} else if (res_key != 0) {
8156 			/*
8157 			 * We are not registered and trying to register but
8158 			 * the register key isn't zero.
8159 			 */
8160 			mtx_unlock(&lun->lun_lock);
8161 			free(ctsio->kern_data_ptr, M_CTL);
8162 			ctl_set_reservation_conflict(ctsio);
8163 			ctl_done((union ctl_io *)ctsio);
8164 			return (CTL_RETVAL_COMPLETE);
8165 		}
8166 		mtx_unlock(&lun->lun_lock);
8167 	}
8168 
8169 	switch (cdb->action & SPRO_ACTION_MASK) {
8170 	case SPRO_REGISTER:
8171 	case SPRO_REG_IGNO: {
8172 
8173 #if 0
8174 		printf("Registration received\n");
8175 #endif
8176 
8177 		/*
8178 		 * We don't support any of these options, as we report in
8179 		 * the read capabilities request (see
8180 		 * ctl_persistent_reserve_in(), above).
8181 		 */
8182 		if ((param->flags & SPR_SPEC_I_PT)
8183 		 || (param->flags & SPR_ALL_TG_PT)
8184 		 || (param->flags & SPR_APTPL)) {
8185 			int bit_ptr;
8186 
8187 			if (param->flags & SPR_APTPL)
8188 				bit_ptr = 0;
8189 			else if (param->flags & SPR_ALL_TG_PT)
8190 				bit_ptr = 2;
8191 			else /* SPR_SPEC_I_PT */
8192 				bit_ptr = 3;
8193 
8194 			free(ctsio->kern_data_ptr, M_CTL);
8195 			ctl_set_invalid_field(ctsio,
8196 					      /*sks_valid*/ 1,
8197 					      /*command*/ 0,
8198 					      /*field*/ 20,
8199 					      /*bit_valid*/ 1,
8200 					      /*bit*/ bit_ptr);
8201 			ctl_done((union ctl_io *)ctsio);
8202 			return (CTL_RETVAL_COMPLETE);
8203 		}
8204 
8205 		mtx_lock(&lun->lun_lock);
8206 
8207 		/*
8208 		 * The initiator wants to clear the
8209 		 * key/unregister.
8210 		 */
8211 		if (sa_res_key == 0) {
8212 			if ((res_key == 0
8213 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8214 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8215 			  && ctl_get_prkey(lun, residx) == 0)) {
8216 				mtx_unlock(&lun->lun_lock);
8217 				goto done;
8218 			}
8219 
8220 			ctl_clr_prkey(lun, residx);
8221 			lun->pr_key_count--;
8222 
8223 			if (residx == lun->pr_res_idx) {
8224 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8225 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8226 
8227 				if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8228 				     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8229 				    lun->pr_key_count) {
8230 					/*
8231 					 * If the reservation is a registrants
8232 					 * only type we need to generate a UA
8233 					 * for other registered inits.  The
8234 					 * sense code should be RESERVATIONS
8235 					 * RELEASED
8236 					 */
8237 
8238 					for (i = softc->init_min; i < softc->init_max; i++){
8239 						if (ctl_get_prkey(lun, i) == 0)
8240 							continue;
8241 						ctl_est_ua(lun, i,
8242 						    CTL_UA_RES_RELEASE);
8243 					}
8244 				}
8245 				lun->pr_res_type = 0;
8246 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8247 				if (lun->pr_key_count==0) {
8248 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8249 					lun->pr_res_type = 0;
8250 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8251 				}
8252 			}
8253 			lun->pr_generation++;
8254 			mtx_unlock(&lun->lun_lock);
8255 
8256 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8257 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8258 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8259 			persis_io.pr.pr_info.residx = residx;
8260 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8261 			    sizeof(persis_io.pr), M_WAITOK);
8262 		} else /* sa_res_key != 0 */ {
8263 
8264 			/*
8265 			 * If we aren't registered currently then increment
8266 			 * the key count and set the registered flag.
8267 			 */
8268 			ctl_alloc_prkey(lun, residx);
8269 			if (ctl_get_prkey(lun, residx) == 0)
8270 				lun->pr_key_count++;
8271 			ctl_set_prkey(lun, residx, sa_res_key);
8272 			lun->pr_generation++;
8273 			mtx_unlock(&lun->lun_lock);
8274 
8275 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8276 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8277 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8278 			persis_io.pr.pr_info.residx = residx;
8279 			memcpy(persis_io.pr.pr_info.sa_res_key,
8280 			       param->serv_act_res_key,
8281 			       sizeof(param->serv_act_res_key));
8282 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8283 			    sizeof(persis_io.pr), M_WAITOK);
8284 		}
8285 
8286 		break;
8287 	}
8288 	case SPRO_RESERVE:
8289 #if 0
8290                 printf("Reserve executed type %d\n", type);
8291 #endif
8292 		mtx_lock(&lun->lun_lock);
8293 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8294 			/*
8295 			 * if this isn't the reservation holder and it's
8296 			 * not a "all registrants" type or if the type is
8297 			 * different then we have a conflict
8298 			 */
8299 			if ((lun->pr_res_idx != residx
8300 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8301 			 || lun->pr_res_type != type) {
8302 				mtx_unlock(&lun->lun_lock);
8303 				free(ctsio->kern_data_ptr, M_CTL);
8304 				ctl_set_reservation_conflict(ctsio);
8305 				ctl_done((union ctl_io *)ctsio);
8306 				return (CTL_RETVAL_COMPLETE);
8307 			}
8308 			mtx_unlock(&lun->lun_lock);
8309 		} else /* create a reservation */ {
8310 			/*
8311 			 * If it's not an "all registrants" type record
8312 			 * reservation holder
8313 			 */
8314 			if (type != SPR_TYPE_WR_EX_AR
8315 			 && type != SPR_TYPE_EX_AC_AR)
8316 				lun->pr_res_idx = residx; /* Res holder */
8317 			else
8318 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8319 
8320 			lun->flags |= CTL_LUN_PR_RESERVED;
8321 			lun->pr_res_type = type;
8322 
8323 			mtx_unlock(&lun->lun_lock);
8324 
8325 			/* send msg to other side */
8326 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8327 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8328 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8329 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8330 			persis_io.pr.pr_info.res_type = type;
8331 			ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8332 			    sizeof(persis_io.pr), M_WAITOK);
8333 		}
8334 		break;
8335 
8336 	case SPRO_RELEASE:
8337 		mtx_lock(&lun->lun_lock);
8338 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8339 			/* No reservation exists return good status */
8340 			mtx_unlock(&lun->lun_lock);
8341 			goto done;
8342 		}
8343 		/*
8344 		 * Is this nexus a reservation holder?
8345 		 */
8346 		if (lun->pr_res_idx != residx
8347 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8348 			/*
8349 			 * not a res holder return good status but
8350 			 * do nothing
8351 			 */
8352 			mtx_unlock(&lun->lun_lock);
8353 			goto done;
8354 		}
8355 
8356 		if (lun->pr_res_type != type) {
8357 			mtx_unlock(&lun->lun_lock);
8358 			free(ctsio->kern_data_ptr, M_CTL);
8359 			ctl_set_illegal_pr_release(ctsio);
8360 			ctl_done((union ctl_io *)ctsio);
8361 			return (CTL_RETVAL_COMPLETE);
8362 		}
8363 
8364 		/* okay to release */
8365 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8366 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8367 		lun->pr_res_type = 0;
8368 
8369 		/*
8370 		 * if this isn't an exclusive access
8371 		 * res generate UA for all other
8372 		 * registrants.
8373 		 */
8374 		if (type != SPR_TYPE_EX_AC
8375 		 && type != SPR_TYPE_WR_EX) {
8376 			for (i = softc->init_min; i < softc->init_max; i++) {
8377 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8378 					continue;
8379 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8380 			}
8381 		}
8382 		mtx_unlock(&lun->lun_lock);
8383 
8384 		/* Send msg to other side */
8385 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8386 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8387 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8388 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8389 		     sizeof(persis_io.pr), M_WAITOK);
8390 		break;
8391 
8392 	case SPRO_CLEAR:
8393 		/* send msg to other side */
8394 
8395 		mtx_lock(&lun->lun_lock);
8396 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8397 		lun->pr_res_type = 0;
8398 		lun->pr_key_count = 0;
8399 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8400 
8401 		ctl_clr_prkey(lun, residx);
8402 		for (i = 0; i < CTL_MAX_INITIATORS; i++)
8403 			if (ctl_get_prkey(lun, i) != 0) {
8404 				ctl_clr_prkey(lun, i);
8405 				ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8406 			}
8407 		lun->pr_generation++;
8408 		mtx_unlock(&lun->lun_lock);
8409 
8410 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8411 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8412 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8413 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8414 		     sizeof(persis_io.pr), M_WAITOK);
8415 		break;
8416 
8417 	case SPRO_PREEMPT:
8418 	case SPRO_PRE_ABO: {
8419 		int nretval;
8420 
8421 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8422 					  residx, ctsio, cdb, param);
8423 		if (nretval != 0)
8424 			return (CTL_RETVAL_COMPLETE);
8425 		break;
8426 	}
8427 	default:
8428 		panic("%s: Invalid PR type %#x", __func__, cdb->action);
8429 	}
8430 
8431 done:
8432 	free(ctsio->kern_data_ptr, M_CTL);
8433 	ctl_set_success(ctsio);
8434 	ctl_done((union ctl_io *)ctsio);
8435 
8436 	return (retval);
8437 }
8438 
8439 /*
8440  * This routine is for handling a message from the other SC pertaining to
8441  * persistent reserve out. All the error checking will have been done
8442  * so only perorming the action need be done here to keep the two
8443  * in sync.
8444  */
8445 static void
8446 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8447 {
8448 	struct ctl_softc *softc = control_softc;
8449 	struct ctl_lun *lun;
8450 	int i;
8451 	uint32_t residx, targ_lun;
8452 
8453 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8454 	mtx_lock(&softc->ctl_lock);
8455 	if ((targ_lun >= CTL_MAX_LUNS) ||
8456 	    ((lun = softc->ctl_luns[targ_lun]) == NULL)) {
8457 		mtx_unlock(&softc->ctl_lock);
8458 		return;
8459 	}
8460 	mtx_lock(&lun->lun_lock);
8461 	mtx_unlock(&softc->ctl_lock);
8462 	if (lun->flags & CTL_LUN_DISABLED) {
8463 		mtx_unlock(&lun->lun_lock);
8464 		return;
8465 	}
8466 	residx = ctl_get_initindex(&msg->hdr.nexus);
8467 	switch(msg->pr.pr_info.action) {
8468 	case CTL_PR_REG_KEY:
8469 		ctl_alloc_prkey(lun, msg->pr.pr_info.residx);
8470 		if (ctl_get_prkey(lun, msg->pr.pr_info.residx) == 0)
8471 			lun->pr_key_count++;
8472 		ctl_set_prkey(lun, msg->pr.pr_info.residx,
8473 		    scsi_8btou64(msg->pr.pr_info.sa_res_key));
8474 		lun->pr_generation++;
8475 		break;
8476 
8477 	case CTL_PR_UNREG_KEY:
8478 		ctl_clr_prkey(lun, msg->pr.pr_info.residx);
8479 		lun->pr_key_count--;
8480 
8481 		/* XXX Need to see if the reservation has been released */
8482 		/* if so do we need to generate UA? */
8483 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8484 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8485 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8486 
8487 			if ((lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
8488 			     lun->pr_res_type == SPR_TYPE_EX_AC_RO) &&
8489 			    lun->pr_key_count) {
8490 				/*
8491 				 * If the reservation is a registrants
8492 				 * only type we need to generate a UA
8493 				 * for other registered inits.  The
8494 				 * sense code should be RESERVATIONS
8495 				 * RELEASED
8496 				 */
8497 
8498 				for (i = softc->init_min; i < softc->init_max; i++) {
8499 					if (ctl_get_prkey(lun, i) == 0)
8500 						continue;
8501 
8502 					ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8503 				}
8504 			}
8505 			lun->pr_res_type = 0;
8506 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8507 			if (lun->pr_key_count==0) {
8508 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8509 				lun->pr_res_type = 0;
8510 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8511 			}
8512 		}
8513 		lun->pr_generation++;
8514 		break;
8515 
8516 	case CTL_PR_RESERVE:
8517 		lun->flags |= CTL_LUN_PR_RESERVED;
8518 		lun->pr_res_type = msg->pr.pr_info.res_type;
8519 		lun->pr_res_idx = msg->pr.pr_info.residx;
8520 
8521 		break;
8522 
8523 	case CTL_PR_RELEASE:
8524 		/*
8525 		 * if this isn't an exclusive access res generate UA for all
8526 		 * other registrants.
8527 		 */
8528 		if (lun->pr_res_type != SPR_TYPE_EX_AC &&
8529 		    lun->pr_res_type != SPR_TYPE_WR_EX) {
8530 			for (i = softc->init_min; i < softc->init_max; i++)
8531 				if (i == residx || ctl_get_prkey(lun, i) == 0)
8532 					continue;
8533 				ctl_est_ua(lun, i, CTL_UA_RES_RELEASE);
8534 		}
8535 
8536 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8537 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8538 		lun->pr_res_type = 0;
8539 		break;
8540 
8541 	case CTL_PR_PREEMPT:
8542 		ctl_pro_preempt_other(lun, msg);
8543 		break;
8544 	case CTL_PR_CLEAR:
8545 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8546 		lun->pr_res_type = 0;
8547 		lun->pr_key_count = 0;
8548 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8549 
8550 		for (i=0; i < CTL_MAX_INITIATORS; i++) {
8551 			if (ctl_get_prkey(lun, i) == 0)
8552 				continue;
8553 			ctl_clr_prkey(lun, i);
8554 			ctl_est_ua(lun, i, CTL_UA_REG_PREEMPT);
8555 		}
8556 		lun->pr_generation++;
8557 		break;
8558 	}
8559 
8560 	mtx_unlock(&lun->lun_lock);
8561 }
8562 
8563 int
8564 ctl_read_write(struct ctl_scsiio *ctsio)
8565 {
8566 	struct ctl_lun *lun;
8567 	struct ctl_lba_len_flags *lbalen;
8568 	uint64_t lba;
8569 	uint32_t num_blocks;
8570 	int flags, retval;
8571 	int isread;
8572 
8573 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8574 
8575 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
8576 
8577 	flags = 0;
8578 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
8579 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
8580 	switch (ctsio->cdb[0]) {
8581 	case READ_6:
8582 	case WRITE_6: {
8583 		struct scsi_rw_6 *cdb;
8584 
8585 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
8586 
8587 		lba = scsi_3btoul(cdb->addr);
8588 		/* only 5 bits are valid in the most significant address byte */
8589 		lba &= 0x1fffff;
8590 		num_blocks = cdb->length;
8591 		/*
8592 		 * This is correct according to SBC-2.
8593 		 */
8594 		if (num_blocks == 0)
8595 			num_blocks = 256;
8596 		break;
8597 	}
8598 	case READ_10:
8599 	case WRITE_10: {
8600 		struct scsi_rw_10 *cdb;
8601 
8602 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
8603 		if (cdb->byte2 & SRW10_FUA)
8604 			flags |= CTL_LLF_FUA;
8605 		if (cdb->byte2 & SRW10_DPO)
8606 			flags |= CTL_LLF_DPO;
8607 		lba = scsi_4btoul(cdb->addr);
8608 		num_blocks = scsi_2btoul(cdb->length);
8609 		break;
8610 	}
8611 	case WRITE_VERIFY_10: {
8612 		struct scsi_write_verify_10 *cdb;
8613 
8614 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
8615 		flags |= CTL_LLF_FUA;
8616 		if (cdb->byte2 & SWV_DPO)
8617 			flags |= CTL_LLF_DPO;
8618 		lba = scsi_4btoul(cdb->addr);
8619 		num_blocks = scsi_2btoul(cdb->length);
8620 		break;
8621 	}
8622 	case READ_12:
8623 	case WRITE_12: {
8624 		struct scsi_rw_12 *cdb;
8625 
8626 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
8627 		if (cdb->byte2 & SRW12_FUA)
8628 			flags |= CTL_LLF_FUA;
8629 		if (cdb->byte2 & SRW12_DPO)
8630 			flags |= CTL_LLF_DPO;
8631 		lba = scsi_4btoul(cdb->addr);
8632 		num_blocks = scsi_4btoul(cdb->length);
8633 		break;
8634 	}
8635 	case WRITE_VERIFY_12: {
8636 		struct scsi_write_verify_12 *cdb;
8637 
8638 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
8639 		flags |= CTL_LLF_FUA;
8640 		if (cdb->byte2 & SWV_DPO)
8641 			flags |= CTL_LLF_DPO;
8642 		lba = scsi_4btoul(cdb->addr);
8643 		num_blocks = scsi_4btoul(cdb->length);
8644 		break;
8645 	}
8646 	case READ_16:
8647 	case WRITE_16: {
8648 		struct scsi_rw_16 *cdb;
8649 
8650 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8651 		if (cdb->byte2 & SRW12_FUA)
8652 			flags |= CTL_LLF_FUA;
8653 		if (cdb->byte2 & SRW12_DPO)
8654 			flags |= CTL_LLF_DPO;
8655 		lba = scsi_8btou64(cdb->addr);
8656 		num_blocks = scsi_4btoul(cdb->length);
8657 		break;
8658 	}
8659 	case WRITE_ATOMIC_16: {
8660 		struct scsi_write_atomic_16 *cdb;
8661 
8662 		if (lun->be_lun->atomicblock == 0) {
8663 			ctl_set_invalid_opcode(ctsio);
8664 			ctl_done((union ctl_io *)ctsio);
8665 			return (CTL_RETVAL_COMPLETE);
8666 		}
8667 
8668 		cdb = (struct scsi_write_atomic_16 *)ctsio->cdb;
8669 		if (cdb->byte2 & SRW12_FUA)
8670 			flags |= CTL_LLF_FUA;
8671 		if (cdb->byte2 & SRW12_DPO)
8672 			flags |= CTL_LLF_DPO;
8673 		lba = scsi_8btou64(cdb->addr);
8674 		num_blocks = scsi_2btoul(cdb->length);
8675 		if (num_blocks > lun->be_lun->atomicblock) {
8676 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
8677 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
8678 			    /*bit*/ 0);
8679 			ctl_done((union ctl_io *)ctsio);
8680 			return (CTL_RETVAL_COMPLETE);
8681 		}
8682 		break;
8683 	}
8684 	case WRITE_VERIFY_16: {
8685 		struct scsi_write_verify_16 *cdb;
8686 
8687 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
8688 		flags |= CTL_LLF_FUA;
8689 		if (cdb->byte2 & SWV_DPO)
8690 			flags |= CTL_LLF_DPO;
8691 		lba = scsi_8btou64(cdb->addr);
8692 		num_blocks = scsi_4btoul(cdb->length);
8693 		break;
8694 	}
8695 	default:
8696 		/*
8697 		 * We got a command we don't support.  This shouldn't
8698 		 * happen, commands should be filtered out above us.
8699 		 */
8700 		ctl_set_invalid_opcode(ctsio);
8701 		ctl_done((union ctl_io *)ctsio);
8702 
8703 		return (CTL_RETVAL_COMPLETE);
8704 		break; /* NOTREACHED */
8705 	}
8706 
8707 	/*
8708 	 * The first check is to make sure we're in bounds, the second
8709 	 * check is to catch wrap-around problems.  If the lba + num blocks
8710 	 * is less than the lba, then we've wrapped around and the block
8711 	 * range is invalid anyway.
8712 	 */
8713 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8714 	 || ((lba + num_blocks) < lba)) {
8715 		ctl_set_lba_out_of_range(ctsio);
8716 		ctl_done((union ctl_io *)ctsio);
8717 		return (CTL_RETVAL_COMPLETE);
8718 	}
8719 
8720 	/*
8721 	 * According to SBC-3, a transfer length of 0 is not an error.
8722 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
8723 	 * translates to 256 blocks for those commands.
8724 	 */
8725 	if (num_blocks == 0) {
8726 		ctl_set_success(ctsio);
8727 		ctl_done((union ctl_io *)ctsio);
8728 		return (CTL_RETVAL_COMPLETE);
8729 	}
8730 
8731 	/* Set FUA and/or DPO if caches are disabled. */
8732 	if (isread) {
8733 		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8734 		    SCP_RCD) != 0)
8735 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
8736 	} else {
8737 		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8738 		    SCP_WCE) == 0)
8739 			flags |= CTL_LLF_FUA;
8740 	}
8741 
8742 	lbalen = (struct ctl_lba_len_flags *)
8743 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8744 	lbalen->lba = lba;
8745 	lbalen->len = num_blocks;
8746 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
8747 
8748 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8749 	ctsio->kern_rel_offset = 0;
8750 
8751 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
8752 
8753 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8754 	return (retval);
8755 }
8756 
8757 static int
8758 ctl_cnw_cont(union ctl_io *io)
8759 {
8760 	struct ctl_scsiio *ctsio;
8761 	struct ctl_lun *lun;
8762 	struct ctl_lba_len_flags *lbalen;
8763 	int retval;
8764 
8765 	ctsio = &io->scsiio;
8766 	ctsio->io_hdr.status = CTL_STATUS_NONE;
8767 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
8768 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8769 	lbalen = (struct ctl_lba_len_flags *)
8770 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8771 	lbalen->flags &= ~CTL_LLF_COMPARE;
8772 	lbalen->flags |= CTL_LLF_WRITE;
8773 
8774 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
8775 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8776 	return (retval);
8777 }
8778 
8779 int
8780 ctl_cnw(struct ctl_scsiio *ctsio)
8781 {
8782 	struct ctl_lun *lun;
8783 	struct ctl_lba_len_flags *lbalen;
8784 	uint64_t lba;
8785 	uint32_t num_blocks;
8786 	int flags, retval;
8787 
8788 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8789 
8790 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
8791 
8792 	flags = 0;
8793 	switch (ctsio->cdb[0]) {
8794 	case COMPARE_AND_WRITE: {
8795 		struct scsi_compare_and_write *cdb;
8796 
8797 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
8798 		if (cdb->byte2 & SRW10_FUA)
8799 			flags |= CTL_LLF_FUA;
8800 		if (cdb->byte2 & SRW10_DPO)
8801 			flags |= CTL_LLF_DPO;
8802 		lba = scsi_8btou64(cdb->addr);
8803 		num_blocks = cdb->length;
8804 		break;
8805 	}
8806 	default:
8807 		/*
8808 		 * We got a command we don't support.  This shouldn't
8809 		 * happen, commands should be filtered out above us.
8810 		 */
8811 		ctl_set_invalid_opcode(ctsio);
8812 		ctl_done((union ctl_io *)ctsio);
8813 
8814 		return (CTL_RETVAL_COMPLETE);
8815 		break; /* NOTREACHED */
8816 	}
8817 
8818 	/*
8819 	 * The first check is to make sure we're in bounds, the second
8820 	 * check is to catch wrap-around problems.  If the lba + num blocks
8821 	 * is less than the lba, then we've wrapped around and the block
8822 	 * range is invalid anyway.
8823 	 */
8824 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8825 	 || ((lba + num_blocks) < lba)) {
8826 		ctl_set_lba_out_of_range(ctsio);
8827 		ctl_done((union ctl_io *)ctsio);
8828 		return (CTL_RETVAL_COMPLETE);
8829 	}
8830 
8831 	/*
8832 	 * According to SBC-3, a transfer length of 0 is not an error.
8833 	 */
8834 	if (num_blocks == 0) {
8835 		ctl_set_success(ctsio);
8836 		ctl_done((union ctl_io *)ctsio);
8837 		return (CTL_RETVAL_COMPLETE);
8838 	}
8839 
8840 	/* Set FUA if write cache is disabled. */
8841 	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
8842 	    SCP_WCE) == 0)
8843 		flags |= CTL_LLF_FUA;
8844 
8845 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
8846 	ctsio->kern_rel_offset = 0;
8847 
8848 	/*
8849 	 * Set the IO_CONT flag, so that if this I/O gets passed to
8850 	 * ctl_data_submit_done(), it'll get passed back to
8851 	 * ctl_ctl_cnw_cont() for further processing.
8852 	 */
8853 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
8854 	ctsio->io_cont = ctl_cnw_cont;
8855 
8856 	lbalen = (struct ctl_lba_len_flags *)
8857 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8858 	lbalen->lba = lba;
8859 	lbalen->len = num_blocks;
8860 	lbalen->flags = CTL_LLF_COMPARE | flags;
8861 
8862 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
8863 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8864 	return (retval);
8865 }
8866 
8867 int
8868 ctl_verify(struct ctl_scsiio *ctsio)
8869 {
8870 	struct ctl_lun *lun;
8871 	struct ctl_lba_len_flags *lbalen;
8872 	uint64_t lba;
8873 	uint32_t num_blocks;
8874 	int bytchk, flags;
8875 	int retval;
8876 
8877 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8878 
8879 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
8880 
8881 	bytchk = 0;
8882 	flags = CTL_LLF_FUA;
8883 	switch (ctsio->cdb[0]) {
8884 	case VERIFY_10: {
8885 		struct scsi_verify_10 *cdb;
8886 
8887 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
8888 		if (cdb->byte2 & SVFY_BYTCHK)
8889 			bytchk = 1;
8890 		if (cdb->byte2 & SVFY_DPO)
8891 			flags |= CTL_LLF_DPO;
8892 		lba = scsi_4btoul(cdb->addr);
8893 		num_blocks = scsi_2btoul(cdb->length);
8894 		break;
8895 	}
8896 	case VERIFY_12: {
8897 		struct scsi_verify_12 *cdb;
8898 
8899 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
8900 		if (cdb->byte2 & SVFY_BYTCHK)
8901 			bytchk = 1;
8902 		if (cdb->byte2 & SVFY_DPO)
8903 			flags |= CTL_LLF_DPO;
8904 		lba = scsi_4btoul(cdb->addr);
8905 		num_blocks = scsi_4btoul(cdb->length);
8906 		break;
8907 	}
8908 	case VERIFY_16: {
8909 		struct scsi_rw_16 *cdb;
8910 
8911 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
8912 		if (cdb->byte2 & SVFY_BYTCHK)
8913 			bytchk = 1;
8914 		if (cdb->byte2 & SVFY_DPO)
8915 			flags |= CTL_LLF_DPO;
8916 		lba = scsi_8btou64(cdb->addr);
8917 		num_blocks = scsi_4btoul(cdb->length);
8918 		break;
8919 	}
8920 	default:
8921 		/*
8922 		 * We got a command we don't support.  This shouldn't
8923 		 * happen, commands should be filtered out above us.
8924 		 */
8925 		ctl_set_invalid_opcode(ctsio);
8926 		ctl_done((union ctl_io *)ctsio);
8927 		return (CTL_RETVAL_COMPLETE);
8928 	}
8929 
8930 	/*
8931 	 * The first check is to make sure we're in bounds, the second
8932 	 * check is to catch wrap-around problems.  If the lba + num blocks
8933 	 * is less than the lba, then we've wrapped around and the block
8934 	 * range is invalid anyway.
8935 	 */
8936 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
8937 	 || ((lba + num_blocks) < lba)) {
8938 		ctl_set_lba_out_of_range(ctsio);
8939 		ctl_done((union ctl_io *)ctsio);
8940 		return (CTL_RETVAL_COMPLETE);
8941 	}
8942 
8943 	/*
8944 	 * According to SBC-3, a transfer length of 0 is not an error.
8945 	 */
8946 	if (num_blocks == 0) {
8947 		ctl_set_success(ctsio);
8948 		ctl_done((union ctl_io *)ctsio);
8949 		return (CTL_RETVAL_COMPLETE);
8950 	}
8951 
8952 	lbalen = (struct ctl_lba_len_flags *)
8953 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
8954 	lbalen->lba = lba;
8955 	lbalen->len = num_blocks;
8956 	if (bytchk) {
8957 		lbalen->flags = CTL_LLF_COMPARE | flags;
8958 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
8959 	} else {
8960 		lbalen->flags = CTL_LLF_VERIFY | flags;
8961 		ctsio->kern_total_len = 0;
8962 	}
8963 	ctsio->kern_rel_offset = 0;
8964 
8965 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
8966 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
8967 	return (retval);
8968 }
8969 
8970 int
8971 ctl_report_luns(struct ctl_scsiio *ctsio)
8972 {
8973 	struct ctl_softc *softc;
8974 	struct scsi_report_luns *cdb;
8975 	struct scsi_report_luns_data *lun_data;
8976 	struct ctl_lun *lun, *request_lun;
8977 	struct ctl_port *port;
8978 	int num_luns, retval;
8979 	uint32_t alloc_len, lun_datalen;
8980 	int num_filled;
8981 	uint32_t initidx, targ_lun_id, lun_id;
8982 
8983 	retval = CTL_RETVAL_COMPLETE;
8984 	cdb = (struct scsi_report_luns *)ctsio->cdb;
8985 	port = ctl_io_port(&ctsio->io_hdr);
8986 	softc = port->ctl_softc;
8987 
8988 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
8989 
8990 	mtx_lock(&softc->ctl_lock);
8991 	num_luns = 0;
8992 	for (targ_lun_id = 0; targ_lun_id < CTL_MAX_LUNS; targ_lun_id++) {
8993 		if (ctl_lun_map_from_port(port, targ_lun_id) < CTL_MAX_LUNS)
8994 			num_luns++;
8995 	}
8996 	mtx_unlock(&softc->ctl_lock);
8997 
8998 	switch (cdb->select_report) {
8999 	case RPL_REPORT_DEFAULT:
9000 	case RPL_REPORT_ALL:
9001 	case RPL_REPORT_NONSUBSID:
9002 		break;
9003 	case RPL_REPORT_WELLKNOWN:
9004 	case RPL_REPORT_ADMIN:
9005 	case RPL_REPORT_CONGLOM:
9006 		num_luns = 0;
9007 		break;
9008 	default:
9009 		ctl_set_invalid_field(ctsio,
9010 				      /*sks_valid*/ 1,
9011 				      /*command*/ 1,
9012 				      /*field*/ 2,
9013 				      /*bit_valid*/ 0,
9014 				      /*bit*/ 0);
9015 		ctl_done((union ctl_io *)ctsio);
9016 		return (retval);
9017 		break; /* NOTREACHED */
9018 	}
9019 
9020 	alloc_len = scsi_4btoul(cdb->length);
9021 	/*
9022 	 * The initiator has to allocate at least 16 bytes for this request,
9023 	 * so he can at least get the header and the first LUN.  Otherwise
9024 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9025 	 */
9026 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9027 	    sizeof(struct scsi_report_luns_lundata))) {
9028 		ctl_set_invalid_field(ctsio,
9029 				      /*sks_valid*/ 1,
9030 				      /*command*/ 1,
9031 				      /*field*/ 6,
9032 				      /*bit_valid*/ 0,
9033 				      /*bit*/ 0);
9034 		ctl_done((union ctl_io *)ctsio);
9035 		return (retval);
9036 	}
9037 
9038 	request_lun = (struct ctl_lun *)
9039 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9040 
9041 	lun_datalen = sizeof(*lun_data) +
9042 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9043 
9044 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9045 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9046 	ctsio->kern_sg_entries = 0;
9047 
9048 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9049 
9050 	mtx_lock(&softc->ctl_lock);
9051 	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9052 		lun_id = ctl_lun_map_from_port(port, targ_lun_id);
9053 		if (lun_id >= CTL_MAX_LUNS)
9054 			continue;
9055 		lun = softc->ctl_luns[lun_id];
9056 		if (lun == NULL)
9057 			continue;
9058 
9059 		if (targ_lun_id <= 0xff) {
9060 			/*
9061 			 * Peripheral addressing method, bus number 0.
9062 			 */
9063 			lun_data->luns[num_filled].lundata[0] =
9064 				RPL_LUNDATA_ATYP_PERIPH;
9065 			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9066 			num_filled++;
9067 		} else if (targ_lun_id <= 0x3fff) {
9068 			/*
9069 			 * Flat addressing method.
9070 			 */
9071 			lun_data->luns[num_filled].lundata[0] =
9072 				RPL_LUNDATA_ATYP_FLAT | (targ_lun_id >> 8);
9073 			lun_data->luns[num_filled].lundata[1] =
9074 				(targ_lun_id & 0xff);
9075 			num_filled++;
9076 		} else if (targ_lun_id <= 0xffffff) {
9077 			/*
9078 			 * Extended flat addressing method.
9079 			 */
9080 			lun_data->luns[num_filled].lundata[0] =
9081 			    RPL_LUNDATA_ATYP_EXTLUN | 0x12;
9082 			scsi_ulto3b(targ_lun_id,
9083 			    &lun_data->luns[num_filled].lundata[1]);
9084 			num_filled++;
9085 		} else {
9086 			printf("ctl_report_luns: bogus LUN number %jd, "
9087 			       "skipping\n", (intmax_t)targ_lun_id);
9088 		}
9089 		/*
9090 		 * According to SPC-3, rev 14 section 6.21:
9091 		 *
9092 		 * "The execution of a REPORT LUNS command to any valid and
9093 		 * installed logical unit shall clear the REPORTED LUNS DATA
9094 		 * HAS CHANGED unit attention condition for all logical
9095 		 * units of that target with respect to the requesting
9096 		 * initiator. A valid and installed logical unit is one
9097 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9098 		 * INQUIRY data (see 6.4.2)."
9099 		 *
9100 		 * If request_lun is NULL, the LUN this report luns command
9101 		 * was issued to is either disabled or doesn't exist. In that
9102 		 * case, we shouldn't clear any pending lun change unit
9103 		 * attention.
9104 		 */
9105 		if (request_lun != NULL) {
9106 			mtx_lock(&lun->lun_lock);
9107 			ctl_clr_ua(lun, initidx, CTL_UA_LUN_CHANGE);
9108 			mtx_unlock(&lun->lun_lock);
9109 		}
9110 	}
9111 	mtx_unlock(&softc->ctl_lock);
9112 
9113 	/*
9114 	 * It's quite possible that we've returned fewer LUNs than we allocated
9115 	 * space for.  Trim it.
9116 	 */
9117 	lun_datalen = sizeof(*lun_data) +
9118 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9119 
9120 	if (lun_datalen < alloc_len) {
9121 		ctsio->residual = alloc_len - lun_datalen;
9122 		ctsio->kern_data_len = lun_datalen;
9123 		ctsio->kern_total_len = lun_datalen;
9124 	} else {
9125 		ctsio->residual = 0;
9126 		ctsio->kern_data_len = alloc_len;
9127 		ctsio->kern_total_len = alloc_len;
9128 	}
9129 	ctsio->kern_data_resid = 0;
9130 	ctsio->kern_rel_offset = 0;
9131 	ctsio->kern_sg_entries = 0;
9132 
9133 	/*
9134 	 * We set this to the actual data length, regardless of how much
9135 	 * space we actually have to return results.  If the user looks at
9136 	 * this value, he'll know whether or not he allocated enough space
9137 	 * and reissue the command if necessary.  We don't support well
9138 	 * known logical units, so if the user asks for that, return none.
9139 	 */
9140 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9141 
9142 	/*
9143 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9144 	 * this request.
9145 	 */
9146 	ctl_set_success(ctsio);
9147 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9148 	ctsio->be_move_done = ctl_config_move_done;
9149 	ctl_datamove((union ctl_io *)ctsio);
9150 	return (retval);
9151 }
9152 
9153 int
9154 ctl_request_sense(struct ctl_scsiio *ctsio)
9155 {
9156 	struct scsi_request_sense *cdb;
9157 	struct scsi_sense_data *sense_ptr;
9158 	struct ctl_softc *ctl_softc;
9159 	struct ctl_lun *lun;
9160 	uint32_t initidx;
9161 	int have_error;
9162 	scsi_sense_data_type sense_format;
9163 	ctl_ua_type ua_type;
9164 
9165 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9166 
9167 	ctl_softc = control_softc;
9168 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9169 
9170 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9171 
9172 	/*
9173 	 * Determine which sense format the user wants.
9174 	 */
9175 	if (cdb->byte2 & SRS_DESC)
9176 		sense_format = SSD_TYPE_DESC;
9177 	else
9178 		sense_format = SSD_TYPE_FIXED;
9179 
9180 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9181 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9182 	ctsio->kern_sg_entries = 0;
9183 
9184 	/*
9185 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9186 	 * larger than the largest allowed value for the length field in the
9187 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9188 	 */
9189 	ctsio->residual = 0;
9190 	ctsio->kern_data_len = cdb->length;
9191 	ctsio->kern_total_len = cdb->length;
9192 
9193 	ctsio->kern_data_resid = 0;
9194 	ctsio->kern_rel_offset = 0;
9195 	ctsio->kern_sg_entries = 0;
9196 
9197 	/*
9198 	 * If we don't have a LUN, we don't have any pending sense.
9199 	 */
9200 	if (lun == NULL)
9201 		goto no_sense;
9202 
9203 	have_error = 0;
9204 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9205 	/*
9206 	 * Check for pending sense, and then for pending unit attentions.
9207 	 * Pending sense gets returned first, then pending unit attentions.
9208 	 */
9209 	mtx_lock(&lun->lun_lock);
9210 #ifdef CTL_WITH_CA
9211 	if (ctl_is_set(lun->have_ca, initidx)) {
9212 		scsi_sense_data_type stored_format;
9213 
9214 		/*
9215 		 * Check to see which sense format was used for the stored
9216 		 * sense data.
9217 		 */
9218 		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9219 
9220 		/*
9221 		 * If the user requested a different sense format than the
9222 		 * one we stored, then we need to convert it to the other
9223 		 * format.  If we're going from descriptor to fixed format
9224 		 * sense data, we may lose things in translation, depending
9225 		 * on what options were used.
9226 		 *
9227 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9228 		 * for some reason we'll just copy it out as-is.
9229 		 */
9230 		if ((stored_format == SSD_TYPE_FIXED)
9231 		 && (sense_format == SSD_TYPE_DESC))
9232 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9233 			    &lun->pending_sense[initidx],
9234 			    (struct scsi_sense_data_desc *)sense_ptr);
9235 		else if ((stored_format == SSD_TYPE_DESC)
9236 		      && (sense_format == SSD_TYPE_FIXED))
9237 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9238 			    &lun->pending_sense[initidx],
9239 			    (struct scsi_sense_data_fixed *)sense_ptr);
9240 		else
9241 			memcpy(sense_ptr, &lun->pending_sense[initidx],
9242 			       MIN(sizeof(*sense_ptr),
9243 			       sizeof(lun->pending_sense[initidx])));
9244 
9245 		ctl_clear_mask(lun->have_ca, initidx);
9246 		have_error = 1;
9247 	} else
9248 #endif
9249 	{
9250 		ua_type = ctl_build_ua(lun, initidx, sense_ptr, sense_format);
9251 		if (ua_type != CTL_UA_NONE)
9252 			have_error = 1;
9253 		if (ua_type == CTL_UA_LUN_CHANGE) {
9254 			mtx_unlock(&lun->lun_lock);
9255 			mtx_lock(&ctl_softc->ctl_lock);
9256 			ctl_clr_ua_allluns(ctl_softc, initidx, ua_type);
9257 			mtx_unlock(&ctl_softc->ctl_lock);
9258 			mtx_lock(&lun->lun_lock);
9259 		}
9260 
9261 	}
9262 	mtx_unlock(&lun->lun_lock);
9263 
9264 	/*
9265 	 * We already have a pending error, return it.
9266 	 */
9267 	if (have_error != 0) {
9268 		/*
9269 		 * We report the SCSI status as OK, since the status of the
9270 		 * request sense command itself is OK.
9271 		 * We report 0 for the sense length, because we aren't doing
9272 		 * autosense in this case.  We're reporting sense as
9273 		 * parameter data.
9274 		 */
9275 		ctl_set_success(ctsio);
9276 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9277 		ctsio->be_move_done = ctl_config_move_done;
9278 		ctl_datamove((union ctl_io *)ctsio);
9279 		return (CTL_RETVAL_COMPLETE);
9280 	}
9281 
9282 no_sense:
9283 
9284 	/*
9285 	 * No sense information to report, so we report that everything is
9286 	 * okay.
9287 	 */
9288 	ctl_set_sense_data(sense_ptr,
9289 			   lun,
9290 			   sense_format,
9291 			   /*current_error*/ 1,
9292 			   /*sense_key*/ SSD_KEY_NO_SENSE,
9293 			   /*asc*/ 0x00,
9294 			   /*ascq*/ 0x00,
9295 			   SSD_ELEM_NONE);
9296 
9297 	/*
9298 	 * We report 0 for the sense length, because we aren't doing
9299 	 * autosense in this case.  We're reporting sense as parameter data.
9300 	 */
9301 	ctl_set_success(ctsio);
9302 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9303 	ctsio->be_move_done = ctl_config_move_done;
9304 	ctl_datamove((union ctl_io *)ctsio);
9305 	return (CTL_RETVAL_COMPLETE);
9306 }
9307 
9308 int
9309 ctl_tur(struct ctl_scsiio *ctsio)
9310 {
9311 
9312 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9313 
9314 	ctl_set_success(ctsio);
9315 	ctl_done((union ctl_io *)ctsio);
9316 
9317 	return (CTL_RETVAL_COMPLETE);
9318 }
9319 
9320 /*
9321  * SCSI VPD page 0x00, the Supported VPD Pages page.
9322  */
9323 static int
9324 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9325 {
9326 	struct scsi_vpd_supported_pages *pages;
9327 	int sup_page_size;
9328 	struct ctl_lun *lun;
9329 	int p;
9330 
9331 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9332 
9333 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9334 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9335 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9336 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9337 	ctsio->kern_sg_entries = 0;
9338 
9339 	if (sup_page_size < alloc_len) {
9340 		ctsio->residual = alloc_len - sup_page_size;
9341 		ctsio->kern_data_len = sup_page_size;
9342 		ctsio->kern_total_len = sup_page_size;
9343 	} else {
9344 		ctsio->residual = 0;
9345 		ctsio->kern_data_len = alloc_len;
9346 		ctsio->kern_total_len = alloc_len;
9347 	}
9348 	ctsio->kern_data_resid = 0;
9349 	ctsio->kern_rel_offset = 0;
9350 	ctsio->kern_sg_entries = 0;
9351 
9352 	/*
9353 	 * The control device is always connected.  The disk device, on the
9354 	 * other hand, may not be online all the time.  Need to change this
9355 	 * to figure out whether the disk device is actually online or not.
9356 	 */
9357 	if (lun != NULL)
9358 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9359 				lun->be_lun->lun_type;
9360 	else
9361 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9362 
9363 	p = 0;
9364 	/* Supported VPD pages */
9365 	pages->page_list[p++] = SVPD_SUPPORTED_PAGES;
9366 	/* Serial Number */
9367 	pages->page_list[p++] = SVPD_UNIT_SERIAL_NUMBER;
9368 	/* Device Identification */
9369 	pages->page_list[p++] = SVPD_DEVICE_ID;
9370 	/* Extended INQUIRY Data */
9371 	pages->page_list[p++] = SVPD_EXTENDED_INQUIRY_DATA;
9372 	/* Mode Page Policy */
9373 	pages->page_list[p++] = SVPD_MODE_PAGE_POLICY;
9374 	/* SCSI Ports */
9375 	pages->page_list[p++] = SVPD_SCSI_PORTS;
9376 	/* Third-party Copy */
9377 	pages->page_list[p++] = SVPD_SCSI_TPC;
9378 	if (lun != NULL && lun->be_lun->lun_type == T_DIRECT) {
9379 		/* Block limits */
9380 		pages->page_list[p++] = SVPD_BLOCK_LIMITS;
9381 		/* Block Device Characteristics */
9382 		pages->page_list[p++] = SVPD_BDC;
9383 		/* Logical Block Provisioning */
9384 		pages->page_list[p++] = SVPD_LBP;
9385 	}
9386 	pages->length = p;
9387 
9388 	ctl_set_success(ctsio);
9389 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9390 	ctsio->be_move_done = ctl_config_move_done;
9391 	ctl_datamove((union ctl_io *)ctsio);
9392 	return (CTL_RETVAL_COMPLETE);
9393 }
9394 
9395 /*
9396  * SCSI VPD page 0x80, the Unit Serial Number page.
9397  */
9398 static int
9399 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9400 {
9401 	struct scsi_vpd_unit_serial_number *sn_ptr;
9402 	struct ctl_lun *lun;
9403 	int data_len;
9404 
9405 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9406 
9407 	data_len = 4 + CTL_SN_LEN;
9408 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9409 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9410 	if (data_len < alloc_len) {
9411 		ctsio->residual = alloc_len - data_len;
9412 		ctsio->kern_data_len = data_len;
9413 		ctsio->kern_total_len = data_len;
9414 	} else {
9415 		ctsio->residual = 0;
9416 		ctsio->kern_data_len = alloc_len;
9417 		ctsio->kern_total_len = alloc_len;
9418 	}
9419 	ctsio->kern_data_resid = 0;
9420 	ctsio->kern_rel_offset = 0;
9421 	ctsio->kern_sg_entries = 0;
9422 
9423 	/*
9424 	 * The control device is always connected.  The disk device, on the
9425 	 * other hand, may not be online all the time.  Need to change this
9426 	 * to figure out whether the disk device is actually online or not.
9427 	 */
9428 	if (lun != NULL)
9429 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9430 				  lun->be_lun->lun_type;
9431 	else
9432 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9433 
9434 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9435 	sn_ptr->length = CTL_SN_LEN;
9436 	/*
9437 	 * If we don't have a LUN, we just leave the serial number as
9438 	 * all spaces.
9439 	 */
9440 	if (lun != NULL) {
9441 		strncpy((char *)sn_ptr->serial_num,
9442 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9443 	} else
9444 		memset(sn_ptr->serial_num, 0x20, CTL_SN_LEN);
9445 
9446 	ctl_set_success(ctsio);
9447 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9448 	ctsio->be_move_done = ctl_config_move_done;
9449 	ctl_datamove((union ctl_io *)ctsio);
9450 	return (CTL_RETVAL_COMPLETE);
9451 }
9452 
9453 
9454 /*
9455  * SCSI VPD page 0x86, the Extended INQUIRY Data page.
9456  */
9457 static int
9458 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9459 {
9460 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9461 	struct ctl_lun *lun;
9462 	int data_len;
9463 
9464 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9465 
9466 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9467 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9468 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9469 	ctsio->kern_sg_entries = 0;
9470 
9471 	if (data_len < alloc_len) {
9472 		ctsio->residual = alloc_len - data_len;
9473 		ctsio->kern_data_len = data_len;
9474 		ctsio->kern_total_len = data_len;
9475 	} else {
9476 		ctsio->residual = 0;
9477 		ctsio->kern_data_len = alloc_len;
9478 		ctsio->kern_total_len = alloc_len;
9479 	}
9480 	ctsio->kern_data_resid = 0;
9481 	ctsio->kern_rel_offset = 0;
9482 	ctsio->kern_sg_entries = 0;
9483 
9484 	/*
9485 	 * The control device is always connected.  The disk device, on the
9486 	 * other hand, may not be online all the time.
9487 	 */
9488 	if (lun != NULL)
9489 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9490 				     lun->be_lun->lun_type;
9491 	else
9492 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9493 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9494 	scsi_ulto2b(data_len - 4, eid_ptr->page_length);
9495 	/*
9496 	 * We support head of queue, ordered and simple tags.
9497 	 */
9498 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9499 	/*
9500 	 * Volatile cache supported.
9501 	 */
9502 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9503 
9504 	/*
9505 	 * This means that we clear the REPORTED LUNS DATA HAS CHANGED unit
9506 	 * attention for a particular IT nexus on all LUNs once we report
9507 	 * it to that nexus once.  This bit is required as of SPC-4.
9508 	 */
9509 	eid_ptr->flags4 = SVPD_EID_LUICLT;
9510 
9511 	/*
9512 	 * XXX KDM in order to correctly answer this, we would need
9513 	 * information from the SIM to determine how much sense data it
9514 	 * can send.  So this would really be a path inquiry field, most
9515 	 * likely.  This can be set to a maximum of 252 according to SPC-4,
9516 	 * but the hardware may or may not be able to support that much.
9517 	 * 0 just means that the maximum sense data length is not reported.
9518 	 */
9519 	eid_ptr->max_sense_length = 0;
9520 
9521 	ctl_set_success(ctsio);
9522 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9523 	ctsio->be_move_done = ctl_config_move_done;
9524 	ctl_datamove((union ctl_io *)ctsio);
9525 	return (CTL_RETVAL_COMPLETE);
9526 }
9527 
9528 static int
9529 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
9530 {
9531 	struct scsi_vpd_mode_page_policy *mpp_ptr;
9532 	struct ctl_lun *lun;
9533 	int data_len;
9534 
9535 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9536 
9537 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
9538 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
9539 
9540 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9541 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
9542 	ctsio->kern_sg_entries = 0;
9543 
9544 	if (data_len < alloc_len) {
9545 		ctsio->residual = alloc_len - data_len;
9546 		ctsio->kern_data_len = data_len;
9547 		ctsio->kern_total_len = data_len;
9548 	} else {
9549 		ctsio->residual = 0;
9550 		ctsio->kern_data_len = alloc_len;
9551 		ctsio->kern_total_len = alloc_len;
9552 	}
9553 	ctsio->kern_data_resid = 0;
9554 	ctsio->kern_rel_offset = 0;
9555 	ctsio->kern_sg_entries = 0;
9556 
9557 	/*
9558 	 * The control device is always connected.  The disk device, on the
9559 	 * other hand, may not be online all the time.
9560 	 */
9561 	if (lun != NULL)
9562 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9563 				     lun->be_lun->lun_type;
9564 	else
9565 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9566 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
9567 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
9568 	mpp_ptr->descr[0].page_code = 0x3f;
9569 	mpp_ptr->descr[0].subpage_code = 0xff;
9570 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
9571 
9572 	ctl_set_success(ctsio);
9573 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9574 	ctsio->be_move_done = ctl_config_move_done;
9575 	ctl_datamove((union ctl_io *)ctsio);
9576 	return (CTL_RETVAL_COMPLETE);
9577 }
9578 
9579 /*
9580  * SCSI VPD page 0x83, the Device Identification page.
9581  */
9582 static int
9583 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
9584 {
9585 	struct scsi_vpd_device_id *devid_ptr;
9586 	struct scsi_vpd_id_descriptor *desc;
9587 	struct ctl_softc *softc;
9588 	struct ctl_lun *lun;
9589 	struct ctl_port *port;
9590 	int data_len;
9591 	uint8_t proto;
9592 
9593 	softc = control_softc;
9594 
9595 	port = ctl_io_port(&ctsio->io_hdr);
9596 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9597 
9598 	data_len = sizeof(struct scsi_vpd_device_id) +
9599 	    sizeof(struct scsi_vpd_id_descriptor) +
9600 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
9601 	    sizeof(struct scsi_vpd_id_descriptor) +
9602 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
9603 	if (lun && lun->lun_devid)
9604 		data_len += lun->lun_devid->len;
9605 	if (port && port->port_devid)
9606 		data_len += port->port_devid->len;
9607 	if (port && port->target_devid)
9608 		data_len += port->target_devid->len;
9609 
9610 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9611 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
9612 	ctsio->kern_sg_entries = 0;
9613 
9614 	if (data_len < alloc_len) {
9615 		ctsio->residual = alloc_len - data_len;
9616 		ctsio->kern_data_len = data_len;
9617 		ctsio->kern_total_len = data_len;
9618 	} else {
9619 		ctsio->residual = 0;
9620 		ctsio->kern_data_len = alloc_len;
9621 		ctsio->kern_total_len = alloc_len;
9622 	}
9623 	ctsio->kern_data_resid = 0;
9624 	ctsio->kern_rel_offset = 0;
9625 	ctsio->kern_sg_entries = 0;
9626 
9627 	/*
9628 	 * The control device is always connected.  The disk device, on the
9629 	 * other hand, may not be online all the time.
9630 	 */
9631 	if (lun != NULL)
9632 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9633 				     lun->be_lun->lun_type;
9634 	else
9635 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9636 	devid_ptr->page_code = SVPD_DEVICE_ID;
9637 	scsi_ulto2b(data_len - 4, devid_ptr->length);
9638 
9639 	if (port && port->port_type == CTL_PORT_FC)
9640 		proto = SCSI_PROTO_FC << 4;
9641 	else if (port && port->port_type == CTL_PORT_ISCSI)
9642 		proto = SCSI_PROTO_ISCSI << 4;
9643 	else
9644 		proto = SCSI_PROTO_SPI << 4;
9645 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
9646 
9647 	/*
9648 	 * We're using a LUN association here.  i.e., this device ID is a
9649 	 * per-LUN identifier.
9650 	 */
9651 	if (lun && lun->lun_devid) {
9652 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
9653 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9654 		    lun->lun_devid->len);
9655 	}
9656 
9657 	/*
9658 	 * This is for the WWPN which is a port association.
9659 	 */
9660 	if (port && port->port_devid) {
9661 		memcpy(desc, port->port_devid->data, port->port_devid->len);
9662 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
9663 		    port->port_devid->len);
9664 	}
9665 
9666 	/*
9667 	 * This is for the Relative Target Port(type 4h) identifier
9668 	 */
9669 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9670 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9671 	    SVPD_ID_TYPE_RELTARG;
9672 	desc->length = 4;
9673 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
9674 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9675 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
9676 
9677 	/*
9678 	 * This is for the Target Port Group(type 5h) identifier
9679 	 */
9680 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
9681 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
9682 	    SVPD_ID_TYPE_TPORTGRP;
9683 	desc->length = 4;
9684 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / softc->port_cnt + 1,
9685 	    &desc->identifier[2]);
9686 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
9687 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
9688 
9689 	/*
9690 	 * This is for the Target identifier
9691 	 */
9692 	if (port && port->target_devid) {
9693 		memcpy(desc, port->target_devid->data, port->target_devid->len);
9694 	}
9695 
9696 	ctl_set_success(ctsio);
9697 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9698 	ctsio->be_move_done = ctl_config_move_done;
9699 	ctl_datamove((union ctl_io *)ctsio);
9700 	return (CTL_RETVAL_COMPLETE);
9701 }
9702 
9703 static int
9704 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
9705 {
9706 	struct ctl_softc *softc = control_softc;
9707 	struct scsi_vpd_scsi_ports *sp;
9708 	struct scsi_vpd_port_designation *pd;
9709 	struct scsi_vpd_port_designation_cont *pdc;
9710 	struct ctl_lun *lun;
9711 	struct ctl_port *port;
9712 	int data_len, num_target_ports, iid_len, id_len;
9713 
9714 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9715 
9716 	num_target_ports = 0;
9717 	iid_len = 0;
9718 	id_len = 0;
9719 	mtx_lock(&softc->ctl_lock);
9720 	STAILQ_FOREACH(port, &softc->port_list, links) {
9721 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9722 			continue;
9723 		if (lun != NULL &&
9724 		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9725 			continue;
9726 		num_target_ports++;
9727 		if (port->init_devid)
9728 			iid_len += port->init_devid->len;
9729 		if (port->port_devid)
9730 			id_len += port->port_devid->len;
9731 	}
9732 	mtx_unlock(&softc->ctl_lock);
9733 
9734 	data_len = sizeof(struct scsi_vpd_scsi_ports) +
9735 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
9736 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
9737 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9738 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
9739 	ctsio->kern_sg_entries = 0;
9740 
9741 	if (data_len < alloc_len) {
9742 		ctsio->residual = alloc_len - data_len;
9743 		ctsio->kern_data_len = data_len;
9744 		ctsio->kern_total_len = data_len;
9745 	} else {
9746 		ctsio->residual = 0;
9747 		ctsio->kern_data_len = alloc_len;
9748 		ctsio->kern_total_len = alloc_len;
9749 	}
9750 	ctsio->kern_data_resid = 0;
9751 	ctsio->kern_rel_offset = 0;
9752 	ctsio->kern_sg_entries = 0;
9753 
9754 	/*
9755 	 * The control device is always connected.  The disk device, on the
9756 	 * other hand, may not be online all the time.  Need to change this
9757 	 * to figure out whether the disk device is actually online or not.
9758 	 */
9759 	if (lun != NULL)
9760 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
9761 				  lun->be_lun->lun_type;
9762 	else
9763 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9764 
9765 	sp->page_code = SVPD_SCSI_PORTS;
9766 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
9767 	    sp->page_length);
9768 	pd = &sp->design[0];
9769 
9770 	mtx_lock(&softc->ctl_lock);
9771 	STAILQ_FOREACH(port, &softc->port_list, links) {
9772 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
9773 			continue;
9774 		if (lun != NULL &&
9775 		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
9776 			continue;
9777 		scsi_ulto2b(port->targ_port, pd->relative_port_id);
9778 		if (port->init_devid) {
9779 			iid_len = port->init_devid->len;
9780 			memcpy(pd->initiator_transportid,
9781 			    port->init_devid->data, port->init_devid->len);
9782 		} else
9783 			iid_len = 0;
9784 		scsi_ulto2b(iid_len, pd->initiator_transportid_length);
9785 		pdc = (struct scsi_vpd_port_designation_cont *)
9786 		    (&pd->initiator_transportid[iid_len]);
9787 		if (port->port_devid) {
9788 			id_len = port->port_devid->len;
9789 			memcpy(pdc->target_port_descriptors,
9790 			    port->port_devid->data, port->port_devid->len);
9791 		} else
9792 			id_len = 0;
9793 		scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
9794 		pd = (struct scsi_vpd_port_designation *)
9795 		    ((uint8_t *)pdc->target_port_descriptors + id_len);
9796 	}
9797 	mtx_unlock(&softc->ctl_lock);
9798 
9799 	ctl_set_success(ctsio);
9800 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9801 	ctsio->be_move_done = ctl_config_move_done;
9802 	ctl_datamove((union ctl_io *)ctsio);
9803 	return (CTL_RETVAL_COMPLETE);
9804 }
9805 
9806 static int
9807 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
9808 {
9809 	struct scsi_vpd_block_limits *bl_ptr;
9810 	struct ctl_lun *lun;
9811 
9812 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9813 
9814 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
9815 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
9816 	ctsio->kern_sg_entries = 0;
9817 
9818 	if (sizeof(*bl_ptr) < alloc_len) {
9819 		ctsio->residual = alloc_len - sizeof(*bl_ptr);
9820 		ctsio->kern_data_len = sizeof(*bl_ptr);
9821 		ctsio->kern_total_len = sizeof(*bl_ptr);
9822 	} else {
9823 		ctsio->residual = 0;
9824 		ctsio->kern_data_len = alloc_len;
9825 		ctsio->kern_total_len = alloc_len;
9826 	}
9827 	ctsio->kern_data_resid = 0;
9828 	ctsio->kern_rel_offset = 0;
9829 	ctsio->kern_sg_entries = 0;
9830 
9831 	/*
9832 	 * The control device is always connected.  The disk device, on the
9833 	 * other hand, may not be online all the time.  Need to change this
9834 	 * to figure out whether the disk device is actually online or not.
9835 	 */
9836 	if (lun != NULL)
9837 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9838 				  lun->be_lun->lun_type;
9839 	else
9840 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9841 
9842 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
9843 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
9844 	bl_ptr->max_cmp_write_len = 0xff;
9845 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
9846 	if (lun != NULL) {
9847 		scsi_ulto4b(lun->be_lun->opttxferlen, bl_ptr->opt_txfer_len);
9848 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9849 			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
9850 			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
9851 			if (lun->be_lun->ublockexp != 0) {
9852 				scsi_ulto4b((1 << lun->be_lun->ublockexp),
9853 				    bl_ptr->opt_unmap_grain);
9854 				scsi_ulto4b(0x80000000 | lun->be_lun->ublockoff,
9855 				    bl_ptr->unmap_grain_align);
9856 			}
9857 		}
9858 		scsi_ulto4b(lun->be_lun->atomicblock,
9859 		    bl_ptr->max_atomic_transfer_length);
9860 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
9861 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
9862 		scsi_ulto4b(0, bl_ptr->max_atomic_transfer_length_with_atomic_boundary);
9863 		scsi_ulto4b(0, bl_ptr->max_atomic_boundary_size);
9864 	}
9865 	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
9866 
9867 	ctl_set_success(ctsio);
9868 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9869 	ctsio->be_move_done = ctl_config_move_done;
9870 	ctl_datamove((union ctl_io *)ctsio);
9871 	return (CTL_RETVAL_COMPLETE);
9872 }
9873 
9874 static int
9875 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
9876 {
9877 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
9878 	struct ctl_lun *lun;
9879 	const char *value;
9880 	u_int i;
9881 
9882 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9883 
9884 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
9885 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
9886 	ctsio->kern_sg_entries = 0;
9887 
9888 	if (sizeof(*bdc_ptr) < alloc_len) {
9889 		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
9890 		ctsio->kern_data_len = sizeof(*bdc_ptr);
9891 		ctsio->kern_total_len = sizeof(*bdc_ptr);
9892 	} else {
9893 		ctsio->residual = 0;
9894 		ctsio->kern_data_len = alloc_len;
9895 		ctsio->kern_total_len = alloc_len;
9896 	}
9897 	ctsio->kern_data_resid = 0;
9898 	ctsio->kern_rel_offset = 0;
9899 	ctsio->kern_sg_entries = 0;
9900 
9901 	/*
9902 	 * The control device is always connected.  The disk device, on the
9903 	 * other hand, may not be online all the time.  Need to change this
9904 	 * to figure out whether the disk device is actually online or not.
9905 	 */
9906 	if (lun != NULL)
9907 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9908 				  lun->be_lun->lun_type;
9909 	else
9910 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9911 	bdc_ptr->page_code = SVPD_BDC;
9912 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
9913 	if (lun != NULL &&
9914 	    (value = ctl_get_opt(&lun->be_lun->options, "rpm")) != NULL)
9915 		i = strtol(value, NULL, 0);
9916 	else
9917 		i = CTL_DEFAULT_ROTATION_RATE;
9918 	scsi_ulto2b(i, bdc_ptr->medium_rotation_rate);
9919 	if (lun != NULL &&
9920 	    (value = ctl_get_opt(&lun->be_lun->options, "formfactor")) != NULL)
9921 		i = strtol(value, NULL, 0);
9922 	else
9923 		i = 0;
9924 	bdc_ptr->wab_wac_ff = (i & 0x0f);
9925 	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
9926 
9927 	ctl_set_success(ctsio);
9928 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9929 	ctsio->be_move_done = ctl_config_move_done;
9930 	ctl_datamove((union ctl_io *)ctsio);
9931 	return (CTL_RETVAL_COMPLETE);
9932 }
9933 
9934 static int
9935 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
9936 {
9937 	struct scsi_vpd_logical_block_prov *lbp_ptr;
9938 	struct ctl_lun *lun;
9939 
9940 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9941 
9942 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
9943 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
9944 	ctsio->kern_sg_entries = 0;
9945 
9946 	if (sizeof(*lbp_ptr) < alloc_len) {
9947 		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
9948 		ctsio->kern_data_len = sizeof(*lbp_ptr);
9949 		ctsio->kern_total_len = sizeof(*lbp_ptr);
9950 	} else {
9951 		ctsio->residual = 0;
9952 		ctsio->kern_data_len = alloc_len;
9953 		ctsio->kern_total_len = alloc_len;
9954 	}
9955 	ctsio->kern_data_resid = 0;
9956 	ctsio->kern_rel_offset = 0;
9957 	ctsio->kern_sg_entries = 0;
9958 
9959 	/*
9960 	 * The control device is always connected.  The disk device, on the
9961 	 * other hand, may not be online all the time.  Need to change this
9962 	 * to figure out whether the disk device is actually online or not.
9963 	 */
9964 	if (lun != NULL)
9965 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9966 				  lun->be_lun->lun_type;
9967 	else
9968 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9969 
9970 	lbp_ptr->page_code = SVPD_LBP;
9971 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
9972 	lbp_ptr->threshold_exponent = CTL_LBP_EXPONENT;
9973 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
9974 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
9975 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
9976 		lbp_ptr->prov_type = SVPD_LBP_THIN;
9977 	}
9978 
9979 	ctl_set_success(ctsio);
9980 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9981 	ctsio->be_move_done = ctl_config_move_done;
9982 	ctl_datamove((union ctl_io *)ctsio);
9983 	return (CTL_RETVAL_COMPLETE);
9984 }
9985 
9986 /*
9987  * INQUIRY with the EVPD bit set.
9988  */
9989 static int
9990 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
9991 {
9992 	struct ctl_lun *lun;
9993 	struct scsi_inquiry *cdb;
9994 	int alloc_len, retval;
9995 
9996 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9997 	cdb = (struct scsi_inquiry *)ctsio->cdb;
9998 	alloc_len = scsi_2btoul(cdb->length);
9999 
10000 	switch (cdb->page_code) {
10001 	case SVPD_SUPPORTED_PAGES:
10002 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10003 		break;
10004 	case SVPD_UNIT_SERIAL_NUMBER:
10005 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10006 		break;
10007 	case SVPD_DEVICE_ID:
10008 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10009 		break;
10010 	case SVPD_EXTENDED_INQUIRY_DATA:
10011 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10012 		break;
10013 	case SVPD_MODE_PAGE_POLICY:
10014 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10015 		break;
10016 	case SVPD_SCSI_PORTS:
10017 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10018 		break;
10019 	case SVPD_SCSI_TPC:
10020 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10021 		break;
10022 	case SVPD_BLOCK_LIMITS:
10023 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10024 			goto err;
10025 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10026 		break;
10027 	case SVPD_BDC:
10028 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10029 			goto err;
10030 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10031 		break;
10032 	case SVPD_LBP:
10033 		if (lun == NULL || lun->be_lun->lun_type != T_DIRECT)
10034 			goto err;
10035 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10036 		break;
10037 	default:
10038 err:
10039 		ctl_set_invalid_field(ctsio,
10040 				      /*sks_valid*/ 1,
10041 				      /*command*/ 1,
10042 				      /*field*/ 2,
10043 				      /*bit_valid*/ 0,
10044 				      /*bit*/ 0);
10045 		ctl_done((union ctl_io *)ctsio);
10046 		retval = CTL_RETVAL_COMPLETE;
10047 		break;
10048 	}
10049 
10050 	return (retval);
10051 }
10052 
10053 /*
10054  * Standard INQUIRY data.
10055  */
10056 static int
10057 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10058 {
10059 	struct scsi_inquiry_data *inq_ptr;
10060 	struct scsi_inquiry *cdb;
10061 	struct ctl_softc *softc = control_softc;
10062 	struct ctl_port *port;
10063 	struct ctl_lun *lun;
10064 	char *val;
10065 	uint32_t alloc_len, data_len;
10066 	ctl_port_type port_type;
10067 
10068 	port = ctl_io_port(&ctsio->io_hdr);
10069 	port_type = port->port_type;
10070 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10071 		port_type = CTL_PORT_SCSI;
10072 
10073 	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10074 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10075 	alloc_len = scsi_2btoul(cdb->length);
10076 
10077 	/*
10078 	 * We malloc the full inquiry data size here and fill it
10079 	 * in.  If the user only asks for less, we'll give him
10080 	 * that much.
10081 	 */
10082 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10083 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10084 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10085 	ctsio->kern_sg_entries = 0;
10086 	ctsio->kern_data_resid = 0;
10087 	ctsio->kern_rel_offset = 0;
10088 
10089 	if (data_len < alloc_len) {
10090 		ctsio->residual = alloc_len - data_len;
10091 		ctsio->kern_data_len = data_len;
10092 		ctsio->kern_total_len = data_len;
10093 	} else {
10094 		ctsio->residual = 0;
10095 		ctsio->kern_data_len = alloc_len;
10096 		ctsio->kern_total_len = alloc_len;
10097 	}
10098 
10099 	if (lun != NULL) {
10100 		if ((lun->flags & CTL_LUN_PRIMARY_SC) ||
10101 		    softc->ha_link >= CTL_HA_LINK_UNKNOWN) {
10102 			inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10103 			    lun->be_lun->lun_type;
10104 		} else {
10105 			inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) |
10106 			    lun->be_lun->lun_type;
10107 		}
10108 		if (lun->flags & CTL_LUN_REMOVABLE)
10109 			inq_ptr->dev_qual2 |= SID_RMB;
10110 	} else
10111 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10112 
10113 	/* RMB in byte 2 is 0 */
10114 	inq_ptr->version = SCSI_REV_SPC4;
10115 
10116 	/*
10117 	 * According to SAM-3, even if a device only supports a single
10118 	 * level of LUN addressing, it should still set the HISUP bit:
10119 	 *
10120 	 * 4.9.1 Logical unit numbers overview
10121 	 *
10122 	 * All logical unit number formats described in this standard are
10123 	 * hierarchical in structure even when only a single level in that
10124 	 * hierarchy is used. The HISUP bit shall be set to one in the
10125 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10126 	 * format described in this standard is used.  Non-hierarchical
10127 	 * formats are outside the scope of this standard.
10128 	 *
10129 	 * Therefore we set the HiSup bit here.
10130 	 *
10131 	 * The reponse format is 2, per SPC-3.
10132 	 */
10133 	inq_ptr->response_format = SID_HiSup | 2;
10134 
10135 	inq_ptr->additional_length = data_len -
10136 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10137 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10138 			 inq_ptr->additional_length));
10139 
10140 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10141 	if (port_type == CTL_PORT_SCSI)
10142 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10143 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10144 	inq_ptr->flags = SID_CmdQue;
10145 	if (port_type == CTL_PORT_SCSI)
10146 		inq_ptr->flags |= SID_WBus16 | SID_Sync;
10147 
10148 	/*
10149 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10150 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10151 	 * name and 4 bytes for the revision.
10152 	 */
10153 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10154 	    "vendor")) == NULL) {
10155 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10156 	} else {
10157 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10158 		strncpy(inq_ptr->vendor, val,
10159 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10160 	}
10161 	if (lun == NULL) {
10162 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10163 		    sizeof(inq_ptr->product));
10164 	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10165 		switch (lun->be_lun->lun_type) {
10166 		case T_DIRECT:
10167 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10168 			    sizeof(inq_ptr->product));
10169 			break;
10170 		case T_PROCESSOR:
10171 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10172 			    sizeof(inq_ptr->product));
10173 			break;
10174 		case T_CDROM:
10175 			strncpy(inq_ptr->product, CTL_CDROM_PRODUCT,
10176 			    sizeof(inq_ptr->product));
10177 			break;
10178 		default:
10179 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10180 			    sizeof(inq_ptr->product));
10181 			break;
10182 		}
10183 	} else {
10184 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10185 		strncpy(inq_ptr->product, val,
10186 		    min(sizeof(inq_ptr->product), strlen(val)));
10187 	}
10188 
10189 	/*
10190 	 * XXX make this a macro somewhere so it automatically gets
10191 	 * incremented when we make changes.
10192 	 */
10193 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10194 	    "revision")) == NULL) {
10195 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10196 	} else {
10197 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10198 		strncpy(inq_ptr->revision, val,
10199 		    min(sizeof(inq_ptr->revision), strlen(val)));
10200 	}
10201 
10202 	/*
10203 	 * For parallel SCSI, we support double transition and single
10204 	 * transition clocking.  We also support QAS (Quick Arbitration
10205 	 * and Selection) and Information Unit transfers on both the
10206 	 * control and array devices.
10207 	 */
10208 	if (port_type == CTL_PORT_SCSI)
10209 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10210 				    SID_SPI_IUS;
10211 
10212 	/* SAM-5 (no version claimed) */
10213 	scsi_ulto2b(0x00A0, inq_ptr->version1);
10214 	/* SPC-4 (no version claimed) */
10215 	scsi_ulto2b(0x0460, inq_ptr->version2);
10216 	if (port_type == CTL_PORT_FC) {
10217 		/* FCP-2 ANSI INCITS.350:2003 */
10218 		scsi_ulto2b(0x0917, inq_ptr->version3);
10219 	} else if (port_type == CTL_PORT_SCSI) {
10220 		/* SPI-4 ANSI INCITS.362:200x */
10221 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10222 	} else if (port_type == CTL_PORT_ISCSI) {
10223 		/* iSCSI (no version claimed) */
10224 		scsi_ulto2b(0x0960, inq_ptr->version3);
10225 	} else if (port_type == CTL_PORT_SAS) {
10226 		/* SAS (no version claimed) */
10227 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10228 	}
10229 
10230 	if (lun == NULL) {
10231 		/* SBC-4 (no version claimed) */
10232 		scsi_ulto2b(0x0600, inq_ptr->version4);
10233 	} else {
10234 		switch (lun->be_lun->lun_type) {
10235 		case T_DIRECT:
10236 			/* SBC-4 (no version claimed) */
10237 			scsi_ulto2b(0x0600, inq_ptr->version4);
10238 			break;
10239 		case T_PROCESSOR:
10240 			break;
10241 		case T_CDROM:
10242 			/* MMC-6 (no version claimed) */
10243 			scsi_ulto2b(0x04E0, inq_ptr->version4);
10244 			break;
10245 		default:
10246 			break;
10247 		}
10248 	}
10249 
10250 	ctl_set_success(ctsio);
10251 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10252 	ctsio->be_move_done = ctl_config_move_done;
10253 	ctl_datamove((union ctl_io *)ctsio);
10254 	return (CTL_RETVAL_COMPLETE);
10255 }
10256 
10257 int
10258 ctl_inquiry(struct ctl_scsiio *ctsio)
10259 {
10260 	struct scsi_inquiry *cdb;
10261 	int retval;
10262 
10263 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10264 
10265 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10266 	if (cdb->byte2 & SI_EVPD)
10267 		retval = ctl_inquiry_evpd(ctsio);
10268 	else if (cdb->page_code == 0)
10269 		retval = ctl_inquiry_std(ctsio);
10270 	else {
10271 		ctl_set_invalid_field(ctsio,
10272 				      /*sks_valid*/ 1,
10273 				      /*command*/ 1,
10274 				      /*field*/ 2,
10275 				      /*bit_valid*/ 0,
10276 				      /*bit*/ 0);
10277 		ctl_done((union ctl_io *)ctsio);
10278 		return (CTL_RETVAL_COMPLETE);
10279 	}
10280 
10281 	return (retval);
10282 }
10283 
10284 int
10285 ctl_get_config(struct ctl_scsiio *ctsio)
10286 {
10287 	struct scsi_get_config_header *hdr;
10288 	struct scsi_get_config_feature *feature;
10289 	struct scsi_get_config *cdb;
10290 	struct ctl_lun *lun;
10291 	uint32_t alloc_len, data_len;
10292 	int rt, starting;
10293 
10294 	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10295 	cdb = (struct scsi_get_config *)ctsio->cdb;
10296 	rt = (cdb->rt & SGC_RT_MASK);
10297 	starting = scsi_2btoul(cdb->starting_feature);
10298 	alloc_len = scsi_2btoul(cdb->length);
10299 
10300 	data_len = sizeof(struct scsi_get_config_header) +
10301 	    sizeof(struct scsi_get_config_feature) + 8 +
10302 	    sizeof(struct scsi_get_config_feature) + 8 +
10303 	    sizeof(struct scsi_get_config_feature) + 4 +
10304 	    sizeof(struct scsi_get_config_feature) + 4 +
10305 	    sizeof(struct scsi_get_config_feature) + 8 +
10306 	    sizeof(struct scsi_get_config_feature) +
10307 	    sizeof(struct scsi_get_config_feature) + 4 +
10308 	    sizeof(struct scsi_get_config_feature) + 4 +
10309 	    sizeof(struct scsi_get_config_feature) + 4 +
10310 	    sizeof(struct scsi_get_config_feature) + 4 +
10311 	    sizeof(struct scsi_get_config_feature) + 4 +
10312 	    sizeof(struct scsi_get_config_feature) + 4;
10313 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10314 	ctsio->kern_sg_entries = 0;
10315 	ctsio->kern_data_resid = 0;
10316 	ctsio->kern_rel_offset = 0;
10317 
10318 	hdr = (struct scsi_get_config_header *)ctsio->kern_data_ptr;
10319 	if (lun->flags & CTL_LUN_NO_MEDIA)
10320 		scsi_ulto2b(0x0000, hdr->current_profile);
10321 	else
10322 		scsi_ulto2b(0x0010, hdr->current_profile);
10323 	feature = (struct scsi_get_config_feature *)(hdr + 1);
10324 
10325 	if (starting > 0x003b)
10326 		goto done;
10327 	if (starting > 0x003a)
10328 		goto f3b;
10329 	if (starting > 0x002b)
10330 		goto f3a;
10331 	if (starting > 0x002a)
10332 		goto f2b;
10333 	if (starting > 0x001f)
10334 		goto f2a;
10335 	if (starting > 0x001e)
10336 		goto f1f;
10337 	if (starting > 0x001d)
10338 		goto f1e;
10339 	if (starting > 0x0010)
10340 		goto f1d;
10341 	if (starting > 0x0003)
10342 		goto f10;
10343 	if (starting > 0x0002)
10344 		goto f3;
10345 	if (starting > 0x0001)
10346 		goto f2;
10347 	if (starting > 0x0000)
10348 		goto f1;
10349 
10350 	/* Profile List */
10351 	scsi_ulto2b(0x0000, feature->feature_code);
10352 	feature->flags = SGC_F_PERSISTENT | SGC_F_CURRENT;
10353 	feature->add_length = 8;
10354 	scsi_ulto2b(0x0008, &feature->feature_data[0]);	/* CD-ROM */
10355 	feature->feature_data[2] = 0x00;
10356 	scsi_ulto2b(0x0010, &feature->feature_data[4]);	/* DVD-ROM */
10357 	feature->feature_data[6] = 0x01;
10358 	feature = (struct scsi_get_config_feature *)
10359 	    &feature->feature_data[feature->add_length];
10360 
10361 f1:	/* Core */
10362 	scsi_ulto2b(0x0001, feature->feature_code);
10363 	feature->flags = 0x08 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10364 	feature->add_length = 8;
10365 	scsi_ulto4b(0x00000000, &feature->feature_data[0]);
10366 	feature->feature_data[4] = 0x03;
10367 	feature = (struct scsi_get_config_feature *)
10368 	    &feature->feature_data[feature->add_length];
10369 
10370 f2:	/* Morphing */
10371 	scsi_ulto2b(0x0002, feature->feature_code);
10372 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10373 	feature->add_length = 4;
10374 	feature->feature_data[0] = 0x02;
10375 	feature = (struct scsi_get_config_feature *)
10376 	    &feature->feature_data[feature->add_length];
10377 
10378 f3:	/* Removable Medium */
10379 	scsi_ulto2b(0x0003, feature->feature_code);
10380 	feature->flags = 0x04 | SGC_F_PERSISTENT | SGC_F_CURRENT;
10381 	feature->add_length = 4;
10382 	feature->feature_data[0] = 0x39;
10383 	feature = (struct scsi_get_config_feature *)
10384 	    &feature->feature_data[feature->add_length];
10385 
10386 	if (rt == SGC_RT_CURRENT && (lun->flags & CTL_LUN_NO_MEDIA))
10387 		goto done;
10388 
10389 f10:	/* Random Read */
10390 	scsi_ulto2b(0x0010, feature->feature_code);
10391 	feature->flags = 0x00;
10392 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10393 		feature->flags |= SGC_F_CURRENT;
10394 	feature->add_length = 8;
10395 	scsi_ulto4b(lun->be_lun->blocksize, &feature->feature_data[0]);
10396 	scsi_ulto2b(1, &feature->feature_data[4]);
10397 	feature->feature_data[6] = 0x00;
10398 	feature = (struct scsi_get_config_feature *)
10399 	    &feature->feature_data[feature->add_length];
10400 
10401 f1d:	/* Multi-Read */
10402 	scsi_ulto2b(0x001D, feature->feature_code);
10403 	feature->flags = 0x00;
10404 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10405 		feature->flags |= SGC_F_CURRENT;
10406 	feature->add_length = 0;
10407 	feature = (struct scsi_get_config_feature *)
10408 	    &feature->feature_data[feature->add_length];
10409 
10410 f1e:	/* CD Read */
10411 	scsi_ulto2b(0x001E, feature->feature_code);
10412 	feature->flags = 0x00;
10413 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10414 		feature->flags |= SGC_F_CURRENT;
10415 	feature->add_length = 4;
10416 	feature->feature_data[0] = 0x00;
10417 	feature = (struct scsi_get_config_feature *)
10418 	    &feature->feature_data[feature->add_length];
10419 
10420 f1f:	/* DVD Read */
10421 	scsi_ulto2b(0x001F, feature->feature_code);
10422 	feature->flags = 0x08;
10423 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10424 		feature->flags |= SGC_F_CURRENT;
10425 	feature->add_length = 4;
10426 	feature->feature_data[0] = 0x01;
10427 	feature->feature_data[2] = 0x03;
10428 	feature = (struct scsi_get_config_feature *)
10429 	    &feature->feature_data[feature->add_length];
10430 
10431 f2a:	/* DVD+RW */
10432 	scsi_ulto2b(0x002A, feature->feature_code);
10433 	feature->flags = 0x04;
10434 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10435 		feature->flags |= SGC_F_CURRENT;
10436 	feature->add_length = 4;
10437 	feature->feature_data[0] = 0x00;
10438 	feature->feature_data[1] = 0x00;
10439 	feature = (struct scsi_get_config_feature *)
10440 	    &feature->feature_data[feature->add_length];
10441 
10442 f2b:	/* DVD+R */
10443 	scsi_ulto2b(0x002B, feature->feature_code);
10444 	feature->flags = 0x00;
10445 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10446 		feature->flags |= SGC_F_CURRENT;
10447 	feature->add_length = 4;
10448 	feature->feature_data[0] = 0x00;
10449 	feature = (struct scsi_get_config_feature *)
10450 	    &feature->feature_data[feature->add_length];
10451 
10452 f3a:	/* DVD+RW Dual Layer */
10453 	scsi_ulto2b(0x003A, feature->feature_code);
10454 	feature->flags = 0x00;
10455 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10456 		feature->flags |= SGC_F_CURRENT;
10457 	feature->add_length = 4;
10458 	feature->feature_data[0] = 0x00;
10459 	feature->feature_data[1] = 0x00;
10460 	feature = (struct scsi_get_config_feature *)
10461 	    &feature->feature_data[feature->add_length];
10462 
10463 f3b:	/* DVD+R Dual Layer */
10464 	scsi_ulto2b(0x003B, feature->feature_code);
10465 	feature->flags = 0x00;
10466 	if ((lun->flags & CTL_LUN_NO_MEDIA) == 0)
10467 		feature->flags |= SGC_F_CURRENT;
10468 	feature->add_length = 4;
10469 	feature->feature_data[0] = 0x00;
10470 	feature = (struct scsi_get_config_feature *)
10471 	    &feature->feature_data[feature->add_length];
10472 
10473 done:
10474 	data_len = (uint8_t *)feature - (uint8_t *)hdr;
10475 	if (rt == SGC_RT_SPECIFIC && data_len > 4) {
10476 		feature = (struct scsi_get_config_feature *)(hdr + 1);
10477 		if (scsi_2btoul(feature->feature_code) == starting)
10478 			feature = (struct scsi_get_config_feature *)
10479 			    &feature->feature_data[feature->add_length];
10480 		data_len = (uint8_t *)feature - (uint8_t *)hdr;
10481 	}
10482 	scsi_ulto4b(data_len - 4, hdr->data_length);
10483 	if (data_len < alloc_len) {
10484 		ctsio->residual = alloc_len - data_len;
10485 		ctsio->kern_data_len = data_len;
10486 		ctsio->kern_total_len = data_len;
10487 	} else {
10488 		ctsio->residual = 0;
10489 		ctsio->kern_data_len = alloc_len;
10490 		ctsio->kern_total_len = alloc_len;
10491 	}
10492 
10493 	ctl_set_success(ctsio);
10494 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10495 	ctsio->be_move_done = ctl_config_move_done;
10496 	ctl_datamove((union ctl_io *)ctsio);
10497 	return (CTL_RETVAL_COMPLETE);
10498 }
10499 
10500 int
10501 ctl_get_event_status(struct ctl_scsiio *ctsio)
10502 {
10503 	struct scsi_get_event_status_header *hdr;
10504 	struct scsi_get_event_status *cdb;
10505 	struct ctl_lun *lun;
10506 	uint32_t alloc_len, data_len;
10507 	int notif_class;
10508 
10509 	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10510 	cdb = (struct scsi_get_event_status *)ctsio->cdb;
10511 	if ((cdb->byte2 & SGESN_POLLED) == 0) {
10512 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1, /*command*/ 1,
10513 		    /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
10514 		ctl_done((union ctl_io *)ctsio);
10515 		return (CTL_RETVAL_COMPLETE);
10516 	}
10517 	notif_class = cdb->notif_class;
10518 	alloc_len = scsi_2btoul(cdb->length);
10519 
10520 	data_len = sizeof(struct scsi_get_event_status_header);
10521 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10522 	ctsio->kern_sg_entries = 0;
10523 	ctsio->kern_data_resid = 0;
10524 	ctsio->kern_rel_offset = 0;
10525 
10526 	if (data_len < alloc_len) {
10527 		ctsio->residual = alloc_len - data_len;
10528 		ctsio->kern_data_len = data_len;
10529 		ctsio->kern_total_len = data_len;
10530 	} else {
10531 		ctsio->residual = 0;
10532 		ctsio->kern_data_len = alloc_len;
10533 		ctsio->kern_total_len = alloc_len;
10534 	}
10535 
10536 	hdr = (struct scsi_get_event_status_header *)ctsio->kern_data_ptr;
10537 	scsi_ulto2b(0, hdr->descr_length);
10538 	hdr->nea_class = SGESN_NEA;
10539 	hdr->supported_class = 0;
10540 
10541 	ctl_set_success(ctsio);
10542 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10543 	ctsio->be_move_done = ctl_config_move_done;
10544 	ctl_datamove((union ctl_io *)ctsio);
10545 	return (CTL_RETVAL_COMPLETE);
10546 }
10547 
10548 int
10549 ctl_mechanism_status(struct ctl_scsiio *ctsio)
10550 {
10551 	struct scsi_mechanism_status_header *hdr;
10552 	struct scsi_mechanism_status *cdb;
10553 	struct ctl_lun *lun;
10554 	uint32_t alloc_len, data_len;
10555 
10556 	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10557 	cdb = (struct scsi_mechanism_status *)ctsio->cdb;
10558 	alloc_len = scsi_2btoul(cdb->length);
10559 
10560 	data_len = sizeof(struct scsi_mechanism_status_header);
10561 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10562 	ctsio->kern_sg_entries = 0;
10563 	ctsio->kern_data_resid = 0;
10564 	ctsio->kern_rel_offset = 0;
10565 
10566 	if (data_len < alloc_len) {
10567 		ctsio->residual = alloc_len - data_len;
10568 		ctsio->kern_data_len = data_len;
10569 		ctsio->kern_total_len = data_len;
10570 	} else {
10571 		ctsio->residual = 0;
10572 		ctsio->kern_data_len = alloc_len;
10573 		ctsio->kern_total_len = alloc_len;
10574 	}
10575 
10576 	hdr = (struct scsi_mechanism_status_header *)ctsio->kern_data_ptr;
10577 	hdr->state1 = 0x00;
10578 	hdr->state2 = 0xe0;
10579 	scsi_ulto3b(0, hdr->lba);
10580 	hdr->slots_num = 0;
10581 	scsi_ulto2b(0, hdr->slots_length);
10582 
10583 	ctl_set_success(ctsio);
10584 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10585 	ctsio->be_move_done = ctl_config_move_done;
10586 	ctl_datamove((union ctl_io *)ctsio);
10587 	return (CTL_RETVAL_COMPLETE);
10588 }
10589 
10590 static void
10591 ctl_ultomsf(uint32_t lba, uint8_t *buf)
10592 {
10593 
10594 	lba += 150;
10595 	buf[0] = 0;
10596 	buf[1] = bin2bcd((lba / 75) / 60);
10597 	buf[2] = bin2bcd((lba / 75) % 60);
10598 	buf[3] = bin2bcd(lba % 75);
10599 }
10600 
10601 int
10602 ctl_read_toc(struct ctl_scsiio *ctsio)
10603 {
10604 	struct scsi_read_toc_hdr *hdr;
10605 	struct scsi_read_toc_type01_descr *descr;
10606 	struct scsi_read_toc *cdb;
10607 	struct ctl_lun *lun;
10608 	uint32_t alloc_len, data_len;
10609 	int format, msf;
10610 
10611 	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10612 	cdb = (struct scsi_read_toc *)ctsio->cdb;
10613 	msf = (cdb->byte2 & CD_MSF) != 0;
10614 	format = cdb->format;
10615 	alloc_len = scsi_2btoul(cdb->data_len);
10616 
10617 	data_len = sizeof(struct scsi_read_toc_hdr);
10618 	if (format == 0)
10619 		data_len += 2 * sizeof(struct scsi_read_toc_type01_descr);
10620 	else
10621 		data_len += sizeof(struct scsi_read_toc_type01_descr);
10622 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10623 	ctsio->kern_sg_entries = 0;
10624 	ctsio->kern_data_resid = 0;
10625 	ctsio->kern_rel_offset = 0;
10626 
10627 	if (data_len < alloc_len) {
10628 		ctsio->residual = alloc_len - data_len;
10629 		ctsio->kern_data_len = data_len;
10630 		ctsio->kern_total_len = data_len;
10631 	} else {
10632 		ctsio->residual = 0;
10633 		ctsio->kern_data_len = alloc_len;
10634 		ctsio->kern_total_len = alloc_len;
10635 	}
10636 
10637 	hdr = (struct scsi_read_toc_hdr *)ctsio->kern_data_ptr;
10638 	if (format == 0) {
10639 		scsi_ulto2b(0x12, hdr->data_length);
10640 		hdr->first = 1;
10641 		hdr->last = 1;
10642 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10643 		descr->addr_ctl = 0x14;
10644 		descr->track_number = 1;
10645 		if (msf)
10646 			ctl_ultomsf(0, descr->track_start);
10647 		else
10648 			scsi_ulto4b(0, descr->track_start);
10649 		descr++;
10650 		descr->addr_ctl = 0x14;
10651 		descr->track_number = 0xaa;
10652 		if (msf)
10653 			ctl_ultomsf(lun->be_lun->maxlba+1, descr->track_start);
10654 		else
10655 			scsi_ulto4b(lun->be_lun->maxlba+1, descr->track_start);
10656 	} else {
10657 		scsi_ulto2b(0x0a, hdr->data_length);
10658 		hdr->first = 1;
10659 		hdr->last = 1;
10660 		descr = (struct scsi_read_toc_type01_descr *)(hdr + 1);
10661 		descr->addr_ctl = 0x14;
10662 		descr->track_number = 1;
10663 		if (msf)
10664 			ctl_ultomsf(0, descr->track_start);
10665 		else
10666 			scsi_ulto4b(0, descr->track_start);
10667 	}
10668 
10669 	ctl_set_success(ctsio);
10670 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10671 	ctsio->be_move_done = ctl_config_move_done;
10672 	ctl_datamove((union ctl_io *)ctsio);
10673 	return (CTL_RETVAL_COMPLETE);
10674 }
10675 
10676 /*
10677  * For known CDB types, parse the LBA and length.
10678  */
10679 static int
10680 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10681 {
10682 	if (io->io_hdr.io_type != CTL_IO_SCSI)
10683 		return (1);
10684 
10685 	switch (io->scsiio.cdb[0]) {
10686 	case COMPARE_AND_WRITE: {
10687 		struct scsi_compare_and_write *cdb;
10688 
10689 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10690 
10691 		*lba = scsi_8btou64(cdb->addr);
10692 		*len = cdb->length;
10693 		break;
10694 	}
10695 	case READ_6:
10696 	case WRITE_6: {
10697 		struct scsi_rw_6 *cdb;
10698 
10699 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10700 
10701 		*lba = scsi_3btoul(cdb->addr);
10702 		/* only 5 bits are valid in the most significant address byte */
10703 		*lba &= 0x1fffff;
10704 		*len = cdb->length;
10705 		break;
10706 	}
10707 	case READ_10:
10708 	case WRITE_10: {
10709 		struct scsi_rw_10 *cdb;
10710 
10711 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10712 
10713 		*lba = scsi_4btoul(cdb->addr);
10714 		*len = scsi_2btoul(cdb->length);
10715 		break;
10716 	}
10717 	case WRITE_VERIFY_10: {
10718 		struct scsi_write_verify_10 *cdb;
10719 
10720 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10721 
10722 		*lba = scsi_4btoul(cdb->addr);
10723 		*len = scsi_2btoul(cdb->length);
10724 		break;
10725 	}
10726 	case READ_12:
10727 	case WRITE_12: {
10728 		struct scsi_rw_12 *cdb;
10729 
10730 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10731 
10732 		*lba = scsi_4btoul(cdb->addr);
10733 		*len = scsi_4btoul(cdb->length);
10734 		break;
10735 	}
10736 	case WRITE_VERIFY_12: {
10737 		struct scsi_write_verify_12 *cdb;
10738 
10739 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10740 
10741 		*lba = scsi_4btoul(cdb->addr);
10742 		*len = scsi_4btoul(cdb->length);
10743 		break;
10744 	}
10745 	case READ_16:
10746 	case WRITE_16: {
10747 		struct scsi_rw_16 *cdb;
10748 
10749 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10750 
10751 		*lba = scsi_8btou64(cdb->addr);
10752 		*len = scsi_4btoul(cdb->length);
10753 		break;
10754 	}
10755 	case WRITE_ATOMIC_16: {
10756 		struct scsi_write_atomic_16 *cdb;
10757 
10758 		cdb = (struct scsi_write_atomic_16 *)io->scsiio.cdb;
10759 
10760 		*lba = scsi_8btou64(cdb->addr);
10761 		*len = scsi_2btoul(cdb->length);
10762 		break;
10763 	}
10764 	case WRITE_VERIFY_16: {
10765 		struct scsi_write_verify_16 *cdb;
10766 
10767 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10768 
10769 		*lba = scsi_8btou64(cdb->addr);
10770 		*len = scsi_4btoul(cdb->length);
10771 		break;
10772 	}
10773 	case WRITE_SAME_10: {
10774 		struct scsi_write_same_10 *cdb;
10775 
10776 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10777 
10778 		*lba = scsi_4btoul(cdb->addr);
10779 		*len = scsi_2btoul(cdb->length);
10780 		break;
10781 	}
10782 	case WRITE_SAME_16: {
10783 		struct scsi_write_same_16 *cdb;
10784 
10785 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10786 
10787 		*lba = scsi_8btou64(cdb->addr);
10788 		*len = scsi_4btoul(cdb->length);
10789 		break;
10790 	}
10791 	case VERIFY_10: {
10792 		struct scsi_verify_10 *cdb;
10793 
10794 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10795 
10796 		*lba = scsi_4btoul(cdb->addr);
10797 		*len = scsi_2btoul(cdb->length);
10798 		break;
10799 	}
10800 	case VERIFY_12: {
10801 		struct scsi_verify_12 *cdb;
10802 
10803 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10804 
10805 		*lba = scsi_4btoul(cdb->addr);
10806 		*len = scsi_4btoul(cdb->length);
10807 		break;
10808 	}
10809 	case VERIFY_16: {
10810 		struct scsi_verify_16 *cdb;
10811 
10812 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10813 
10814 		*lba = scsi_8btou64(cdb->addr);
10815 		*len = scsi_4btoul(cdb->length);
10816 		break;
10817 	}
10818 	case UNMAP: {
10819 		*lba = 0;
10820 		*len = UINT64_MAX;
10821 		break;
10822 	}
10823 	case SERVICE_ACTION_IN: {	/* GET LBA STATUS */
10824 		struct scsi_get_lba_status *cdb;
10825 
10826 		cdb = (struct scsi_get_lba_status *)io->scsiio.cdb;
10827 		*lba = scsi_8btou64(cdb->addr);
10828 		*len = UINT32_MAX;
10829 		break;
10830 	}
10831 	default:
10832 		return (1);
10833 		break; /* NOTREACHED */
10834 	}
10835 
10836 	return (0);
10837 }
10838 
10839 static ctl_action
10840 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2,
10841     bool seq)
10842 {
10843 	uint64_t endlba1, endlba2;
10844 
10845 	endlba1 = lba1 + len1 - (seq ? 0 : 1);
10846 	endlba2 = lba2 + len2 - 1;
10847 
10848 	if ((endlba1 < lba2) || (endlba2 < lba1))
10849 		return (CTL_ACTION_PASS);
10850 	else
10851 		return (CTL_ACTION_BLOCK);
10852 }
10853 
10854 static int
10855 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10856 {
10857 	struct ctl_ptr_len_flags *ptrlen;
10858 	struct scsi_unmap_desc *buf, *end, *range;
10859 	uint64_t lba;
10860 	uint32_t len;
10861 
10862 	/* If not UNMAP -- go other way. */
10863 	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10864 	    io->scsiio.cdb[0] != UNMAP)
10865 		return (CTL_ACTION_ERROR);
10866 
10867 	/* If UNMAP without data -- block and wait for data. */
10868 	ptrlen = (struct ctl_ptr_len_flags *)
10869 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10870 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10871 	    ptrlen->ptr == NULL)
10872 		return (CTL_ACTION_BLOCK);
10873 
10874 	/* UNMAP with data -- check for collision. */
10875 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10876 	end = buf + ptrlen->len / sizeof(*buf);
10877 	for (range = buf; range < end; range++) {
10878 		lba = scsi_8btou64(range->lba);
10879 		len = scsi_4btoul(range->length);
10880 		if ((lba < lba2 + len2) && (lba + len > lba2))
10881 			return (CTL_ACTION_BLOCK);
10882 	}
10883 	return (CTL_ACTION_PASS);
10884 }
10885 
10886 static ctl_action
10887 ctl_extent_check(union ctl_io *io1, union ctl_io *io2, bool seq)
10888 {
10889 	uint64_t lba1, lba2;
10890 	uint64_t len1, len2;
10891 	int retval;
10892 
10893 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10894 		return (CTL_ACTION_ERROR);
10895 
10896 	retval = ctl_extent_check_unmap(io1, lba2, len2);
10897 	if (retval != CTL_ACTION_ERROR)
10898 		return (retval);
10899 
10900 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10901 		return (CTL_ACTION_ERROR);
10902 
10903 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10904 		seq = FALSE;
10905 	return (ctl_extent_check_lba(lba1, len1, lba2, len2, seq));
10906 }
10907 
10908 static ctl_action
10909 ctl_extent_check_seq(union ctl_io *io1, union ctl_io *io2)
10910 {
10911 	uint64_t lba1, lba2;
10912 	uint64_t len1, len2;
10913 
10914 	if (io1->io_hdr.flags & CTL_FLAG_SERSEQ_DONE)
10915 		return (CTL_ACTION_PASS);
10916 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
10917 		return (CTL_ACTION_ERROR);
10918 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
10919 		return (CTL_ACTION_ERROR);
10920 
10921 	if (lba1 + len1 == lba2)
10922 		return (CTL_ACTION_BLOCK);
10923 	return (CTL_ACTION_PASS);
10924 }
10925 
10926 static ctl_action
10927 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
10928     union ctl_io *ooa_io)
10929 {
10930 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
10931 	const ctl_serialize_action *serialize_row;
10932 
10933 	/*
10934 	 * The initiator attempted multiple untagged commands at the same
10935 	 * time.  Can't do that.
10936 	 */
10937 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10938 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
10939 	 && ((pending_io->io_hdr.nexus.targ_port ==
10940 	      ooa_io->io_hdr.nexus.targ_port)
10941 	  && (pending_io->io_hdr.nexus.initid ==
10942 	      ooa_io->io_hdr.nexus.initid))
10943 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10944 	      CTL_FLAG_STATUS_SENT)) == 0))
10945 		return (CTL_ACTION_OVERLAP);
10946 
10947 	/*
10948 	 * The initiator attempted to send multiple tagged commands with
10949 	 * the same ID.  (It's fine if different initiators have the same
10950 	 * tag ID.)
10951 	 *
10952 	 * Even if all of those conditions are true, we don't kill the I/O
10953 	 * if the command ahead of us has been aborted.  We won't end up
10954 	 * sending it to the FETD, and it's perfectly legal to resend a
10955 	 * command with the same tag number as long as the previous
10956 	 * instance of this tag number has been aborted somehow.
10957 	 */
10958 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10959 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
10960 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
10961 	 && ((pending_io->io_hdr.nexus.targ_port ==
10962 	      ooa_io->io_hdr.nexus.targ_port)
10963 	  && (pending_io->io_hdr.nexus.initid ==
10964 	      ooa_io->io_hdr.nexus.initid))
10965 	 && ((ooa_io->io_hdr.flags & (CTL_FLAG_ABORT |
10966 	      CTL_FLAG_STATUS_SENT)) == 0))
10967 		return (CTL_ACTION_OVERLAP_TAG);
10968 
10969 	/*
10970 	 * If we get a head of queue tag, SAM-3 says that we should
10971 	 * immediately execute it.
10972 	 *
10973 	 * What happens if this command would normally block for some other
10974 	 * reason?  e.g. a request sense with a head of queue tag
10975 	 * immediately after a write.  Normally that would block, but this
10976 	 * will result in its getting executed immediately...
10977 	 *
10978 	 * We currently return "pass" instead of "skip", so we'll end up
10979 	 * going through the rest of the queue to check for overlapped tags.
10980 	 *
10981 	 * XXX KDM check for other types of blockage first??
10982 	 */
10983 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
10984 		return (CTL_ACTION_PASS);
10985 
10986 	/*
10987 	 * Ordered tags have to block until all items ahead of them
10988 	 * have completed.  If we get called with an ordered tag, we always
10989 	 * block, if something else is ahead of us in the queue.
10990 	 */
10991 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
10992 		return (CTL_ACTION_BLOCK);
10993 
10994 	/*
10995 	 * Simple tags get blocked until all head of queue and ordered tags
10996 	 * ahead of them have completed.  I'm lumping untagged commands in
10997 	 * with simple tags here.  XXX KDM is that the right thing to do?
10998 	 */
10999 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11000 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11001 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11002 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11003 		return (CTL_ACTION_BLOCK);
11004 
11005 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11006 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11007 
11008 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11009 
11010 	switch (serialize_row[pending_entry->seridx]) {
11011 	case CTL_SER_BLOCK:
11012 		return (CTL_ACTION_BLOCK);
11013 	case CTL_SER_EXTENT:
11014 		return (ctl_extent_check(ooa_io, pending_io,
11015 		    (lun->be_lun && lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11016 	case CTL_SER_EXTENTOPT:
11017 		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11018 		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11019 			return (ctl_extent_check(ooa_io, pending_io,
11020 			    (lun->be_lun &&
11021 			     lun->be_lun->serseq == CTL_LUN_SERSEQ_ON)));
11022 		return (CTL_ACTION_PASS);
11023 	case CTL_SER_EXTENTSEQ:
11024 		if (lun->be_lun && lun->be_lun->serseq != CTL_LUN_SERSEQ_OFF)
11025 			return (ctl_extent_check_seq(ooa_io, pending_io));
11026 		return (CTL_ACTION_PASS);
11027 	case CTL_SER_PASS:
11028 		return (CTL_ACTION_PASS);
11029 	case CTL_SER_BLOCKOPT:
11030 		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11031 		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11032 			return (CTL_ACTION_BLOCK);
11033 		return (CTL_ACTION_PASS);
11034 	case CTL_SER_SKIP:
11035 		return (CTL_ACTION_SKIP);
11036 	default:
11037 		panic("%s: Invalid serialization value %d for %d => %d",
11038 		    __func__, serialize_row[pending_entry->seridx],
11039 		    pending_entry->seridx, ooa_entry->seridx);
11040 	}
11041 
11042 	return (CTL_ACTION_ERROR);
11043 }
11044 
11045 /*
11046  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11047  * Assumptions:
11048  * - pending_io is generally either incoming, or on the blocked queue
11049  * - starting I/O is the I/O we want to start the check with.
11050  */
11051 static ctl_action
11052 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11053 	      union ctl_io *starting_io)
11054 {
11055 	union ctl_io *ooa_io;
11056 	ctl_action action;
11057 
11058 	mtx_assert(&lun->lun_lock, MA_OWNED);
11059 
11060 	/*
11061 	 * Run back along the OOA queue, starting with the current
11062 	 * blocked I/O and going through every I/O before it on the
11063 	 * queue.  If starting_io is NULL, we'll just end up returning
11064 	 * CTL_ACTION_PASS.
11065 	 */
11066 	for (ooa_io = starting_io; ooa_io != NULL;
11067 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11068 	     ooa_links)){
11069 
11070 		/*
11071 		 * This routine just checks to see whether
11072 		 * cur_blocked is blocked by ooa_io, which is ahead
11073 		 * of it in the queue.  It doesn't queue/dequeue
11074 		 * cur_blocked.
11075 		 */
11076 		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11077 		switch (action) {
11078 		case CTL_ACTION_BLOCK:
11079 		case CTL_ACTION_OVERLAP:
11080 		case CTL_ACTION_OVERLAP_TAG:
11081 		case CTL_ACTION_SKIP:
11082 		case CTL_ACTION_ERROR:
11083 			return (action);
11084 			break; /* NOTREACHED */
11085 		case CTL_ACTION_PASS:
11086 			break;
11087 		default:
11088 			panic("%s: Invalid action %d\n", __func__, action);
11089 		}
11090 	}
11091 
11092 	return (CTL_ACTION_PASS);
11093 }
11094 
11095 /*
11096  * Assumptions:
11097  * - An I/O has just completed, and has been removed from the per-LUN OOA
11098  *   queue, so some items on the blocked queue may now be unblocked.
11099  */
11100 static int
11101 ctl_check_blocked(struct ctl_lun *lun)
11102 {
11103 	struct ctl_softc *softc = lun->ctl_softc;
11104 	union ctl_io *cur_blocked, *next_blocked;
11105 
11106 	mtx_assert(&lun->lun_lock, MA_OWNED);
11107 
11108 	/*
11109 	 * Run forward from the head of the blocked queue, checking each
11110 	 * entry against the I/Os prior to it on the OOA queue to see if
11111 	 * there is still any blockage.
11112 	 *
11113 	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11114 	 * with our removing a variable on it while it is traversing the
11115 	 * list.
11116 	 */
11117 	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11118 	     cur_blocked != NULL; cur_blocked = next_blocked) {
11119 		union ctl_io *prev_ooa;
11120 		ctl_action action;
11121 
11122 		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11123 							  blocked_links);
11124 
11125 		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11126 						      ctl_ooaq, ooa_links);
11127 
11128 		/*
11129 		 * If cur_blocked happens to be the first item in the OOA
11130 		 * queue now, prev_ooa will be NULL, and the action
11131 		 * returned will just be CTL_ACTION_PASS.
11132 		 */
11133 		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11134 
11135 		switch (action) {
11136 		case CTL_ACTION_BLOCK:
11137 			/* Nothing to do here, still blocked */
11138 			break;
11139 		case CTL_ACTION_OVERLAP:
11140 		case CTL_ACTION_OVERLAP_TAG:
11141 			/*
11142 			 * This shouldn't happen!  In theory we've already
11143 			 * checked this command for overlap...
11144 			 */
11145 			break;
11146 		case CTL_ACTION_PASS:
11147 		case CTL_ACTION_SKIP: {
11148 			const struct ctl_cmd_entry *entry;
11149 
11150 			/*
11151 			 * The skip case shouldn't happen, this transaction
11152 			 * should have never made it onto the blocked queue.
11153 			 */
11154 			/*
11155 			 * This I/O is no longer blocked, we can remove it
11156 			 * from the blocked queue.  Since this is a TAILQ
11157 			 * (doubly linked list), we can do O(1) removals
11158 			 * from any place on the list.
11159 			 */
11160 			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11161 				     blocked_links);
11162 			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11163 
11164 			if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
11165 			    (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)){
11166 				/*
11167 				 * Need to send IO back to original side to
11168 				 * run
11169 				 */
11170 				union ctl_ha_msg msg_info;
11171 
11172 				cur_blocked->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11173 				msg_info.hdr.original_sc =
11174 					cur_blocked->io_hdr.original_sc;
11175 				msg_info.hdr.serializing_sc = cur_blocked;
11176 				msg_info.hdr.msg_type = CTL_MSG_R2R;
11177 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11178 				    sizeof(msg_info.hdr), M_NOWAIT);
11179 				break;
11180 			}
11181 			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11182 
11183 			/*
11184 			 * Check this I/O for LUN state changes that may
11185 			 * have happened while this command was blocked.
11186 			 * The LUN state may have been changed by a command
11187 			 * ahead of us in the queue, so we need to re-check
11188 			 * for any states that can be caused by SCSI
11189 			 * commands.
11190 			 */
11191 			if (ctl_scsiio_lun_check(lun, entry,
11192 						 &cur_blocked->scsiio) == 0) {
11193 				cur_blocked->io_hdr.flags |=
11194 				                      CTL_FLAG_IS_WAS_ON_RTR;
11195 				ctl_enqueue_rtr(cur_blocked);
11196 			} else
11197 				ctl_done(cur_blocked);
11198 			break;
11199 		}
11200 		default:
11201 			/*
11202 			 * This probably shouldn't happen -- we shouldn't
11203 			 * get CTL_ACTION_ERROR, or anything else.
11204 			 */
11205 			break;
11206 		}
11207 	}
11208 
11209 	return (CTL_RETVAL_COMPLETE);
11210 }
11211 
11212 /*
11213  * This routine (with one exception) checks LUN flags that can be set by
11214  * commands ahead of us in the OOA queue.  These flags have to be checked
11215  * when a command initially comes in, and when we pull a command off the
11216  * blocked queue and are preparing to execute it.  The reason we have to
11217  * check these flags for commands on the blocked queue is that the LUN
11218  * state may have been changed by a command ahead of us while we're on the
11219  * blocked queue.
11220  *
11221  * Ordering is somewhat important with these checks, so please pay
11222  * careful attention to the placement of any new checks.
11223  */
11224 static int
11225 ctl_scsiio_lun_check(struct ctl_lun *lun,
11226     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11227 {
11228 	struct ctl_softc *softc = lun->ctl_softc;
11229 	int retval;
11230 	uint32_t residx;
11231 
11232 	retval = 0;
11233 
11234 	mtx_assert(&lun->lun_lock, MA_OWNED);
11235 
11236 	/*
11237 	 * If this shelf is a secondary shelf controller, we may have to
11238 	 * reject some commands disallowed by HA mode and link state.
11239 	 */
11240 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11241 		if (softc->ha_link == CTL_HA_LINK_OFFLINE &&
11242 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11243 			ctl_set_lun_unavail(ctsio);
11244 			retval = 1;
11245 			goto bailout;
11246 		}
11247 		if ((lun->flags & CTL_LUN_PEER_SC_PRIMARY) == 0 &&
11248 		    (entry->flags & CTL_CMD_FLAG_OK_ON_UNAVAIL) == 0) {
11249 			ctl_set_lun_transit(ctsio);
11250 			retval = 1;
11251 			goto bailout;
11252 		}
11253 		if (softc->ha_mode == CTL_HA_MODE_ACT_STBY &&
11254 		    (entry->flags & CTL_CMD_FLAG_OK_ON_STANDBY) == 0) {
11255 			ctl_set_lun_standby(ctsio);
11256 			retval = 1;
11257 			goto bailout;
11258 		}
11259 
11260 		/* The rest of checks are only done on executing side */
11261 		if (softc->ha_mode == CTL_HA_MODE_XFER)
11262 			goto bailout;
11263 	}
11264 
11265 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11266 		if (lun->be_lun &&
11267 		    lun->be_lun->flags & CTL_LUN_FLAG_READONLY) {
11268 			ctl_set_hw_write_protected(ctsio);
11269 			retval = 1;
11270 			goto bailout;
11271 		}
11272 		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11273 		    .eca_and_aen & SCP_SWP) != 0) {
11274 			ctl_set_sense(ctsio, /*current_error*/ 1,
11275 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11276 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11277 			retval = 1;
11278 			goto bailout;
11279 		}
11280 	}
11281 
11282 	/*
11283 	 * Check for a reservation conflict.  If this command isn't allowed
11284 	 * even on reserved LUNs, and if this initiator isn't the one who
11285 	 * reserved us, reject the command with a reservation conflict.
11286 	 */
11287 	residx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11288 	if ((lun->flags & CTL_LUN_RESERVED)
11289 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11290 		if (lun->res_idx != residx) {
11291 			ctl_set_reservation_conflict(ctsio);
11292 			retval = 1;
11293 			goto bailout;
11294 		}
11295 	}
11296 
11297 	if ((lun->flags & CTL_LUN_PR_RESERVED) == 0 ||
11298 	    (entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV)) {
11299 		/* No reservation or command is allowed. */;
11300 	} else if ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_WRESV) &&
11301 	    (lun->pr_res_type == SPR_TYPE_WR_EX ||
11302 	     lun->pr_res_type == SPR_TYPE_WR_EX_RO ||
11303 	     lun->pr_res_type == SPR_TYPE_WR_EX_AR)) {
11304 		/* The command is allowed for Write Exclusive resv. */;
11305 	} else {
11306 		/*
11307 		 * if we aren't registered or it's a res holder type
11308 		 * reservation and this isn't the res holder then set a
11309 		 * conflict.
11310 		 */
11311 		if (ctl_get_prkey(lun, residx) == 0 ||
11312 		    (residx != lun->pr_res_idx && lun->pr_res_type < 4)) {
11313 			ctl_set_reservation_conflict(ctsio);
11314 			retval = 1;
11315 			goto bailout;
11316 		}
11317 	}
11318 
11319 	if ((entry->flags & CTL_CMD_FLAG_OK_ON_NO_MEDIA) == 0) {
11320 		if (lun->flags & CTL_LUN_EJECTED)
11321 			ctl_set_lun_ejected(ctsio);
11322 		else if (lun->flags & CTL_LUN_NO_MEDIA) {
11323 			if (lun->flags & CTL_LUN_REMOVABLE)
11324 				ctl_set_lun_no_media(ctsio);
11325 			else
11326 				ctl_set_lun_int_reqd(ctsio);
11327 		} else if (lun->flags & CTL_LUN_STOPPED)
11328 			ctl_set_lun_stopped(ctsio);
11329 		else
11330 			goto bailout;
11331 		retval = 1;
11332 		goto bailout;
11333 	}
11334 
11335 bailout:
11336 	return (retval);
11337 }
11338 
11339 static void
11340 ctl_failover_io(union ctl_io *io, int have_lock)
11341 {
11342 	ctl_set_busy(&io->scsiio);
11343 	ctl_done(io);
11344 }
11345 
11346 static void
11347 ctl_failover_lun(union ctl_io *rio)
11348 {
11349 	struct ctl_softc *softc = control_softc;
11350 	struct ctl_lun *lun;
11351 	struct ctl_io_hdr *io, *next_io;
11352 	uint32_t targ_lun;
11353 
11354 	targ_lun = rio->io_hdr.nexus.targ_mapped_lun;
11355 	CTL_DEBUG_PRINT(("FAILOVER for lun %ju\n", targ_lun));
11356 
11357 	/* Find and lock the LUN. */
11358 	mtx_lock(&softc->ctl_lock);
11359 	if ((targ_lun < CTL_MAX_LUNS) &&
11360 	    ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11361 		mtx_lock(&lun->lun_lock);
11362 		mtx_unlock(&softc->ctl_lock);
11363 		if (lun->flags & CTL_LUN_DISABLED) {
11364 			mtx_unlock(&lun->lun_lock);
11365 			return;
11366 		}
11367 	} else {
11368 		mtx_unlock(&softc->ctl_lock);
11369 		return;
11370 	}
11371 
11372 	if (softc->ha_mode == CTL_HA_MODE_XFER) {
11373 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11374 			/* We are master */
11375 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11376 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11377 					io->flags |= CTL_FLAG_ABORT;
11378 					io->flags |= CTL_FLAG_FAILOVER;
11379 				} else { /* This can be only due to DATAMOVE */
11380 					io->msg_type = CTL_MSG_DATAMOVE_DONE;
11381 					io->flags &= ~CTL_FLAG_DMA_INPROG;
11382 					io->flags |= CTL_FLAG_IO_ACTIVE;
11383 					io->port_status = 31340;
11384 					ctl_enqueue_isc((union ctl_io *)io);
11385 				}
11386 			}
11387 			/* We are slave */
11388 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11389 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11390 				if (io->flags & CTL_FLAG_IO_ACTIVE) {
11391 					io->flags |= CTL_FLAG_FAILOVER;
11392 				} else {
11393 					ctl_set_busy(&((union ctl_io *)io)->
11394 					    scsiio);
11395 					ctl_done((union ctl_io *)io);
11396 				}
11397 			}
11398 		}
11399 	} else { /* SERIALIZE modes */
11400 		TAILQ_FOREACH_SAFE(io, &lun->blocked_queue, blocked_links,
11401 		    next_io) {
11402 			/* We are master */
11403 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11404 				TAILQ_REMOVE(&lun->blocked_queue, io,
11405 				    blocked_links);
11406 				io->flags &= ~CTL_FLAG_BLOCKED;
11407 				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11408 				ctl_free_io((union ctl_io *)io);
11409 			}
11410 		}
11411 		TAILQ_FOREACH_SAFE(io, &lun->ooa_queue, ooa_links, next_io) {
11412 			/* We are master */
11413 			if (io->flags & CTL_FLAG_FROM_OTHER_SC) {
11414 				TAILQ_REMOVE(&lun->ooa_queue, io, ooa_links);
11415 				ctl_free_io((union ctl_io *)io);
11416 			}
11417 			/* We are slave */
11418 			if (io->flags & CTL_FLAG_SENT_2OTHER_SC) {
11419 				io->flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11420 				if (!(io->flags & CTL_FLAG_IO_ACTIVE)) {
11421 					ctl_set_busy(&((union ctl_io *)io)->
11422 					    scsiio);
11423 					ctl_done((union ctl_io *)io);
11424 				}
11425 			}
11426 		}
11427 		ctl_check_blocked(lun);
11428 	}
11429 	mtx_unlock(&lun->lun_lock);
11430 }
11431 
11432 static int
11433 ctl_scsiio_precheck(struct ctl_softc *softc, struct ctl_scsiio *ctsio)
11434 {
11435 	struct ctl_lun *lun;
11436 	const struct ctl_cmd_entry *entry;
11437 	uint32_t initidx, targ_lun;
11438 	int retval;
11439 
11440 	retval = 0;
11441 
11442 	lun = NULL;
11443 
11444 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11445 	if ((targ_lun < CTL_MAX_LUNS)
11446 	 && ((lun = softc->ctl_luns[targ_lun]) != NULL)) {
11447 		/*
11448 		 * If the LUN is invalid, pretend that it doesn't exist.
11449 		 * It will go away as soon as all pending I/O has been
11450 		 * completed.
11451 		 */
11452 		mtx_lock(&lun->lun_lock);
11453 		if (lun->flags & CTL_LUN_DISABLED) {
11454 			mtx_unlock(&lun->lun_lock);
11455 			lun = NULL;
11456 			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11457 			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11458 		} else {
11459 			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11460 			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11461 				lun->be_lun;
11462 
11463 			/*
11464 			 * Every I/O goes into the OOA queue for a
11465 			 * particular LUN, and stays there until completion.
11466 			 */
11467 #ifdef CTL_TIME_IO
11468 			if (TAILQ_EMPTY(&lun->ooa_queue)) {
11469 				lun->idle_time += getsbinuptime() -
11470 				    lun->last_busy;
11471 			}
11472 #endif
11473 			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11474 			    ooa_links);
11475 		}
11476 	} else {
11477 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11478 		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11479 	}
11480 
11481 	/* Get command entry and return error if it is unsuppotyed. */
11482 	entry = ctl_validate_command(ctsio);
11483 	if (entry == NULL) {
11484 		if (lun)
11485 			mtx_unlock(&lun->lun_lock);
11486 		return (retval);
11487 	}
11488 
11489 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11490 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11491 
11492 	/*
11493 	 * Check to see whether we can send this command to LUNs that don't
11494 	 * exist.  This should pretty much only be the case for inquiry
11495 	 * and request sense.  Further checks, below, really require having
11496 	 * a LUN, so we can't really check the command anymore.  Just put
11497 	 * it on the rtr queue.
11498 	 */
11499 	if (lun == NULL) {
11500 		if (entry->flags & CTL_CMD_FLAG_OK_ON_NO_LUN) {
11501 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11502 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11503 			return (retval);
11504 		}
11505 
11506 		ctl_set_unsupported_lun(ctsio);
11507 		ctl_done((union ctl_io *)ctsio);
11508 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11509 		return (retval);
11510 	} else {
11511 		/*
11512 		 * Make sure we support this particular command on this LUN.
11513 		 * e.g., we don't support writes to the control LUN.
11514 		 */
11515 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11516 			mtx_unlock(&lun->lun_lock);
11517 			ctl_set_invalid_opcode(ctsio);
11518 			ctl_done((union ctl_io *)ctsio);
11519 			return (retval);
11520 		}
11521 	}
11522 
11523 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11524 
11525 #ifdef CTL_WITH_CA
11526 	/*
11527 	 * If we've got a request sense, it'll clear the contingent
11528 	 * allegiance condition.  Otherwise, if we have a CA condition for
11529 	 * this initiator, clear it, because it sent down a command other
11530 	 * than request sense.
11531 	 */
11532 	if ((ctsio->cdb[0] != REQUEST_SENSE)
11533 	 && (ctl_is_set(lun->have_ca, initidx)))
11534 		ctl_clear_mask(lun->have_ca, initidx);
11535 #endif
11536 
11537 	/*
11538 	 * If the command has this flag set, it handles its own unit
11539 	 * attention reporting, we shouldn't do anything.  Otherwise we
11540 	 * check for any pending unit attentions, and send them back to the
11541 	 * initiator.  We only do this when a command initially comes in,
11542 	 * not when we pull it off the blocked queue.
11543 	 *
11544 	 * According to SAM-3, section 5.3.2, the order that things get
11545 	 * presented back to the host is basically unit attentions caused
11546 	 * by some sort of reset event, busy status, reservation conflicts
11547 	 * or task set full, and finally any other status.
11548 	 *
11549 	 * One issue here is that some of the unit attentions we report
11550 	 * don't fall into the "reset" category (e.g. "reported luns data
11551 	 * has changed").  So reporting it here, before the reservation
11552 	 * check, may be technically wrong.  I guess the only thing to do
11553 	 * would be to check for and report the reset events here, and then
11554 	 * check for the other unit attention types after we check for a
11555 	 * reservation conflict.
11556 	 *
11557 	 * XXX KDM need to fix this
11558 	 */
11559 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11560 		ctl_ua_type ua_type;
11561 
11562 		ua_type = ctl_build_ua(lun, initidx, &ctsio->sense_data,
11563 		    SSD_TYPE_NONE);
11564 		if (ua_type != CTL_UA_NONE) {
11565 			mtx_unlock(&lun->lun_lock);
11566 			ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11567 			ctsio->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
11568 			ctsio->sense_len = SSD_FULL_SIZE;
11569 			ctl_done((union ctl_io *)ctsio);
11570 			return (retval);
11571 		}
11572 	}
11573 
11574 
11575 	if (ctl_scsiio_lun_check(lun, entry, ctsio) != 0) {
11576 		mtx_unlock(&lun->lun_lock);
11577 		ctl_done((union ctl_io *)ctsio);
11578 		return (retval);
11579 	}
11580 
11581 	/*
11582 	 * XXX CHD this is where we want to send IO to other side if
11583 	 * this LUN is secondary on this SC. We will need to make a copy
11584 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11585 	 * the copy we send as FROM_OTHER.
11586 	 * We also need to stuff the address of the original IO so we can
11587 	 * find it easily. Something similar will need be done on the other
11588 	 * side so when we are done we can find the copy.
11589 	 */
11590 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
11591 	    (lun->flags & CTL_LUN_PEER_SC_PRIMARY) != 0 &&
11592 	    (entry->flags & CTL_CMD_FLAG_RUN_HERE) == 0) {
11593 		union ctl_ha_msg msg_info;
11594 		int isc_retval;
11595 
11596 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11597 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11598 		mtx_unlock(&lun->lun_lock);
11599 
11600 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11601 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11602 		msg_info.hdr.serializing_sc = NULL;
11603 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11604 		msg_info.scsi.tag_num = ctsio->tag_num;
11605 		msg_info.scsi.tag_type = ctsio->tag_type;
11606 		msg_info.scsi.cdb_len = ctsio->cdb_len;
11607 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11608 
11609 		if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11610 		    sizeof(msg_info.scsi) - sizeof(msg_info.scsi.sense_data),
11611 		    M_WAITOK)) > CTL_HA_STATUS_SUCCESS) {
11612 			ctl_set_busy(ctsio);
11613 			ctl_done((union ctl_io *)ctsio);
11614 			return (retval);
11615 		}
11616 		return (retval);
11617 	}
11618 
11619 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11620 			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11621 			      ctl_ooaq, ooa_links))) {
11622 	case CTL_ACTION_BLOCK:
11623 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11624 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11625 				  blocked_links);
11626 		mtx_unlock(&lun->lun_lock);
11627 		return (retval);
11628 	case CTL_ACTION_PASS:
11629 	case CTL_ACTION_SKIP:
11630 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11631 		mtx_unlock(&lun->lun_lock);
11632 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11633 		break;
11634 	case CTL_ACTION_OVERLAP:
11635 		mtx_unlock(&lun->lun_lock);
11636 		ctl_set_overlapped_cmd(ctsio);
11637 		ctl_done((union ctl_io *)ctsio);
11638 		break;
11639 	case CTL_ACTION_OVERLAP_TAG:
11640 		mtx_unlock(&lun->lun_lock);
11641 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11642 		ctl_done((union ctl_io *)ctsio);
11643 		break;
11644 	case CTL_ACTION_ERROR:
11645 	default:
11646 		mtx_unlock(&lun->lun_lock);
11647 		ctl_set_internal_failure(ctsio,
11648 					 /*sks_valid*/ 0,
11649 					 /*retry_count*/ 0);
11650 		ctl_done((union ctl_io *)ctsio);
11651 		break;
11652 	}
11653 	return (retval);
11654 }
11655 
11656 const struct ctl_cmd_entry *
11657 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11658 {
11659 	const struct ctl_cmd_entry *entry;
11660 	int service_action;
11661 
11662 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11663 	if (sa)
11664 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11665 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11666 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11667 		entry = &((const struct ctl_cmd_entry *)
11668 		    entry->execute)[service_action];
11669 	}
11670 	return (entry);
11671 }
11672 
11673 const struct ctl_cmd_entry *
11674 ctl_validate_command(struct ctl_scsiio *ctsio)
11675 {
11676 	const struct ctl_cmd_entry *entry;
11677 	int i, sa;
11678 	uint8_t diff;
11679 
11680 	entry = ctl_get_cmd_entry(ctsio, &sa);
11681 	if (entry->execute == NULL) {
11682 		if (sa)
11683 			ctl_set_invalid_field(ctsio,
11684 					      /*sks_valid*/ 1,
11685 					      /*command*/ 1,
11686 					      /*field*/ 1,
11687 					      /*bit_valid*/ 1,
11688 					      /*bit*/ 4);
11689 		else
11690 			ctl_set_invalid_opcode(ctsio);
11691 		ctl_done((union ctl_io *)ctsio);
11692 		return (NULL);
11693 	}
11694 	KASSERT(entry->length > 0,
11695 	    ("Not defined length for command 0x%02x/0x%02x",
11696 	     ctsio->cdb[0], ctsio->cdb[1]));
11697 	for (i = 1; i < entry->length; i++) {
11698 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11699 		if (diff == 0)
11700 			continue;
11701 		ctl_set_invalid_field(ctsio,
11702 				      /*sks_valid*/ 1,
11703 				      /*command*/ 1,
11704 				      /*field*/ i,
11705 				      /*bit_valid*/ 1,
11706 				      /*bit*/ fls(diff) - 1);
11707 		ctl_done((union ctl_io *)ctsio);
11708 		return (NULL);
11709 	}
11710 	return (entry);
11711 }
11712 
11713 static int
11714 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11715 {
11716 
11717 	switch (lun_type) {
11718 	case T_DIRECT:
11719 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_DIRECT) == 0)
11720 			return (0);
11721 		break;
11722 	case T_PROCESSOR:
11723 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0)
11724 			return (0);
11725 		break;
11726 	case T_CDROM:
11727 		if ((entry->flags & CTL_CMD_FLAG_OK_ON_CDROM) == 0)
11728 			return (0);
11729 		break;
11730 	default:
11731 		return (0);
11732 	}
11733 	return (1);
11734 }
11735 
11736 static int
11737 ctl_scsiio(struct ctl_scsiio *ctsio)
11738 {
11739 	int retval;
11740 	const struct ctl_cmd_entry *entry;
11741 
11742 	retval = CTL_RETVAL_COMPLETE;
11743 
11744 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
11745 
11746 	entry = ctl_get_cmd_entry(ctsio, NULL);
11747 
11748 	/*
11749 	 * If this I/O has been aborted, just send it straight to
11750 	 * ctl_done() without executing it.
11751 	 */
11752 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
11753 		ctl_done((union ctl_io *)ctsio);
11754 		goto bailout;
11755 	}
11756 
11757 	/*
11758 	 * All the checks should have been handled by ctl_scsiio_precheck().
11759 	 * We should be clear now to just execute the I/O.
11760 	 */
11761 	retval = entry->execute(ctsio);
11762 
11763 bailout:
11764 	return (retval);
11765 }
11766 
11767 /*
11768  * Since we only implement one target right now, a bus reset simply resets
11769  * our single target.
11770  */
11771 static int
11772 ctl_bus_reset(struct ctl_softc *softc, union ctl_io *io)
11773 {
11774 	return(ctl_target_reset(softc, io, CTL_UA_BUS_RESET));
11775 }
11776 
11777 static int
11778 ctl_target_reset(struct ctl_softc *softc, union ctl_io *io,
11779 		 ctl_ua_type ua_type)
11780 {
11781 	struct ctl_port *port;
11782 	struct ctl_lun *lun;
11783 	int retval;
11784 
11785 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
11786 		union ctl_ha_msg msg_info;
11787 
11788 		msg_info.hdr.nexus = io->io_hdr.nexus;
11789 		if (ua_type==CTL_UA_TARG_RESET)
11790 			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
11791 		else
11792 			msg_info.task.task_action = CTL_TASK_BUS_RESET;
11793 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11794 		msg_info.hdr.original_sc = NULL;
11795 		msg_info.hdr.serializing_sc = NULL;
11796 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11797 		    sizeof(msg_info.task), M_WAITOK);
11798 	}
11799 	retval = 0;
11800 
11801 	mtx_lock(&softc->ctl_lock);
11802 	port = ctl_io_port(&io->io_hdr);
11803 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
11804 		if (port != NULL &&
11805 		    ctl_lun_map_to_port(port, lun->lun) >= CTL_MAX_LUNS)
11806 			continue;
11807 		retval += ctl_do_lun_reset(lun, io, ua_type);
11808 	}
11809 	mtx_unlock(&softc->ctl_lock);
11810 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11811 	return (retval);
11812 }
11813 
11814 /*
11815  * The LUN should always be set.  The I/O is optional, and is used to
11816  * distinguish between I/Os sent by this initiator, and by other
11817  * initiators.  We set unit attention for initiators other than this one.
11818  * SAM-3 is vague on this point.  It does say that a unit attention should
11819  * be established for other initiators when a LUN is reset (see section
11820  * 5.7.3), but it doesn't specifically say that the unit attention should
11821  * be established for this particular initiator when a LUN is reset.  Here
11822  * is the relevant text, from SAM-3 rev 8:
11823  *
11824  * 5.7.2 When a SCSI initiator port aborts its own tasks
11825  *
11826  * When a SCSI initiator port causes its own task(s) to be aborted, no
11827  * notification that the task(s) have been aborted shall be returned to
11828  * the SCSI initiator port other than the completion response for the
11829  * command or task management function action that caused the task(s) to
11830  * be aborted and notification(s) associated with related effects of the
11831  * action (e.g., a reset unit attention condition).
11832  *
11833  * XXX KDM for now, we're setting unit attention for all initiators.
11834  */
11835 static int
11836 ctl_do_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
11837 {
11838 	union ctl_io *xio;
11839 #if 0
11840 	uint32_t initidx;
11841 #endif
11842 	int i;
11843 
11844 	mtx_lock(&lun->lun_lock);
11845 	/*
11846 	 * Run through the OOA queue and abort each I/O.
11847 	 */
11848 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11849 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11850 		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
11851 	}
11852 
11853 	/*
11854 	 * This version sets unit attention for every
11855 	 */
11856 #if 0
11857 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
11858 	ctl_est_ua_all(lun, initidx, ua_type);
11859 #else
11860 	ctl_est_ua_all(lun, -1, ua_type);
11861 #endif
11862 
11863 	/*
11864 	 * A reset (any kind, really) clears reservations established with
11865 	 * RESERVE/RELEASE.  It does not clear reservations established
11866 	 * with PERSISTENT RESERVE OUT, but we don't support that at the
11867 	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
11868 	 * reservations made with the RESERVE/RELEASE commands, because
11869 	 * those commands are obsolete in SPC-3.
11870 	 */
11871 	lun->flags &= ~CTL_LUN_RESERVED;
11872 
11873 #ifdef CTL_WITH_CA
11874 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11875 		ctl_clear_mask(lun->have_ca, i);
11876 #endif
11877 	lun->prevent_count = 0;
11878 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
11879 		ctl_clear_mask(lun->prevent, i);
11880 	mtx_unlock(&lun->lun_lock);
11881 
11882 	return (0);
11883 }
11884 
11885 static int
11886 ctl_lun_reset(struct ctl_softc *softc, union ctl_io *io)
11887 {
11888 	struct ctl_lun *lun;
11889 	uint32_t targ_lun;
11890 	int retval;
11891 
11892 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11893 	mtx_lock(&softc->ctl_lock);
11894 	if ((targ_lun >= CTL_MAX_LUNS) ||
11895 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11896 		mtx_unlock(&softc->ctl_lock);
11897 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11898 		return (1);
11899 	}
11900 	retval = ctl_do_lun_reset(lun, io, CTL_UA_LUN_RESET);
11901 	mtx_unlock(&softc->ctl_lock);
11902 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11903 
11904 	if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0) {
11905 		union ctl_ha_msg msg_info;
11906 
11907 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11908 		msg_info.hdr.nexus = io->io_hdr.nexus;
11909 		msg_info.task.task_action = CTL_TASK_LUN_RESET;
11910 		msg_info.hdr.original_sc = NULL;
11911 		msg_info.hdr.serializing_sc = NULL;
11912 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11913 		    sizeof(msg_info.task), M_WAITOK);
11914 	}
11915 	return (retval);
11916 }
11917 
11918 static void
11919 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
11920     int other_sc)
11921 {
11922 	union ctl_io *xio;
11923 
11924 	mtx_assert(&lun->lun_lock, MA_OWNED);
11925 
11926 	/*
11927 	 * Run through the OOA queue and attempt to find the given I/O.
11928 	 * The target port, initiator ID, tag type and tag number have to
11929 	 * match the values that we got from the initiator.  If we have an
11930 	 * untagged command to abort, simply abort the first untagged command
11931 	 * we come to.  We only allow one untagged command at a time of course.
11932 	 */
11933 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
11934 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
11935 
11936 		if ((targ_port == UINT32_MAX ||
11937 		     targ_port == xio->io_hdr.nexus.targ_port) &&
11938 		    (init_id == UINT32_MAX ||
11939 		     init_id == xio->io_hdr.nexus.initid)) {
11940 			if (targ_port != xio->io_hdr.nexus.targ_port ||
11941 			    init_id != xio->io_hdr.nexus.initid)
11942 				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
11943 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
11944 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
11945 				union ctl_ha_msg msg_info;
11946 
11947 				msg_info.hdr.nexus = xio->io_hdr.nexus;
11948 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
11949 				msg_info.task.tag_num = xio->scsiio.tag_num;
11950 				msg_info.task.tag_type = xio->scsiio.tag_type;
11951 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
11952 				msg_info.hdr.original_sc = NULL;
11953 				msg_info.hdr.serializing_sc = NULL;
11954 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
11955 				    sizeof(msg_info.task), M_NOWAIT);
11956 			}
11957 		}
11958 	}
11959 }
11960 
11961 static int
11962 ctl_abort_task_set(union ctl_io *io)
11963 {
11964 	struct ctl_softc *softc = control_softc;
11965 	struct ctl_lun *lun;
11966 	uint32_t targ_lun;
11967 
11968 	/*
11969 	 * Look up the LUN.
11970 	 */
11971 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
11972 	mtx_lock(&softc->ctl_lock);
11973 	if ((targ_lun >= CTL_MAX_LUNS) ||
11974 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
11975 		mtx_unlock(&softc->ctl_lock);
11976 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
11977 		return (1);
11978 	}
11979 
11980 	mtx_lock(&lun->lun_lock);
11981 	mtx_unlock(&softc->ctl_lock);
11982 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
11983 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
11984 		    io->io_hdr.nexus.initid,
11985 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11986 	} else { /* CTL_TASK_CLEAR_TASK_SET */
11987 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
11988 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
11989 	}
11990 	mtx_unlock(&lun->lun_lock);
11991 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
11992 	return (0);
11993 }
11994 
11995 static int
11996 ctl_i_t_nexus_reset(union ctl_io *io)
11997 {
11998 	struct ctl_softc *softc = control_softc;
11999 	struct ctl_lun *lun;
12000 	uint32_t initidx;
12001 
12002 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12003 		union ctl_ha_msg msg_info;
12004 
12005 		msg_info.hdr.nexus = io->io_hdr.nexus;
12006 		msg_info.task.task_action = CTL_TASK_I_T_NEXUS_RESET;
12007 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12008 		msg_info.hdr.original_sc = NULL;
12009 		msg_info.hdr.serializing_sc = NULL;
12010 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12011 		    sizeof(msg_info.task), M_WAITOK);
12012 	}
12013 
12014 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12015 	mtx_lock(&softc->ctl_lock);
12016 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12017 		mtx_lock(&lun->lun_lock);
12018 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12019 		    io->io_hdr.nexus.initid, 1);
12020 #ifdef CTL_WITH_CA
12021 		ctl_clear_mask(lun->have_ca, initidx);
12022 #endif
12023 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == initidx))
12024 			lun->flags &= ~CTL_LUN_RESERVED;
12025 		if (ctl_is_set(lun->prevent, initidx)) {
12026 			ctl_clear_mask(lun->prevent, initidx);
12027 			lun->prevent_count--;
12028 		}
12029 		ctl_est_ua(lun, initidx, CTL_UA_I_T_NEXUS_LOSS);
12030 		mtx_unlock(&lun->lun_lock);
12031 	}
12032 	mtx_unlock(&softc->ctl_lock);
12033 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12034 	return (0);
12035 }
12036 
12037 static int
12038 ctl_abort_task(union ctl_io *io)
12039 {
12040 	union ctl_io *xio;
12041 	struct ctl_lun *lun;
12042 	struct ctl_softc *softc;
12043 #if 0
12044 	struct sbuf sb;
12045 	char printbuf[128];
12046 #endif
12047 	int found;
12048 	uint32_t targ_lun;
12049 
12050 	softc = control_softc;
12051 	found = 0;
12052 
12053 	/*
12054 	 * Look up the LUN.
12055 	 */
12056 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12057 	mtx_lock(&softc->ctl_lock);
12058 	if ((targ_lun >= CTL_MAX_LUNS) ||
12059 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12060 		mtx_unlock(&softc->ctl_lock);
12061 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12062 		return (1);
12063 	}
12064 
12065 #if 0
12066 	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12067 	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12068 #endif
12069 
12070 	mtx_lock(&lun->lun_lock);
12071 	mtx_unlock(&softc->ctl_lock);
12072 	/*
12073 	 * Run through the OOA queue and attempt to find the given I/O.
12074 	 * The target port, initiator ID, tag type and tag number have to
12075 	 * match the values that we got from the initiator.  If we have an
12076 	 * untagged command to abort, simply abort the first untagged command
12077 	 * we come to.  We only allow one untagged command at a time of course.
12078 	 */
12079 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12080 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12081 #if 0
12082 		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12083 
12084 		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12085 			    lun->lun, xio->scsiio.tag_num,
12086 			    xio->scsiio.tag_type,
12087 			    (xio->io_hdr.blocked_links.tqe_prev
12088 			    == NULL) ? "" : " BLOCKED",
12089 			    (xio->io_hdr.flags &
12090 			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12091 			    (xio->io_hdr.flags &
12092 			    CTL_FLAG_ABORT) ? " ABORT" : "",
12093 			    (xio->io_hdr.flags &
12094 			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12095 		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12096 		sbuf_finish(&sb);
12097 		printf("%s\n", sbuf_data(&sb));
12098 #endif
12099 
12100 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12101 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12102 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12103 			continue;
12104 
12105 		/*
12106 		 * If the abort says that the task is untagged, the
12107 		 * task in the queue must be untagged.  Otherwise,
12108 		 * we just check to see whether the tag numbers
12109 		 * match.  This is because the QLogic firmware
12110 		 * doesn't pass back the tag type in an abort
12111 		 * request.
12112 		 */
12113 #if 0
12114 		if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12115 		  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12116 		 || (xio->scsiio.tag_num == io->taskio.tag_num))
12117 #endif
12118 		/*
12119 		 * XXX KDM we've got problems with FC, because it
12120 		 * doesn't send down a tag type with aborts.  So we
12121 		 * can only really go by the tag number...
12122 		 * This may cause problems with parallel SCSI.
12123 		 * Need to figure that out!!
12124 		 */
12125 		if (xio->scsiio.tag_num == io->taskio.tag_num) {
12126 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12127 			found = 1;
12128 			if ((io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) == 0 &&
12129 			    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12130 				union ctl_ha_msg msg_info;
12131 
12132 				msg_info.hdr.nexus = io->io_hdr.nexus;
12133 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12134 				msg_info.task.tag_num = io->taskio.tag_num;
12135 				msg_info.task.tag_type = io->taskio.tag_type;
12136 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12137 				msg_info.hdr.original_sc = NULL;
12138 				msg_info.hdr.serializing_sc = NULL;
12139 #if 0
12140 				printf("Sent Abort to other side\n");
12141 #endif
12142 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
12143 				    sizeof(msg_info.task), M_NOWAIT);
12144 			}
12145 #if 0
12146 			printf("ctl_abort_task: found I/O to abort\n");
12147 #endif
12148 		}
12149 	}
12150 	mtx_unlock(&lun->lun_lock);
12151 
12152 	if (found == 0) {
12153 		/*
12154 		 * This isn't really an error.  It's entirely possible for
12155 		 * the abort and command completion to cross on the wire.
12156 		 * This is more of an informative/diagnostic error.
12157 		 */
12158 #if 0
12159 		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12160 		       "%u:%u:%u tag %d type %d\n",
12161 		       io->io_hdr.nexus.initid,
12162 		       io->io_hdr.nexus.targ_port,
12163 		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12164 		       io->taskio.tag_type);
12165 #endif
12166 	}
12167 	io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12168 	return (0);
12169 }
12170 
12171 static int
12172 ctl_query_task(union ctl_io *io, int task_set)
12173 {
12174 	union ctl_io *xio;
12175 	struct ctl_lun *lun;
12176 	struct ctl_softc *softc;
12177 	int found = 0;
12178 	uint32_t targ_lun;
12179 
12180 	softc = control_softc;
12181 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12182 	mtx_lock(&softc->ctl_lock);
12183 	if ((targ_lun >= CTL_MAX_LUNS) ||
12184 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12185 		mtx_unlock(&softc->ctl_lock);
12186 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12187 		return (1);
12188 	}
12189 	mtx_lock(&lun->lun_lock);
12190 	mtx_unlock(&softc->ctl_lock);
12191 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12192 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12193 
12194 		if ((xio->io_hdr.nexus.targ_port != io->io_hdr.nexus.targ_port)
12195 		 || (xio->io_hdr.nexus.initid != io->io_hdr.nexus.initid)
12196 		 || (xio->io_hdr.flags & CTL_FLAG_ABORT))
12197 			continue;
12198 
12199 		if (task_set || xio->scsiio.tag_num == io->taskio.tag_num) {
12200 			found = 1;
12201 			break;
12202 		}
12203 	}
12204 	mtx_unlock(&lun->lun_lock);
12205 	if (found)
12206 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12207 	else
12208 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12209 	return (0);
12210 }
12211 
12212 static int
12213 ctl_query_async_event(union ctl_io *io)
12214 {
12215 	struct ctl_lun *lun;
12216 	struct ctl_softc *softc;
12217 	ctl_ua_type ua;
12218 	uint32_t targ_lun, initidx;
12219 
12220 	softc = control_softc;
12221 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12222 	mtx_lock(&softc->ctl_lock);
12223 	if ((targ_lun >= CTL_MAX_LUNS) ||
12224 	    (lun = softc->ctl_luns[targ_lun]) == NULL) {
12225 		mtx_unlock(&softc->ctl_lock);
12226 		io->taskio.task_status = CTL_TASK_LUN_DOES_NOT_EXIST;
12227 		return (1);
12228 	}
12229 	mtx_lock(&lun->lun_lock);
12230 	mtx_unlock(&softc->ctl_lock);
12231 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
12232 	ua = ctl_build_qae(lun, initidx, io->taskio.task_resp);
12233 	mtx_unlock(&lun->lun_lock);
12234 	if (ua != CTL_UA_NONE)
12235 		io->taskio.task_status = CTL_TASK_FUNCTION_SUCCEEDED;
12236 	else
12237 		io->taskio.task_status = CTL_TASK_FUNCTION_COMPLETE;
12238 	return (0);
12239 }
12240 
12241 static void
12242 ctl_run_task(union ctl_io *io)
12243 {
12244 	struct ctl_softc *softc = control_softc;
12245 	int retval = 1;
12246 
12247 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12248 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12249 	    ("ctl_run_task: Unextected io_type %d\n", io->io_hdr.io_type));
12250 	io->taskio.task_status = CTL_TASK_FUNCTION_NOT_SUPPORTED;
12251 	bzero(io->taskio.task_resp, sizeof(io->taskio.task_resp));
12252 	switch (io->taskio.task_action) {
12253 	case CTL_TASK_ABORT_TASK:
12254 		retval = ctl_abort_task(io);
12255 		break;
12256 	case CTL_TASK_ABORT_TASK_SET:
12257 	case CTL_TASK_CLEAR_TASK_SET:
12258 		retval = ctl_abort_task_set(io);
12259 		break;
12260 	case CTL_TASK_CLEAR_ACA:
12261 		break;
12262 	case CTL_TASK_I_T_NEXUS_RESET:
12263 		retval = ctl_i_t_nexus_reset(io);
12264 		break;
12265 	case CTL_TASK_LUN_RESET:
12266 		retval = ctl_lun_reset(softc, io);
12267 		break;
12268 	case CTL_TASK_TARGET_RESET:
12269 		retval = ctl_target_reset(softc, io, CTL_UA_TARG_RESET);
12270 		break;
12271 	case CTL_TASK_BUS_RESET:
12272 		retval = ctl_bus_reset(softc, io);
12273 		break;
12274 	case CTL_TASK_PORT_LOGIN:
12275 		break;
12276 	case CTL_TASK_PORT_LOGOUT:
12277 		break;
12278 	case CTL_TASK_QUERY_TASK:
12279 		retval = ctl_query_task(io, 0);
12280 		break;
12281 	case CTL_TASK_QUERY_TASK_SET:
12282 		retval = ctl_query_task(io, 1);
12283 		break;
12284 	case CTL_TASK_QUERY_ASYNC_EVENT:
12285 		retval = ctl_query_async_event(io);
12286 		break;
12287 	default:
12288 		printf("%s: got unknown task management event %d\n",
12289 		       __func__, io->taskio.task_action);
12290 		break;
12291 	}
12292 	if (retval == 0)
12293 		io->io_hdr.status = CTL_SUCCESS;
12294 	else
12295 		io->io_hdr.status = CTL_ERROR;
12296 	ctl_done(io);
12297 }
12298 
12299 /*
12300  * For HA operation.  Handle commands that come in from the other
12301  * controller.
12302  */
12303 static void
12304 ctl_handle_isc(union ctl_io *io)
12305 {
12306 	int free_io;
12307 	struct ctl_lun *lun;
12308 	struct ctl_softc *softc = control_softc;
12309 	uint32_t targ_lun;
12310 
12311 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12312 	lun = softc->ctl_luns[targ_lun];
12313 
12314 	switch (io->io_hdr.msg_type) {
12315 	case CTL_MSG_SERIALIZE:
12316 		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12317 		break;
12318 	case CTL_MSG_R2R: {
12319 		const struct ctl_cmd_entry *entry;
12320 
12321 		/*
12322 		 * This is only used in SER_ONLY mode.
12323 		 */
12324 		free_io = 0;
12325 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12326 		mtx_lock(&lun->lun_lock);
12327 		if (ctl_scsiio_lun_check(lun,
12328 		    entry, (struct ctl_scsiio *)io) != 0) {
12329 			mtx_unlock(&lun->lun_lock);
12330 			ctl_done(io);
12331 			break;
12332 		}
12333 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12334 		mtx_unlock(&lun->lun_lock);
12335 		ctl_enqueue_rtr(io);
12336 		break;
12337 	}
12338 	case CTL_MSG_FINISH_IO:
12339 		if (softc->ha_mode == CTL_HA_MODE_XFER) {
12340 			free_io = 0;
12341 			ctl_done(io);
12342 		} else {
12343 			free_io = 1;
12344 			mtx_lock(&lun->lun_lock);
12345 			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12346 				     ooa_links);
12347 			ctl_check_blocked(lun);
12348 			mtx_unlock(&lun->lun_lock);
12349 		}
12350 		break;
12351 	case CTL_MSG_PERS_ACTION:
12352 		ctl_hndl_per_res_out_on_other_sc(
12353 			(union ctl_ha_msg *)&io->presio.pr_msg);
12354 		free_io = 1;
12355 		break;
12356 	case CTL_MSG_BAD_JUJU:
12357 		free_io = 0;
12358 		ctl_done(io);
12359 		break;
12360 	case CTL_MSG_DATAMOVE:
12361 		/* Only used in XFER mode */
12362 		free_io = 0;
12363 		ctl_datamove_remote(io);
12364 		break;
12365 	case CTL_MSG_DATAMOVE_DONE:
12366 		/* Only used in XFER mode */
12367 		free_io = 0;
12368 		io->scsiio.be_move_done(io);
12369 		break;
12370 	case CTL_MSG_FAILOVER:
12371 		ctl_failover_lun(io);
12372 		free_io = 1;
12373 		break;
12374 	default:
12375 		free_io = 1;
12376 		printf("%s: Invalid message type %d\n",
12377 		       __func__, io->io_hdr.msg_type);
12378 		break;
12379 	}
12380 	if (free_io)
12381 		ctl_free_io(io);
12382 
12383 }
12384 
12385 
12386 /*
12387  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12388  * there is no match.
12389  */
12390 static ctl_lun_error_pattern
12391 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12392 {
12393 	const struct ctl_cmd_entry *entry;
12394 	ctl_lun_error_pattern filtered_pattern, pattern;
12395 
12396 	pattern = desc->error_pattern;
12397 
12398 	/*
12399 	 * XXX KDM we need more data passed into this function to match a
12400 	 * custom pattern, and we actually need to implement custom pattern
12401 	 * matching.
12402 	 */
12403 	if (pattern & CTL_LUN_PAT_CMD)
12404 		return (CTL_LUN_PAT_CMD);
12405 
12406 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12407 		return (CTL_LUN_PAT_ANY);
12408 
12409 	entry = ctl_get_cmd_entry(ctsio, NULL);
12410 
12411 	filtered_pattern = entry->pattern & pattern;
12412 
12413 	/*
12414 	 * If the user requested specific flags in the pattern (e.g.
12415 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12416 	 * flags.
12417 	 *
12418 	 * If the user did not specify any flags, it doesn't matter whether
12419 	 * or not the command supports the flags.
12420 	 */
12421 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12422 	     (pattern & ~CTL_LUN_PAT_MASK))
12423 		return (CTL_LUN_PAT_NONE);
12424 
12425 	/*
12426 	 * If the user asked for a range check, see if the requested LBA
12427 	 * range overlaps with this command's LBA range.
12428 	 */
12429 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12430 		uint64_t lba1;
12431 		uint64_t len1;
12432 		ctl_action action;
12433 		int retval;
12434 
12435 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12436 		if (retval != 0)
12437 			return (CTL_LUN_PAT_NONE);
12438 
12439 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12440 					      desc->lba_range.len, FALSE);
12441 		/*
12442 		 * A "pass" means that the LBA ranges don't overlap, so
12443 		 * this doesn't match the user's range criteria.
12444 		 */
12445 		if (action == CTL_ACTION_PASS)
12446 			return (CTL_LUN_PAT_NONE);
12447 	}
12448 
12449 	return (filtered_pattern);
12450 }
12451 
12452 static void
12453 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12454 {
12455 	struct ctl_error_desc *desc, *desc2;
12456 
12457 	mtx_assert(&lun->lun_lock, MA_OWNED);
12458 
12459 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12460 		ctl_lun_error_pattern pattern;
12461 		/*
12462 		 * Check to see whether this particular command matches
12463 		 * the pattern in the descriptor.
12464 		 */
12465 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12466 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12467 			continue;
12468 
12469 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12470 		case CTL_LUN_INJ_ABORTED:
12471 			ctl_set_aborted(&io->scsiio);
12472 			break;
12473 		case CTL_LUN_INJ_MEDIUM_ERR:
12474 			ctl_set_medium_error(&io->scsiio,
12475 			    (io->io_hdr.flags & CTL_FLAG_DATA_MASK) !=
12476 			     CTL_FLAG_DATA_OUT);
12477 			break;
12478 		case CTL_LUN_INJ_UA:
12479 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12480 			 * OCCURRED */
12481 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12482 			break;
12483 		case CTL_LUN_INJ_CUSTOM:
12484 			/*
12485 			 * We're assuming the user knows what he is doing.
12486 			 * Just copy the sense information without doing
12487 			 * checks.
12488 			 */
12489 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12490 			      MIN(sizeof(desc->custom_sense),
12491 				  sizeof(io->scsiio.sense_data)));
12492 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12493 			io->scsiio.sense_len = SSD_FULL_SIZE;
12494 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12495 			break;
12496 		case CTL_LUN_INJ_NONE:
12497 		default:
12498 			/*
12499 			 * If this is an error injection type we don't know
12500 			 * about, clear the continuous flag (if it is set)
12501 			 * so it will get deleted below.
12502 			 */
12503 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12504 			break;
12505 		}
12506 		/*
12507 		 * By default, each error injection action is a one-shot
12508 		 */
12509 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12510 			continue;
12511 
12512 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12513 
12514 		free(desc, M_CTL);
12515 	}
12516 }
12517 
12518 #ifdef CTL_IO_DELAY
12519 static void
12520 ctl_datamove_timer_wakeup(void *arg)
12521 {
12522 	union ctl_io *io;
12523 
12524 	io = (union ctl_io *)arg;
12525 
12526 	ctl_datamove(io);
12527 }
12528 #endif /* CTL_IO_DELAY */
12529 
12530 void
12531 ctl_datamove(union ctl_io *io)
12532 {
12533 	struct ctl_lun *lun;
12534 	void (*fe_datamove)(union ctl_io *io);
12535 
12536 	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12537 
12538 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12539 
12540 	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12541 #ifdef CTL_TIME_IO
12542 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12543 		char str[256];
12544 		char path_str[64];
12545 		struct sbuf sb;
12546 
12547 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12548 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12549 
12550 		sbuf_cat(&sb, path_str);
12551 		switch (io->io_hdr.io_type) {
12552 		case CTL_IO_SCSI:
12553 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12554 			sbuf_printf(&sb, "\n");
12555 			sbuf_cat(&sb, path_str);
12556 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12557 				    io->scsiio.tag_num, io->scsiio.tag_type);
12558 			break;
12559 		case CTL_IO_TASK:
12560 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12561 				    "Tag Type: %d\n", io->taskio.task_action,
12562 				    io->taskio.tag_num, io->taskio.tag_type);
12563 			break;
12564 		default:
12565 			panic("%s: Invalid CTL I/O type %d\n",
12566 			    __func__, io->io_hdr.io_type);
12567 		}
12568 		sbuf_cat(&sb, path_str);
12569 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12570 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12571 		sbuf_finish(&sb);
12572 		printf("%s", sbuf_data(&sb));
12573 	}
12574 #endif /* CTL_TIME_IO */
12575 
12576 #ifdef CTL_IO_DELAY
12577 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12578 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12579 	} else {
12580 		if ((lun != NULL)
12581 		 && (lun->delay_info.datamove_delay > 0)) {
12582 
12583 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
12584 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12585 			callout_reset(&io->io_hdr.delay_callout,
12586 				      lun->delay_info.datamove_delay * hz,
12587 				      ctl_datamove_timer_wakeup, io);
12588 			if (lun->delay_info.datamove_type ==
12589 			    CTL_DELAY_TYPE_ONESHOT)
12590 				lun->delay_info.datamove_delay = 0;
12591 			return;
12592 		}
12593 	}
12594 #endif
12595 
12596 	/*
12597 	 * This command has been aborted.  Set the port status, so we fail
12598 	 * the data move.
12599 	 */
12600 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12601 		printf("ctl_datamove: tag 0x%04x on (%u:%u:%u) aborted\n",
12602 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
12603 		       io->io_hdr.nexus.targ_port,
12604 		       io->io_hdr.nexus.targ_lun);
12605 		io->io_hdr.port_status = 31337;
12606 		/*
12607 		 * Note that the backend, in this case, will get the
12608 		 * callback in its context.  In other cases it may get
12609 		 * called in the frontend's interrupt thread context.
12610 		 */
12611 		io->scsiio.be_move_done(io);
12612 		return;
12613 	}
12614 
12615 	/* Don't confuse frontend with zero length data move. */
12616 	if (io->scsiio.kern_data_len == 0) {
12617 		io->scsiio.be_move_done(io);
12618 		return;
12619 	}
12620 
12621 	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12622 	fe_datamove(io);
12623 }
12624 
12625 static void
12626 ctl_send_datamove_done(union ctl_io *io, int have_lock)
12627 {
12628 	union ctl_ha_msg msg;
12629 #ifdef CTL_TIME_IO
12630 	struct bintime cur_bt;
12631 #endif
12632 
12633 	memset(&msg, 0, sizeof(msg));
12634 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
12635 	msg.hdr.original_sc = io;
12636 	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
12637 	msg.hdr.nexus = io->io_hdr.nexus;
12638 	msg.hdr.status = io->io_hdr.status;
12639 	msg.scsi.tag_num = io->scsiio.tag_num;
12640 	msg.scsi.tag_type = io->scsiio.tag_type;
12641 	msg.scsi.scsi_status = io->scsiio.scsi_status;
12642 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
12643 	       io->scsiio.sense_len);
12644 	msg.scsi.sense_len = io->scsiio.sense_len;
12645 	msg.scsi.sense_residual = io->scsiio.sense_residual;
12646 	msg.scsi.fetd_status = io->io_hdr.port_status;
12647 	msg.scsi.residual = io->scsiio.residual;
12648 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12649 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
12650 		ctl_failover_io(io, /*have_lock*/ have_lock);
12651 		return;
12652 	}
12653 	ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12654 	    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data) +
12655 	    msg.scsi.sense_len, M_WAITOK);
12656 
12657 #ifdef CTL_TIME_IO
12658 	getbinuptime(&cur_bt);
12659 	bintime_sub(&cur_bt, &io->io_hdr.dma_start_bt);
12660 	bintime_add(&io->io_hdr.dma_bt, &cur_bt);
12661 #endif
12662 	io->io_hdr.num_dmas++;
12663 }
12664 
12665 /*
12666  * The DMA to the remote side is done, now we need to tell the other side
12667  * we're done so it can continue with its data movement.
12668  */
12669 static void
12670 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
12671 {
12672 	union ctl_io *io;
12673 	int i;
12674 
12675 	io = rq->context;
12676 
12677 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12678 		printf("%s: ISC DMA write failed with error %d", __func__,
12679 		       rq->ret);
12680 		ctl_set_internal_failure(&io->scsiio,
12681 					 /*sks_valid*/ 1,
12682 					 /*retry_count*/ rq->ret);
12683 	}
12684 
12685 	ctl_dt_req_free(rq);
12686 
12687 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12688 		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12689 	free(io->io_hdr.remote_sglist, M_CTL);
12690 	io->io_hdr.remote_sglist = NULL;
12691 	io->io_hdr.local_sglist = NULL;
12692 
12693 	/*
12694 	 * The data is in local and remote memory, so now we need to send
12695 	 * status (good or back) back to the other side.
12696 	 */
12697 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12698 }
12699 
12700 /*
12701  * We've moved the data from the host/controller into local memory.  Now we
12702  * need to push it over to the remote controller's memory.
12703  */
12704 static int
12705 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
12706 {
12707 	int retval;
12708 
12709 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
12710 					  ctl_datamove_remote_write_cb);
12711 	return (retval);
12712 }
12713 
12714 static void
12715 ctl_datamove_remote_write(union ctl_io *io)
12716 {
12717 	int retval;
12718 	void (*fe_datamove)(union ctl_io *io);
12719 
12720 	/*
12721 	 * - Get the data from the host/HBA into local memory.
12722 	 * - DMA memory from the local controller to the remote controller.
12723 	 * - Send status back to the remote controller.
12724 	 */
12725 
12726 	retval = ctl_datamove_remote_sgl_setup(io);
12727 	if (retval != 0)
12728 		return;
12729 
12730 	/* Switch the pointer over so the FETD knows what to do */
12731 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12732 
12733 	/*
12734 	 * Use a custom move done callback, since we need to send completion
12735 	 * back to the other controller, not to the backend on this side.
12736 	 */
12737 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
12738 
12739 	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12740 	fe_datamove(io);
12741 }
12742 
12743 static int
12744 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
12745 {
12746 #if 0
12747 	char str[256];
12748 	char path_str[64];
12749 	struct sbuf sb;
12750 #endif
12751 	int i;
12752 
12753 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12754 		free(io->io_hdr.local_sglist[i].addr, M_CTL);
12755 	free(io->io_hdr.remote_sglist, M_CTL);
12756 	io->io_hdr.remote_sglist = NULL;
12757 	io->io_hdr.local_sglist = NULL;
12758 
12759 #if 0
12760 	scsi_path_string(io, path_str, sizeof(path_str));
12761 	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12762 	sbuf_cat(&sb, path_str);
12763 	scsi_command_string(&io->scsiio, NULL, &sb);
12764 	sbuf_printf(&sb, "\n");
12765 	sbuf_cat(&sb, path_str);
12766 	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12767 		    io->scsiio.tag_num, io->scsiio.tag_type);
12768 	sbuf_cat(&sb, path_str);
12769 	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
12770 		    io->io_hdr.flags, io->io_hdr.status);
12771 	sbuf_finish(&sb);
12772 	printk("%s", sbuf_data(&sb));
12773 #endif
12774 
12775 
12776 	/*
12777 	 * The read is done, now we need to send status (good or bad) back
12778 	 * to the other side.
12779 	 */
12780 	ctl_send_datamove_done(io, /*have_lock*/ 0);
12781 
12782 	return (0);
12783 }
12784 
12785 static void
12786 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
12787 {
12788 	union ctl_io *io;
12789 	void (*fe_datamove)(union ctl_io *io);
12790 
12791 	io = rq->context;
12792 
12793 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
12794 		printf("%s: ISC DMA read failed with error %d\n", __func__,
12795 		       rq->ret);
12796 		ctl_set_internal_failure(&io->scsiio,
12797 					 /*sks_valid*/ 1,
12798 					 /*retry_count*/ rq->ret);
12799 	}
12800 
12801 	ctl_dt_req_free(rq);
12802 
12803 	/* Switch the pointer over so the FETD knows what to do */
12804 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
12805 
12806 	/*
12807 	 * Use a custom move done callback, since we need to send completion
12808 	 * back to the other controller, not to the backend on this side.
12809 	 */
12810 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
12811 
12812 	/* XXX KDM add checks like the ones in ctl_datamove? */
12813 
12814 	fe_datamove = ctl_io_port(&io->io_hdr)->fe_datamove;
12815 	fe_datamove(io);
12816 }
12817 
12818 static int
12819 ctl_datamove_remote_sgl_setup(union ctl_io *io)
12820 {
12821 	struct ctl_sg_entry *local_sglist;
12822 	uint32_t len_to_go;
12823 	int retval;
12824 	int i;
12825 
12826 	retval = 0;
12827 	local_sglist = io->io_hdr.local_sglist;
12828 	len_to_go = io->scsiio.kern_data_len;
12829 
12830 	/*
12831 	 * The difficult thing here is that the size of the various
12832 	 * S/G segments may be different than the size from the
12833 	 * remote controller.  That'll make it harder when DMAing
12834 	 * the data back to the other side.
12835 	 */
12836 	for (i = 0; len_to_go > 0; i++) {
12837 		local_sglist[i].len = MIN(len_to_go, CTL_HA_DATAMOVE_SEGMENT);
12838 		local_sglist[i].addr =
12839 		    malloc(local_sglist[i].len, M_CTL, M_WAITOK);
12840 
12841 		len_to_go -= local_sglist[i].len;
12842 	}
12843 	/*
12844 	 * Reset the number of S/G entries accordingly.  The original
12845 	 * number of S/G entries is available in rem_sg_entries.
12846 	 */
12847 	io->scsiio.kern_sg_entries = i;
12848 
12849 #if 0
12850 	printf("%s: kern_sg_entries = %d\n", __func__,
12851 	       io->scsiio.kern_sg_entries);
12852 	for (i = 0; i < io->scsiio.kern_sg_entries; i++)
12853 		printf("%s: sg[%d] = %p, %lu\n", __func__, i,
12854 		       local_sglist[i].addr, local_sglist[i].len);
12855 #endif
12856 
12857 	return (retval);
12858 }
12859 
12860 static int
12861 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
12862 			 ctl_ha_dt_cb callback)
12863 {
12864 	struct ctl_ha_dt_req *rq;
12865 	struct ctl_sg_entry *remote_sglist, *local_sglist;
12866 	uint32_t local_used, remote_used, total_used;
12867 	int i, j, isc_ret;
12868 
12869 	rq = ctl_dt_req_alloc();
12870 
12871 	/*
12872 	 * If we failed to allocate the request, and if the DMA didn't fail
12873 	 * anyway, set busy status.  This is just a resource allocation
12874 	 * failure.
12875 	 */
12876 	if ((rq == NULL)
12877 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12878 	     (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS))
12879 		ctl_set_busy(&io->scsiio);
12880 
12881 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE &&
12882 	    (io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS) {
12883 
12884 		if (rq != NULL)
12885 			ctl_dt_req_free(rq);
12886 
12887 		/*
12888 		 * The data move failed.  We need to return status back
12889 		 * to the other controller.  No point in trying to DMA
12890 		 * data to the remote controller.
12891 		 */
12892 
12893 		ctl_send_datamove_done(io, /*have_lock*/ 0);
12894 
12895 		return (1);
12896 	}
12897 
12898 	local_sglist = io->io_hdr.local_sglist;
12899 	remote_sglist = io->io_hdr.remote_sglist;
12900 	local_used = 0;
12901 	remote_used = 0;
12902 	total_used = 0;
12903 
12904 	/*
12905 	 * Pull/push the data over the wire from/to the other controller.
12906 	 * This takes into account the possibility that the local and
12907 	 * remote sglists may not be identical in terms of the size of
12908 	 * the elements and the number of elements.
12909 	 *
12910 	 * One fundamental assumption here is that the length allocated for
12911 	 * both the local and remote sglists is identical.  Otherwise, we've
12912 	 * essentially got a coding error of some sort.
12913 	 */
12914 	isc_ret = CTL_HA_STATUS_SUCCESS;
12915 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
12916 		uint32_t cur_len;
12917 		uint8_t *tmp_ptr;
12918 
12919 		rq->command = command;
12920 		rq->context = io;
12921 
12922 		/*
12923 		 * Both pointers should be aligned.  But it is possible
12924 		 * that the allocation length is not.  They should both
12925 		 * also have enough slack left over at the end, though,
12926 		 * to round up to the next 8 byte boundary.
12927 		 */
12928 		cur_len = MIN(local_sglist[i].len - local_used,
12929 			      remote_sglist[j].len - remote_used);
12930 		rq->size = cur_len;
12931 
12932 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
12933 		tmp_ptr += local_used;
12934 
12935 #if 0
12936 		/* Use physical addresses when talking to ISC hardware */
12937 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
12938 			/* XXX KDM use busdma */
12939 			rq->local = vtophys(tmp_ptr);
12940 		} else
12941 			rq->local = tmp_ptr;
12942 #else
12943 		KASSERT((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0,
12944 		    ("HA does not support BUS_ADDR"));
12945 		rq->local = tmp_ptr;
12946 #endif
12947 
12948 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
12949 		tmp_ptr += remote_used;
12950 		rq->remote = tmp_ptr;
12951 
12952 		rq->callback = NULL;
12953 
12954 		local_used += cur_len;
12955 		if (local_used >= local_sglist[i].len) {
12956 			i++;
12957 			local_used = 0;
12958 		}
12959 
12960 		remote_used += cur_len;
12961 		if (remote_used >= remote_sglist[j].len) {
12962 			j++;
12963 			remote_used = 0;
12964 		}
12965 		total_used += cur_len;
12966 
12967 		if (total_used >= io->scsiio.kern_data_len)
12968 			rq->callback = callback;
12969 
12970 #if 0
12971 		printf("%s: %s: local %p remote %p size %d\n", __func__,
12972 		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
12973 		       rq->local, rq->remote, rq->size);
12974 #endif
12975 
12976 		isc_ret = ctl_dt_single(rq);
12977 		if (isc_ret > CTL_HA_STATUS_SUCCESS)
12978 			break;
12979 	}
12980 	if (isc_ret != CTL_HA_STATUS_WAIT) {
12981 		rq->ret = isc_ret;
12982 		callback(rq);
12983 	}
12984 
12985 	return (0);
12986 }
12987 
12988 static void
12989 ctl_datamove_remote_read(union ctl_io *io)
12990 {
12991 	int retval;
12992 	int i;
12993 
12994 	/*
12995 	 * This will send an error to the other controller in the case of a
12996 	 * failure.
12997 	 */
12998 	retval = ctl_datamove_remote_sgl_setup(io);
12999 	if (retval != 0)
13000 		return;
13001 
13002 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13003 					  ctl_datamove_remote_read_cb);
13004 	if (retval != 0) {
13005 		/*
13006 		 * Make sure we free memory if there was an error..  The
13007 		 * ctl_datamove_remote_xfer() function will send the
13008 		 * datamove done message, or call the callback with an
13009 		 * error if there is a problem.
13010 		 */
13011 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13012 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13013 		free(io->io_hdr.remote_sglist, M_CTL);
13014 		io->io_hdr.remote_sglist = NULL;
13015 		io->io_hdr.local_sglist = NULL;
13016 	}
13017 }
13018 
13019 /*
13020  * Process a datamove request from the other controller.  This is used for
13021  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13022  * first.  Once that is complete, the data gets DMAed into the remote
13023  * controller's memory.  For reads, we DMA from the remote controller's
13024  * memory into our memory first, and then move it out to the FETD.
13025  */
13026 static void
13027 ctl_datamove_remote(union ctl_io *io)
13028 {
13029 
13030 	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
13031 
13032 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13033 		ctl_failover_io(io, /*have_lock*/ 0);
13034 		return;
13035 	}
13036 
13037 	/*
13038 	 * Note that we look for an aborted I/O here, but don't do some of
13039 	 * the other checks that ctl_datamove() normally does.
13040 	 * We don't need to run the datamove delay code, since that should
13041 	 * have been done if need be on the other controller.
13042 	 */
13043 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13044 		printf("%s: tag 0x%04x on (%u:%u:%u) aborted\n", __func__,
13045 		       io->scsiio.tag_num, io->io_hdr.nexus.initid,
13046 		       io->io_hdr.nexus.targ_port,
13047 		       io->io_hdr.nexus.targ_lun);
13048 		io->io_hdr.port_status = 31338;
13049 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13050 		return;
13051 	}
13052 
13053 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT)
13054 		ctl_datamove_remote_write(io);
13055 	else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
13056 		ctl_datamove_remote_read(io);
13057 	else {
13058 		io->io_hdr.port_status = 31339;
13059 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13060 	}
13061 }
13062 
13063 static void
13064 ctl_process_done(union ctl_io *io)
13065 {
13066 	struct ctl_lun *lun;
13067 	struct ctl_softc *softc = control_softc;
13068 	void (*fe_done)(union ctl_io *io);
13069 	union ctl_ha_msg msg;
13070 	uint32_t targ_port = io->io_hdr.nexus.targ_port;
13071 
13072 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13073 	fe_done = softc->ctl_ports[targ_port]->fe_done;
13074 
13075 #ifdef CTL_TIME_IO
13076 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13077 		char str[256];
13078 		char path_str[64];
13079 		struct sbuf sb;
13080 
13081 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13082 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13083 
13084 		sbuf_cat(&sb, path_str);
13085 		switch (io->io_hdr.io_type) {
13086 		case CTL_IO_SCSI:
13087 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13088 			sbuf_printf(&sb, "\n");
13089 			sbuf_cat(&sb, path_str);
13090 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13091 				    io->scsiio.tag_num, io->scsiio.tag_type);
13092 			break;
13093 		case CTL_IO_TASK:
13094 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13095 				    "Tag Type: %d\n", io->taskio.task_action,
13096 				    io->taskio.tag_num, io->taskio.tag_type);
13097 			break;
13098 		default:
13099 			panic("%s: Invalid CTL I/O type %d\n",
13100 			    __func__, io->io_hdr.io_type);
13101 		}
13102 		sbuf_cat(&sb, path_str);
13103 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13104 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13105 		sbuf_finish(&sb);
13106 		printf("%s", sbuf_data(&sb));
13107 	}
13108 #endif /* CTL_TIME_IO */
13109 
13110 	switch (io->io_hdr.io_type) {
13111 	case CTL_IO_SCSI:
13112 		break;
13113 	case CTL_IO_TASK:
13114 		if (ctl_debug & CTL_DEBUG_INFO)
13115 			ctl_io_error_print(io, NULL);
13116 		fe_done(io);
13117 		return;
13118 	default:
13119 		panic("%s: Invalid CTL I/O type %d\n",
13120 		    __func__, io->io_hdr.io_type);
13121 	}
13122 
13123 	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13124 	if (lun == NULL) {
13125 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13126 				 io->io_hdr.nexus.targ_mapped_lun));
13127 		goto bailout;
13128 	}
13129 
13130 	mtx_lock(&lun->lun_lock);
13131 
13132 	/*
13133 	 * Check to see if we have any errors to inject here.  We only
13134 	 * inject errors for commands that don't already have errors set.
13135 	 */
13136 	if (!STAILQ_EMPTY(&lun->error_list) &&
13137 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS) &&
13138 	    ((io->io_hdr.flags & CTL_FLAG_STATUS_SENT) == 0))
13139 		ctl_inject_error(lun, io);
13140 
13141 	/*
13142 	 * XXX KDM how do we treat commands that aren't completed
13143 	 * successfully?
13144 	 *
13145 	 * XXX KDM should we also track I/O latency?
13146 	 */
13147 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13148 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13149 #ifdef CTL_TIME_IO
13150 		struct bintime cur_bt;
13151 #endif
13152 		int type;
13153 
13154 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13155 		    CTL_FLAG_DATA_IN)
13156 			type = CTL_STATS_READ;
13157 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13158 		    CTL_FLAG_DATA_OUT)
13159 			type = CTL_STATS_WRITE;
13160 		else
13161 			type = CTL_STATS_NO_IO;
13162 
13163 		lun->stats.ports[targ_port].bytes[type] +=
13164 		    io->scsiio.kern_total_len;
13165 		lun->stats.ports[targ_port].operations[type]++;
13166 #ifdef CTL_TIME_IO
13167 		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13168 		   &io->io_hdr.dma_bt);
13169 		getbinuptime(&cur_bt);
13170 		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13171 		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13172 #endif
13173 		lun->stats.ports[targ_port].num_dmas[type] +=
13174 		    io->io_hdr.num_dmas;
13175 	}
13176 
13177 	/*
13178 	 * Remove this from the OOA queue.
13179 	 */
13180 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13181 #ifdef CTL_TIME_IO
13182 	if (TAILQ_EMPTY(&lun->ooa_queue))
13183 		lun->last_busy = getsbinuptime();
13184 #endif
13185 
13186 	/*
13187 	 * Run through the blocked queue on this LUN and see if anything
13188 	 * has become unblocked, now that this transaction is done.
13189 	 */
13190 	ctl_check_blocked(lun);
13191 
13192 	/*
13193 	 * If the LUN has been invalidated, free it if there is nothing
13194 	 * left on its OOA queue.
13195 	 */
13196 	if ((lun->flags & CTL_LUN_INVALID)
13197 	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13198 		mtx_unlock(&lun->lun_lock);
13199 		mtx_lock(&softc->ctl_lock);
13200 		ctl_free_lun(lun);
13201 		mtx_unlock(&softc->ctl_lock);
13202 	} else
13203 		mtx_unlock(&lun->lun_lock);
13204 
13205 bailout:
13206 
13207 	/*
13208 	 * If this command has been aborted, make sure we set the status
13209 	 * properly.  The FETD is responsible for freeing the I/O and doing
13210 	 * whatever it needs to do to clean up its state.
13211 	 */
13212 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13213 		ctl_set_task_aborted(&io->scsiio);
13214 
13215 	/*
13216 	 * If enabled, print command error status.
13217 	 */
13218 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS &&
13219 	    (ctl_debug & CTL_DEBUG_INFO) != 0)
13220 		ctl_io_error_print(io, NULL);
13221 
13222 	/*
13223 	 * Tell the FETD or the other shelf controller we're done with this
13224 	 * command.  Note that only SCSI commands get to this point.  Task
13225 	 * management commands are completed above.
13226 	 */
13227 	if ((softc->ha_mode != CTL_HA_MODE_XFER) &&
13228 	    (io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)) {
13229 		memset(&msg, 0, sizeof(msg));
13230 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13231 		msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13232 		msg.hdr.nexus = io->io_hdr.nexus;
13233 		ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13234 		    sizeof(msg.scsi) - sizeof(msg.scsi.sense_data),
13235 		    M_WAITOK);
13236 	}
13237 
13238 	fe_done(io);
13239 }
13240 
13241 #ifdef CTL_WITH_CA
13242 /*
13243  * Front end should call this if it doesn't do autosense.  When the request
13244  * sense comes back in from the initiator, we'll dequeue this and send it.
13245  */
13246 int
13247 ctl_queue_sense(union ctl_io *io)
13248 {
13249 	struct ctl_lun *lun;
13250 	struct ctl_port *port;
13251 	struct ctl_softc *softc;
13252 	uint32_t initidx, targ_lun;
13253 
13254 	softc = control_softc;
13255 
13256 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13257 
13258 	/*
13259 	 * LUN lookup will likely move to the ctl_work_thread() once we
13260 	 * have our new queueing infrastructure (that doesn't put things on
13261 	 * a per-LUN queue initially).  That is so that we can handle
13262 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13263 	 * can't deal with that right now.
13264 	 */
13265 	mtx_lock(&softc->ctl_lock);
13266 
13267 	/*
13268 	 * If we don't have a LUN for this, just toss the sense
13269 	 * information.
13270 	 */
13271 	port = ctl_io_port(&ctsio->io_hdr);
13272 	targ_lun = ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13273 	if ((targ_lun < CTL_MAX_LUNS)
13274 	 && (softc->ctl_luns[targ_lun] != NULL))
13275 		lun = softc->ctl_luns[targ_lun];
13276 	else
13277 		goto bailout;
13278 
13279 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13280 
13281 	mtx_lock(&lun->lun_lock);
13282 	/*
13283 	 * Already have CA set for this LUN...toss the sense information.
13284 	 */
13285 	if (ctl_is_set(lun->have_ca, initidx)) {
13286 		mtx_unlock(&lun->lun_lock);
13287 		goto bailout;
13288 	}
13289 
13290 	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13291 	       MIN(sizeof(lun->pending_sense[initidx]),
13292 	       sizeof(io->scsiio.sense_data)));
13293 	ctl_set_mask(lun->have_ca, initidx);
13294 	mtx_unlock(&lun->lun_lock);
13295 
13296 bailout:
13297 	mtx_unlock(&softc->ctl_lock);
13298 
13299 	ctl_free_io(io);
13300 
13301 	return (CTL_RETVAL_COMPLETE);
13302 }
13303 #endif
13304 
13305 /*
13306  * Primary command inlet from frontend ports.  All SCSI and task I/O
13307  * requests must go through this function.
13308  */
13309 int
13310 ctl_queue(union ctl_io *io)
13311 {
13312 	struct ctl_port *port;
13313 
13314 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
13315 
13316 #ifdef CTL_TIME_IO
13317 	io->io_hdr.start_time = time_uptime;
13318 	getbinuptime(&io->io_hdr.start_bt);
13319 #endif /* CTL_TIME_IO */
13320 
13321 	/* Map FE-specific LUN ID into global one. */
13322 	port = ctl_io_port(&io->io_hdr);
13323 	io->io_hdr.nexus.targ_mapped_lun =
13324 	    ctl_lun_map_from_port(port, io->io_hdr.nexus.targ_lun);
13325 
13326 	switch (io->io_hdr.io_type) {
13327 	case CTL_IO_SCSI:
13328 	case CTL_IO_TASK:
13329 		if (ctl_debug & CTL_DEBUG_CDB)
13330 			ctl_io_print(io);
13331 		ctl_enqueue_incoming(io);
13332 		break;
13333 	default:
13334 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
13335 		return (EINVAL);
13336 	}
13337 
13338 	return (CTL_RETVAL_COMPLETE);
13339 }
13340 
13341 #ifdef CTL_IO_DELAY
13342 static void
13343 ctl_done_timer_wakeup(void *arg)
13344 {
13345 	union ctl_io *io;
13346 
13347 	io = (union ctl_io *)arg;
13348 	ctl_done(io);
13349 }
13350 #endif /* CTL_IO_DELAY */
13351 
13352 void
13353 ctl_serseq_done(union ctl_io *io)
13354 {
13355 	struct ctl_lun *lun;
13356 
13357 	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13358 	if (lun->be_lun == NULL ||
13359 	    lun->be_lun->serseq == CTL_LUN_SERSEQ_OFF)
13360 		return;
13361 	mtx_lock(&lun->lun_lock);
13362 	io->io_hdr.flags |= CTL_FLAG_SERSEQ_DONE;
13363 	ctl_check_blocked(lun);
13364 	mtx_unlock(&lun->lun_lock);
13365 }
13366 
13367 void
13368 ctl_done(union ctl_io *io)
13369 {
13370 
13371 	/*
13372 	 * Enable this to catch duplicate completion issues.
13373 	 */
13374 #if 0
13375 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
13376 		printf("%s: type %d msg %d cdb %x iptl: "
13377 		       "%u:%u:%u tag 0x%04x "
13378 		       "flag %#x status %x\n",
13379 			__func__,
13380 			io->io_hdr.io_type,
13381 			io->io_hdr.msg_type,
13382 			io->scsiio.cdb[0],
13383 			io->io_hdr.nexus.initid,
13384 			io->io_hdr.nexus.targ_port,
13385 			io->io_hdr.nexus.targ_lun,
13386 			(io->io_hdr.io_type ==
13387 			CTL_IO_TASK) ?
13388 			io->taskio.tag_num :
13389 			io->scsiio.tag_num,
13390 		        io->io_hdr.flags,
13391 			io->io_hdr.status);
13392 	} else
13393 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
13394 #endif
13395 
13396 	/*
13397 	 * This is an internal copy of an I/O, and should not go through
13398 	 * the normal done processing logic.
13399 	 */
13400 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
13401 		return;
13402 
13403 #ifdef CTL_IO_DELAY
13404 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
13405 		struct ctl_lun *lun;
13406 
13407 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13408 
13409 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
13410 	} else {
13411 		struct ctl_lun *lun;
13412 
13413 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13414 
13415 		if ((lun != NULL)
13416 		 && (lun->delay_info.done_delay > 0)) {
13417 
13418 			callout_init(&io->io_hdr.delay_callout, /*mpsafe*/ 1);
13419 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
13420 			callout_reset(&io->io_hdr.delay_callout,
13421 				      lun->delay_info.done_delay * hz,
13422 				      ctl_done_timer_wakeup, io);
13423 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
13424 				lun->delay_info.done_delay = 0;
13425 			return;
13426 		}
13427 	}
13428 #endif /* CTL_IO_DELAY */
13429 
13430 	ctl_enqueue_done(io);
13431 }
13432 
13433 static void
13434 ctl_work_thread(void *arg)
13435 {
13436 	struct ctl_thread *thr = (struct ctl_thread *)arg;
13437 	struct ctl_softc *softc = thr->ctl_softc;
13438 	union ctl_io *io;
13439 	int retval;
13440 
13441 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
13442 
13443 	for (;;) {
13444 		/*
13445 		 * We handle the queues in this order:
13446 		 * - ISC
13447 		 * - done queue (to free up resources, unblock other commands)
13448 		 * - RtR queue
13449 		 * - incoming queue
13450 		 *
13451 		 * If those queues are empty, we break out of the loop and
13452 		 * go to sleep.
13453 		 */
13454 		mtx_lock(&thr->queue_lock);
13455 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
13456 		if (io != NULL) {
13457 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
13458 			mtx_unlock(&thr->queue_lock);
13459 			ctl_handle_isc(io);
13460 			continue;
13461 		}
13462 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
13463 		if (io != NULL) {
13464 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
13465 			/* clear any blocked commands, call fe_done */
13466 			mtx_unlock(&thr->queue_lock);
13467 			ctl_process_done(io);
13468 			continue;
13469 		}
13470 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
13471 		if (io != NULL) {
13472 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
13473 			mtx_unlock(&thr->queue_lock);
13474 			if (io->io_hdr.io_type == CTL_IO_TASK)
13475 				ctl_run_task(io);
13476 			else
13477 				ctl_scsiio_precheck(softc, &io->scsiio);
13478 			continue;
13479 		}
13480 		io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
13481 		if (io != NULL) {
13482 			STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
13483 			mtx_unlock(&thr->queue_lock);
13484 			retval = ctl_scsiio(&io->scsiio);
13485 			if (retval != CTL_RETVAL_COMPLETE)
13486 				CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
13487 			continue;
13488 		}
13489 
13490 		/* Sleep until we have something to do. */
13491 		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
13492 	}
13493 }
13494 
13495 static void
13496 ctl_lun_thread(void *arg)
13497 {
13498 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13499 	struct ctl_be_lun *be_lun;
13500 
13501 	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
13502 
13503 	for (;;) {
13504 		mtx_lock(&softc->ctl_lock);
13505 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
13506 		if (be_lun != NULL) {
13507 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
13508 			mtx_unlock(&softc->ctl_lock);
13509 			ctl_create_lun(be_lun);
13510 			continue;
13511 		}
13512 
13513 		/* Sleep until we have something to do. */
13514 		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
13515 		    PDROP | PRIBIO, "-", 0);
13516 	}
13517 }
13518 
13519 static void
13520 ctl_thresh_thread(void *arg)
13521 {
13522 	struct ctl_softc *softc = (struct ctl_softc *)arg;
13523 	struct ctl_lun *lun;
13524 	struct scsi_da_rw_recovery_page *rwpage;
13525 	struct ctl_logical_block_provisioning_page *page;
13526 	const char *attr;
13527 	union ctl_ha_msg msg;
13528 	uint64_t thres, val;
13529 	int i, e, set;
13530 
13531 	CTL_DEBUG_PRINT(("ctl_thresh_thread starting\n"));
13532 
13533 	for (;;) {
13534 		mtx_lock(&softc->ctl_lock);
13535 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
13536 			if ((lun->flags & CTL_LUN_DISABLED) ||
13537 			    (lun->flags & CTL_LUN_NO_MEDIA) ||
13538 			    lun->backend->lun_attr == NULL)
13539 				continue;
13540 			if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0 &&
13541 			    softc->ha_mode == CTL_HA_MODE_XFER)
13542 				continue;
13543 			rwpage = &lun->mode_pages.rw_er_page[CTL_PAGE_CURRENT];
13544 			if ((rwpage->byte8 & SMS_RWER_LBPERE) == 0)
13545 				continue;
13546 			e = 0;
13547 			page = &lun->mode_pages.lbp_page[CTL_PAGE_CURRENT];
13548 			for (i = 0; i < CTL_NUM_LBP_THRESH; i++) {
13549 				if ((page->descr[i].flags & SLBPPD_ENABLED) == 0)
13550 					continue;
13551 				thres = scsi_4btoul(page->descr[i].count);
13552 				thres <<= CTL_LBP_EXPONENT;
13553 				switch (page->descr[i].resource) {
13554 				case 0x01:
13555 					attr = "blocksavail";
13556 					break;
13557 				case 0x02:
13558 					attr = "blocksused";
13559 					break;
13560 				case 0xf1:
13561 					attr = "poolblocksavail";
13562 					break;
13563 				case 0xf2:
13564 					attr = "poolblocksused";
13565 					break;
13566 				default:
13567 					continue;
13568 				}
13569 				mtx_unlock(&softc->ctl_lock); // XXX
13570 				val = lun->backend->lun_attr(
13571 				    lun->be_lun->be_lun, attr);
13572 				mtx_lock(&softc->ctl_lock);
13573 				if (val == UINT64_MAX)
13574 					continue;
13575 				if ((page->descr[i].flags & SLBPPD_ARMING_MASK)
13576 				    == SLBPPD_ARMING_INC)
13577 					e = (val >= thres);
13578 				else
13579 					e = (val <= thres);
13580 				if (e)
13581 					break;
13582 			}
13583 			mtx_lock(&lun->lun_lock);
13584 			if (e) {
13585 				scsi_u64to8b((uint8_t *)&page->descr[i] -
13586 				    (uint8_t *)page, lun->ua_tpt_info);
13587 				if (lun->lasttpt == 0 ||
13588 				    time_uptime - lun->lasttpt >= CTL_LBP_UA_PERIOD) {
13589 					lun->lasttpt = time_uptime;
13590 					ctl_est_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13591 					set = 1;
13592 				} else
13593 					set = 0;
13594 			} else {
13595 				lun->lasttpt = 0;
13596 				ctl_clr_ua_all(lun, -1, CTL_UA_THIN_PROV_THRES);
13597 				set = -1;
13598 			}
13599 			mtx_unlock(&lun->lun_lock);
13600 			if (set != 0 &&
13601 			    lun->ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
13602 				/* Send msg to other side. */
13603 				bzero(&msg.ua, sizeof(msg.ua));
13604 				msg.hdr.msg_type = CTL_MSG_UA;
13605 				msg.hdr.nexus.initid = -1;
13606 				msg.hdr.nexus.targ_port = -1;
13607 				msg.hdr.nexus.targ_lun = lun->lun;
13608 				msg.hdr.nexus.targ_mapped_lun = lun->lun;
13609 				msg.ua.ua_all = 1;
13610 				msg.ua.ua_set = (set > 0);
13611 				msg.ua.ua_type = CTL_UA_THIN_PROV_THRES;
13612 				memcpy(msg.ua.ua_info, lun->ua_tpt_info, 8);
13613 				mtx_unlock(&softc->ctl_lock); // XXX
13614 				ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13615 				    sizeof(msg.ua), M_WAITOK);
13616 				mtx_lock(&softc->ctl_lock);
13617 			}
13618 		}
13619 		mtx_unlock(&softc->ctl_lock);
13620 		pause("-", CTL_LBP_PERIOD * hz);
13621 	}
13622 }
13623 
13624 static void
13625 ctl_enqueue_incoming(union ctl_io *io)
13626 {
13627 	struct ctl_softc *softc = control_softc;
13628 	struct ctl_thread *thr;
13629 	u_int idx;
13630 
13631 	idx = (io->io_hdr.nexus.targ_port * 127 +
13632 	       io->io_hdr.nexus.initid) % worker_threads;
13633 	thr = &softc->threads[idx];
13634 	mtx_lock(&thr->queue_lock);
13635 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
13636 	mtx_unlock(&thr->queue_lock);
13637 	wakeup(thr);
13638 }
13639 
13640 static void
13641 ctl_enqueue_rtr(union ctl_io *io)
13642 {
13643 	struct ctl_softc *softc = control_softc;
13644 	struct ctl_thread *thr;
13645 
13646 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13647 	mtx_lock(&thr->queue_lock);
13648 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
13649 	mtx_unlock(&thr->queue_lock);
13650 	wakeup(thr);
13651 }
13652 
13653 static void
13654 ctl_enqueue_done(union ctl_io *io)
13655 {
13656 	struct ctl_softc *softc = control_softc;
13657 	struct ctl_thread *thr;
13658 
13659 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13660 	mtx_lock(&thr->queue_lock);
13661 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
13662 	mtx_unlock(&thr->queue_lock);
13663 	wakeup(thr);
13664 }
13665 
13666 static void
13667 ctl_enqueue_isc(union ctl_io *io)
13668 {
13669 	struct ctl_softc *softc = control_softc;
13670 	struct ctl_thread *thr;
13671 
13672 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
13673 	mtx_lock(&thr->queue_lock);
13674 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
13675 	mtx_unlock(&thr->queue_lock);
13676 	wakeup(thr);
13677 }
13678 
13679 /*
13680  *  vim: ts=8
13681  */
13682