xref: /freebsd/sys/cam/ctl/ctl.c (revision 6186fd1857626de0f7cb1a9e4dff19082f9ebb11)
1 /*-
2  * Copyright (c) 2003-2009 Silicon Graphics International Corp.
3  * Copyright (c) 2012 The FreeBSD Foundation
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Edward Tomasz Napierala
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions, and the following disclaimer,
14  *    without modification.
15  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
16  *    substantially similar to the "NO WARRANTY" disclaimer below
17  *    ("Disclaimer") and any redistribution must be conditioned upon
18  *    including a substantially similar Disclaimer requirement for further
19  *    binary redistribution.
20  *
21  * NO WARRANTY
22  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
25  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
26  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
31  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGES.
33  *
34  * $Id: //depot/users/kenm/FreeBSD-test2/sys/cam/ctl/ctl.c#8 $
35  */
36 /*
37  * CAM Target Layer, a SCSI device emulation subsystem.
38  *
39  * Author: Ken Merry <ken@FreeBSD.org>
40  */
41 
42 #define _CTL_C
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/kernel.h>
50 #include <sys/types.h>
51 #include <sys/kthread.h>
52 #include <sys/bio.h>
53 #include <sys/fcntl.h>
54 #include <sys/lock.h>
55 #include <sys/module.h>
56 #include <sys/mutex.h>
57 #include <sys/condvar.h>
58 #include <sys/malloc.h>
59 #include <sys/conf.h>
60 #include <sys/ioccom.h>
61 #include <sys/queue.h>
62 #include <sys/sbuf.h>
63 #include <sys/smp.h>
64 #include <sys/endian.h>
65 #include <sys/sysctl.h>
66 
67 #include <cam/cam.h>
68 #include <cam/scsi/scsi_all.h>
69 #include <cam/scsi/scsi_da.h>
70 #include <cam/ctl/ctl_io.h>
71 #include <cam/ctl/ctl.h>
72 #include <cam/ctl/ctl_frontend.h>
73 #include <cam/ctl/ctl_frontend_internal.h>
74 #include <cam/ctl/ctl_util.h>
75 #include <cam/ctl/ctl_backend.h>
76 #include <cam/ctl/ctl_ioctl.h>
77 #include <cam/ctl/ctl_ha.h>
78 #include <cam/ctl/ctl_private.h>
79 #include <cam/ctl/ctl_debug.h>
80 #include <cam/ctl/ctl_scsi_all.h>
81 #include <cam/ctl/ctl_error.h>
82 
83 struct ctl_softc *control_softc = NULL;
84 
85 /*
86  * Size and alignment macros needed for Copan-specific HA hardware.  These
87  * can go away when the HA code is re-written, and uses busdma for any
88  * hardware.
89  */
90 #define	CTL_ALIGN_8B(target, source, type)				\
91 	if (((uint32_t)source & 0x7) != 0)				\
92 		target = (type)(source + (0x8 - ((uint32_t)source & 0x7)));\
93 	else								\
94 		target = (type)source;
95 
96 #define	CTL_SIZE_8B(target, size)					\
97 	if ((size & 0x7) != 0)						\
98 		target = size + (0x8 - (size & 0x7));			\
99 	else								\
100 		target = size;
101 
102 #define CTL_ALIGN_8B_MARGIN	16
103 
104 /*
105  * Template mode pages.
106  */
107 
108 /*
109  * Note that these are default values only.  The actual values will be
110  * filled in when the user does a mode sense.
111  */
112 static struct copan_power_subpage power_page_default = {
113 	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
114 	/*subpage*/ PWR_SUBPAGE_CODE,
115 	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
116 			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
117 	/*page_version*/ PWR_VERSION,
118 	/* total_luns */ 26,
119 	/* max_active_luns*/ PWR_DFLT_MAX_LUNS,
120 	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
121 		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
122 		      0, 0, 0, 0, 0, 0}
123 };
124 
125 static struct copan_power_subpage power_page_changeable = {
126 	/*page_code*/ PWR_PAGE_CODE | SMPH_SPF,
127 	/*subpage*/ PWR_SUBPAGE_CODE,
128 	/*page_length*/ {(sizeof(struct copan_power_subpage) - 4) & 0xff00,
129 			 (sizeof(struct copan_power_subpage) - 4) & 0x00ff},
130 	/*page_version*/ 0,
131 	/* total_luns */ 0,
132 	/* max_active_luns*/ 0,
133 	/*reserved*/ {0, 0, 0, 0, 0, 0, 0, 0, 0,
134 		      0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
135 		      0, 0, 0, 0, 0, 0}
136 };
137 
138 static struct copan_aps_subpage aps_page_default = {
139 	APS_PAGE_CODE | SMPH_SPF, //page_code
140 	APS_SUBPAGE_CODE, //subpage
141 	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
142 	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
143 	APS_VERSION, //page_version
144 	0, //lock_active
145 	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
146 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
147 	0, 0, 0, 0, 0} //reserved
148 };
149 
150 static struct copan_aps_subpage aps_page_changeable = {
151 	APS_PAGE_CODE | SMPH_SPF, //page_code
152 	APS_SUBPAGE_CODE, //subpage
153 	{(sizeof(struct copan_aps_subpage) - 4) & 0xff00,
154 	 (sizeof(struct copan_aps_subpage) - 4) & 0x00ff}, //page_length
155 	0, //page_version
156 	0, //lock_active
157 	{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
158 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
159 	0, 0, 0, 0, 0} //reserved
160 };
161 
162 static struct copan_debugconf_subpage debugconf_page_default = {
163 	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
164 	DBGCNF_SUBPAGE_CODE,		/* subpage */
165 	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
166 	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
167 	DBGCNF_VERSION,			/* page_version */
168 	{CTL_TIME_IO_DEFAULT_SECS>>8,
169 	 CTL_TIME_IO_DEFAULT_SECS>>0},	/* ctl_time_io_secs */
170 };
171 
172 static struct copan_debugconf_subpage debugconf_page_changeable = {
173 	DBGCNF_PAGE_CODE | SMPH_SPF,	/* page_code */
174 	DBGCNF_SUBPAGE_CODE,		/* subpage */
175 	{(sizeof(struct copan_debugconf_subpage) - 4) >> 8,
176 	 (sizeof(struct copan_debugconf_subpage) - 4) >> 0}, /* page_length */
177 	0,				/* page_version */
178 	{0xff,0xff},			/* ctl_time_io_secs */
179 };
180 
181 static struct scsi_format_page format_page_default = {
182 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
183 	/*page_length*/sizeof(struct scsi_format_page) - 2,
184 	/*tracks_per_zone*/ {0, 0},
185 	/*alt_sectors_per_zone*/ {0, 0},
186 	/*alt_tracks_per_zone*/ {0, 0},
187 	/*alt_tracks_per_lun*/ {0, 0},
188 	/*sectors_per_track*/ {(CTL_DEFAULT_SECTORS_PER_TRACK >> 8) & 0xff,
189 			        CTL_DEFAULT_SECTORS_PER_TRACK & 0xff},
190 	/*bytes_per_sector*/ {0, 0},
191 	/*interleave*/ {0, 0},
192 	/*track_skew*/ {0, 0},
193 	/*cylinder_skew*/ {0, 0},
194 	/*flags*/ SFP_HSEC,
195 	/*reserved*/ {0, 0, 0}
196 };
197 
198 static struct scsi_format_page format_page_changeable = {
199 	/*page_code*/SMS_FORMAT_DEVICE_PAGE,
200 	/*page_length*/sizeof(struct scsi_format_page) - 2,
201 	/*tracks_per_zone*/ {0, 0},
202 	/*alt_sectors_per_zone*/ {0, 0},
203 	/*alt_tracks_per_zone*/ {0, 0},
204 	/*alt_tracks_per_lun*/ {0, 0},
205 	/*sectors_per_track*/ {0, 0},
206 	/*bytes_per_sector*/ {0, 0},
207 	/*interleave*/ {0, 0},
208 	/*track_skew*/ {0, 0},
209 	/*cylinder_skew*/ {0, 0},
210 	/*flags*/ 0,
211 	/*reserved*/ {0, 0, 0}
212 };
213 
214 static struct scsi_rigid_disk_page rigid_disk_page_default = {
215 	/*page_code*/SMS_RIGID_DISK_PAGE,
216 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
217 	/*cylinders*/ {0, 0, 0},
218 	/*heads*/ CTL_DEFAULT_HEADS,
219 	/*start_write_precomp*/ {0, 0, 0},
220 	/*start_reduced_current*/ {0, 0, 0},
221 	/*step_rate*/ {0, 0},
222 	/*landing_zone_cylinder*/ {0, 0, 0},
223 	/*rpl*/ SRDP_RPL_DISABLED,
224 	/*rotational_offset*/ 0,
225 	/*reserved1*/ 0,
226 	/*rotation_rate*/ {(CTL_DEFAULT_ROTATION_RATE >> 8) & 0xff,
227 			   CTL_DEFAULT_ROTATION_RATE & 0xff},
228 	/*reserved2*/ {0, 0}
229 };
230 
231 static struct scsi_rigid_disk_page rigid_disk_page_changeable = {
232 	/*page_code*/SMS_RIGID_DISK_PAGE,
233 	/*page_length*/sizeof(struct scsi_rigid_disk_page) - 2,
234 	/*cylinders*/ {0, 0, 0},
235 	/*heads*/ 0,
236 	/*start_write_precomp*/ {0, 0, 0},
237 	/*start_reduced_current*/ {0, 0, 0},
238 	/*step_rate*/ {0, 0},
239 	/*landing_zone_cylinder*/ {0, 0, 0},
240 	/*rpl*/ 0,
241 	/*rotational_offset*/ 0,
242 	/*reserved1*/ 0,
243 	/*rotation_rate*/ {0, 0},
244 	/*reserved2*/ {0, 0}
245 };
246 
247 static struct scsi_caching_page caching_page_default = {
248 	/*page_code*/SMS_CACHING_PAGE,
249 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
250 	/*flags1*/ SCP_DISC | SCP_WCE,
251 	/*ret_priority*/ 0,
252 	/*disable_pf_transfer_len*/ {0xff, 0xff},
253 	/*min_prefetch*/ {0, 0},
254 	/*max_prefetch*/ {0xff, 0xff},
255 	/*max_pf_ceiling*/ {0xff, 0xff},
256 	/*flags2*/ 0,
257 	/*cache_segments*/ 0,
258 	/*cache_seg_size*/ {0, 0},
259 	/*reserved*/ 0,
260 	/*non_cache_seg_size*/ {0, 0, 0}
261 };
262 
263 static struct scsi_caching_page caching_page_changeable = {
264 	/*page_code*/SMS_CACHING_PAGE,
265 	/*page_length*/sizeof(struct scsi_caching_page) - 2,
266 	/*flags1*/ SCP_WCE | SCP_RCD,
267 	/*ret_priority*/ 0,
268 	/*disable_pf_transfer_len*/ {0, 0},
269 	/*min_prefetch*/ {0, 0},
270 	/*max_prefetch*/ {0, 0},
271 	/*max_pf_ceiling*/ {0, 0},
272 	/*flags2*/ 0,
273 	/*cache_segments*/ 0,
274 	/*cache_seg_size*/ {0, 0},
275 	/*reserved*/ 0,
276 	/*non_cache_seg_size*/ {0, 0, 0}
277 };
278 
279 static struct scsi_control_page control_page_default = {
280 	/*page_code*/SMS_CONTROL_MODE_PAGE,
281 	/*page_length*/sizeof(struct scsi_control_page) - 2,
282 	/*rlec*/0,
283 	/*queue_flags*/SCP_QUEUE_ALG_RESTRICTED,
284 	/*eca_and_aen*/0,
285 	/*flags4*/SCP_TAS,
286 	/*aen_holdoff_period*/{0, 0},
287 	/*busy_timeout_period*/{0, 0},
288 	/*extended_selftest_completion_time*/{0, 0}
289 };
290 
291 static struct scsi_control_page control_page_changeable = {
292 	/*page_code*/SMS_CONTROL_MODE_PAGE,
293 	/*page_length*/sizeof(struct scsi_control_page) - 2,
294 	/*rlec*/SCP_DSENSE,
295 	/*queue_flags*/SCP_QUEUE_ALG_MASK,
296 	/*eca_and_aen*/SCP_SWP,
297 	/*flags4*/0,
298 	/*aen_holdoff_period*/{0, 0},
299 	/*busy_timeout_period*/{0, 0},
300 	/*extended_selftest_completion_time*/{0, 0}
301 };
302 
303 
304 /*
305  * XXX KDM move these into the softc.
306  */
307 static int rcv_sync_msg;
308 static int persis_offset;
309 static uint8_t ctl_pause_rtr;
310 static int     ctl_is_single = 1;
311 static int     index_to_aps_page;
312 
313 SYSCTL_NODE(_kern_cam, OID_AUTO, ctl, CTLFLAG_RD, 0, "CAM Target Layer");
314 static int worker_threads = -1;
315 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, worker_threads, CTLFLAG_RDTUN,
316     &worker_threads, 1, "Number of worker threads");
317 static int verbose = 0;
318 SYSCTL_INT(_kern_cam_ctl, OID_AUTO, verbose, CTLFLAG_RWTUN,
319     &verbose, 0, "Show SCSI errors returned to initiator");
320 
321 /*
322  * Supported pages (0x00), Serial number (0x80), Device ID (0x83),
323  * Extended INQUIRY Data (0x86), Mode Page Policy (0x87),
324  * SCSI Ports (0x88), Third-party Copy (0x8F), Block limits (0xB0),
325  * Block Device Characteristics (0xB1) and Logical Block Provisioning (0xB2)
326  */
327 #define SCSI_EVPD_NUM_SUPPORTED_PAGES	10
328 
329 static void ctl_isc_event_handler(ctl_ha_channel chanel, ctl_ha_event event,
330 				  int param);
331 static void ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest);
332 static int ctl_init(void);
333 void ctl_shutdown(void);
334 static int ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td);
335 static int ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td);
336 static void ctl_ioctl_online(void *arg);
337 static void ctl_ioctl_offline(void *arg);
338 static int ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id);
339 static int ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id);
340 static int ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio);
341 static int ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio);
342 static int ctl_ioctl_submit_wait(union ctl_io *io);
343 static void ctl_ioctl_datamove(union ctl_io *io);
344 static void ctl_ioctl_done(union ctl_io *io);
345 static void ctl_ioctl_hard_startstop_callback(void *arg,
346 					      struct cfi_metatask *metatask);
347 static void ctl_ioctl_bbrread_callback(void *arg,struct cfi_metatask *metatask);
348 static int ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
349 			      struct ctl_ooa *ooa_hdr,
350 			      struct ctl_ooa_entry *kern_entries);
351 static int ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
352 		     struct thread *td);
353 static uint32_t ctl_map_lun(int port_num, uint32_t lun);
354 static uint32_t ctl_map_lun_back(int port_num, uint32_t lun);
355 #ifdef unused
356 static union ctl_io *ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port,
357 				   uint32_t targ_target, uint32_t targ_lun,
358 				   int can_wait);
359 static void ctl_kfree_io(union ctl_io *io);
360 #endif /* unused */
361 static int ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
362 			 struct ctl_be_lun *be_lun, struct ctl_id target_id);
363 static int ctl_free_lun(struct ctl_lun *lun);
364 static void ctl_create_lun(struct ctl_be_lun *be_lun);
365 /**
366 static void ctl_failover_change_pages(struct ctl_softc *softc,
367 				      struct ctl_scsiio *ctsio, int master);
368 **/
369 
370 static int ctl_do_mode_select(union ctl_io *io);
371 static int ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun,
372 			   uint64_t res_key, uint64_t sa_res_key,
373 			   uint8_t type, uint32_t residx,
374 			   struct ctl_scsiio *ctsio,
375 			   struct scsi_per_res_out *cdb,
376 			   struct scsi_per_res_out_parms* param);
377 static void ctl_pro_preempt_other(struct ctl_lun *lun,
378 				  union ctl_ha_msg *msg);
379 static void ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg);
380 static int ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len);
381 static int ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len);
382 static int ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len);
383 static int ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len);
384 static int ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len);
385 static int ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio,
386 					 int alloc_len);
387 static int ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio,
388 					 int alloc_len);
389 static int ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len);
390 static int ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len);
391 static int ctl_inquiry_evpd(struct ctl_scsiio *ctsio);
392 static int ctl_inquiry_std(struct ctl_scsiio *ctsio);
393 static int ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len);
394 static ctl_action ctl_extent_check(union ctl_io *io1, union ctl_io *io2);
395 static ctl_action ctl_check_for_blockage(struct ctl_lun *lun,
396     union ctl_io *pending_io, union ctl_io *ooa_io);
397 static ctl_action ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
398 				union ctl_io *starting_io);
399 static int ctl_check_blocked(struct ctl_lun *lun);
400 static int ctl_scsiio_lun_check(struct ctl_softc *ctl_softc,
401 				struct ctl_lun *lun,
402 				const struct ctl_cmd_entry *entry,
403 				struct ctl_scsiio *ctsio);
404 //static int ctl_check_rtr(union ctl_io *pending_io, struct ctl_softc *softc);
405 static void ctl_failover(void);
406 static int ctl_scsiio_precheck(struct ctl_softc *ctl_softc,
407 			       struct ctl_scsiio *ctsio);
408 static int ctl_scsiio(struct ctl_scsiio *ctsio);
409 
410 static int ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io);
411 static int ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
412 			    ctl_ua_type ua_type);
413 static int ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io,
414 			 ctl_ua_type ua_type);
415 static int ctl_abort_task(union ctl_io *io);
416 static int ctl_abort_task_set(union ctl_io *io);
417 static int ctl_i_t_nexus_reset(union ctl_io *io);
418 static void ctl_run_task(union ctl_io *io);
419 #ifdef CTL_IO_DELAY
420 static void ctl_datamove_timer_wakeup(void *arg);
421 static void ctl_done_timer_wakeup(void *arg);
422 #endif /* CTL_IO_DELAY */
423 
424 static void ctl_send_datamove_done(union ctl_io *io, int have_lock);
425 static void ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq);
426 static int ctl_datamove_remote_dm_write_cb(union ctl_io *io);
427 static void ctl_datamove_remote_write(union ctl_io *io);
428 static int ctl_datamove_remote_dm_read_cb(union ctl_io *io);
429 static void ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq);
430 static int ctl_datamove_remote_sgl_setup(union ctl_io *io);
431 static int ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
432 				    ctl_ha_dt_cb callback);
433 static void ctl_datamove_remote_read(union ctl_io *io);
434 static void ctl_datamove_remote(union ctl_io *io);
435 static int ctl_process_done(union ctl_io *io);
436 static void ctl_lun_thread(void *arg);
437 static void ctl_work_thread(void *arg);
438 static void ctl_enqueue_incoming(union ctl_io *io);
439 static void ctl_enqueue_rtr(union ctl_io *io);
440 static void ctl_enqueue_done(union ctl_io *io);
441 static void ctl_enqueue_isc(union ctl_io *io);
442 static const struct ctl_cmd_entry *
443     ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa);
444 static const struct ctl_cmd_entry *
445     ctl_validate_command(struct ctl_scsiio *ctsio);
446 static int ctl_cmd_applicable(uint8_t lun_type,
447     const struct ctl_cmd_entry *entry);
448 
449 /*
450  * Load the serialization table.  This isn't very pretty, but is probably
451  * the easiest way to do it.
452  */
453 #include "ctl_ser_table.c"
454 
455 /*
456  * We only need to define open, close and ioctl routines for this driver.
457  */
458 static struct cdevsw ctl_cdevsw = {
459 	.d_version =	D_VERSION,
460 	.d_flags =	0,
461 	.d_open =	ctl_open,
462 	.d_close =	ctl_close,
463 	.d_ioctl =	ctl_ioctl,
464 	.d_name =	"ctl",
465 };
466 
467 
468 MALLOC_DEFINE(M_CTL, "ctlmem", "Memory used for CTL");
469 MALLOC_DEFINE(M_CTLIO, "ctlio", "Memory used for CTL requests");
470 
471 static int ctl_module_event_handler(module_t, int /*modeventtype_t*/, void *);
472 
473 static moduledata_t ctl_moduledata = {
474 	"ctl",
475 	ctl_module_event_handler,
476 	NULL
477 };
478 
479 DECLARE_MODULE(ctl, ctl_moduledata, SI_SUB_CONFIGURE, SI_ORDER_THIRD);
480 MODULE_VERSION(ctl, 1);
481 
482 static struct ctl_frontend ioctl_frontend =
483 {
484 	.name = "ioctl",
485 };
486 
487 static void
488 ctl_isc_handler_finish_xfer(struct ctl_softc *ctl_softc,
489 			    union ctl_ha_msg *msg_info)
490 {
491 	struct ctl_scsiio *ctsio;
492 
493 	if (msg_info->hdr.original_sc == NULL) {
494 		printf("%s: original_sc == NULL!\n", __func__);
495 		/* XXX KDM now what? */
496 		return;
497 	}
498 
499 	ctsio = &msg_info->hdr.original_sc->scsiio;
500 	ctsio->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
501 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
502 	ctsio->io_hdr.status = msg_info->hdr.status;
503 	ctsio->scsi_status = msg_info->scsi.scsi_status;
504 	ctsio->sense_len = msg_info->scsi.sense_len;
505 	ctsio->sense_residual = msg_info->scsi.sense_residual;
506 	ctsio->residual = msg_info->scsi.residual;
507 	memcpy(&ctsio->sense_data, &msg_info->scsi.sense_data,
508 	       sizeof(ctsio->sense_data));
509 	memcpy(&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
510 	       &msg_info->scsi.lbalen, sizeof(msg_info->scsi.lbalen));
511 	ctl_enqueue_isc((union ctl_io *)ctsio);
512 }
513 
514 static void
515 ctl_isc_handler_finish_ser_only(struct ctl_softc *ctl_softc,
516 				union ctl_ha_msg *msg_info)
517 {
518 	struct ctl_scsiio *ctsio;
519 
520 	if (msg_info->hdr.serializing_sc == NULL) {
521 		printf("%s: serializing_sc == NULL!\n", __func__);
522 		/* XXX KDM now what? */
523 		return;
524 	}
525 
526 	ctsio = &msg_info->hdr.serializing_sc->scsiio;
527 #if 0
528 	/*
529 	 * Attempt to catch the situation where an I/O has
530 	 * been freed, and we're using it again.
531 	 */
532 	if (ctsio->io_hdr.io_type == 0xff) {
533 		union ctl_io *tmp_io;
534 		tmp_io = (union ctl_io *)ctsio;
535 		printf("%s: %p use after free!\n", __func__,
536 		       ctsio);
537 		printf("%s: type %d msg %d cdb %x iptl: "
538 		       "%d:%d:%d:%d tag 0x%04x "
539 		       "flag %#x status %x\n",
540 			__func__,
541 			tmp_io->io_hdr.io_type,
542 			tmp_io->io_hdr.msg_type,
543 			tmp_io->scsiio.cdb[0],
544 			tmp_io->io_hdr.nexus.initid.id,
545 			tmp_io->io_hdr.nexus.targ_port,
546 			tmp_io->io_hdr.nexus.targ_target.id,
547 			tmp_io->io_hdr.nexus.targ_lun,
548 			(tmp_io->io_hdr.io_type ==
549 			CTL_IO_TASK) ?
550 			tmp_io->taskio.tag_num :
551 			tmp_io->scsiio.tag_num,
552 		        tmp_io->io_hdr.flags,
553 			tmp_io->io_hdr.status);
554 	}
555 #endif
556 	ctsio->io_hdr.msg_type = CTL_MSG_FINISH_IO;
557 	ctl_enqueue_isc((union ctl_io *)ctsio);
558 }
559 
560 /*
561  * ISC (Inter Shelf Communication) event handler.  Events from the HA
562  * subsystem come in here.
563  */
564 static void
565 ctl_isc_event_handler(ctl_ha_channel channel, ctl_ha_event event, int param)
566 {
567 	struct ctl_softc *ctl_softc;
568 	union ctl_io *io;
569 	struct ctl_prio *presio;
570 	ctl_ha_status isc_status;
571 
572 	ctl_softc = control_softc;
573 	io = NULL;
574 
575 
576 #if 0
577 	printf("CTL: Isc Msg event %d\n", event);
578 #endif
579 	if (event == CTL_HA_EVT_MSG_RECV) {
580 		union ctl_ha_msg msg_info;
581 
582 		isc_status = ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
583 					     sizeof(msg_info), /*wait*/ 0);
584 #if 0
585 		printf("CTL: msg_type %d\n", msg_info.msg_type);
586 #endif
587 		if (isc_status != 0) {
588 			printf("Error receiving message, status = %d\n",
589 			       isc_status);
590 			return;
591 		}
592 
593 		switch (msg_info.hdr.msg_type) {
594 		case CTL_MSG_SERIALIZE:
595 #if 0
596 			printf("Serialize\n");
597 #endif
598 			io = ctl_alloc_io((void *)ctl_softc->othersc_pool);
599 			if (io == NULL) {
600 				printf("ctl_isc_event_handler: can't allocate "
601 				       "ctl_io!\n");
602 				/* Bad Juju */
603 				/* Need to set busy and send msg back */
604 				msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
605 				msg_info.hdr.status = CTL_SCSI_ERROR;
606 				msg_info.scsi.scsi_status = SCSI_STATUS_BUSY;
607 				msg_info.scsi.sense_len = 0;
608 			        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
609 				    sizeof(msg_info), 0) > CTL_HA_STATUS_SUCCESS){
610 				}
611 				goto bailout;
612 			}
613 			ctl_zero_io(io);
614 			// populate ctsio from msg_info
615 			io->io_hdr.io_type = CTL_IO_SCSI;
616 			io->io_hdr.msg_type = CTL_MSG_SERIALIZE;
617 			io->io_hdr.original_sc = msg_info.hdr.original_sc;
618 #if 0
619 			printf("pOrig %x\n", (int)msg_info.original_sc);
620 #endif
621 			io->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC |
622 					    CTL_FLAG_IO_ACTIVE;
623 			/*
624 			 * If we're in serialization-only mode, we don't
625 			 * want to go through full done processing.  Thus
626 			 * the COPY flag.
627 			 *
628 			 * XXX KDM add another flag that is more specific.
629 			 */
630 			if (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)
631 				io->io_hdr.flags |= CTL_FLAG_INT_COPY;
632 			io->io_hdr.nexus = msg_info.hdr.nexus;
633 #if 0
634 			printf("targ %d, port %d, iid %d, lun %d\n",
635 			       io->io_hdr.nexus.targ_target.id,
636 			       io->io_hdr.nexus.targ_port,
637 			       io->io_hdr.nexus.initid.id,
638 			       io->io_hdr.nexus.targ_lun);
639 #endif
640 			io->scsiio.tag_num = msg_info.scsi.tag_num;
641 			io->scsiio.tag_type = msg_info.scsi.tag_type;
642 			memcpy(io->scsiio.cdb, msg_info.scsi.cdb,
643 			       CTL_MAX_CDBLEN);
644 			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
645 				const struct ctl_cmd_entry *entry;
646 
647 				entry = ctl_get_cmd_entry(&io->scsiio, NULL);
648 				io->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
649 				io->io_hdr.flags |=
650 					entry->flags & CTL_FLAG_DATA_MASK;
651 			}
652 			ctl_enqueue_isc(io);
653 			break;
654 
655 		/* Performed on the Originating SC, XFER mode only */
656 		case CTL_MSG_DATAMOVE: {
657 			struct ctl_sg_entry *sgl;
658 			int i, j;
659 
660 			io = msg_info.hdr.original_sc;
661 			if (io == NULL) {
662 				printf("%s: original_sc == NULL!\n", __func__);
663 				/* XXX KDM do something here */
664 				break;
665 			}
666 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE;
667 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
668 			/*
669 			 * Keep track of this, we need to send it back over
670 			 * when the datamove is complete.
671 			 */
672 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
673 
674 			if (msg_info.dt.sg_sequence == 0) {
675 				/*
676 				 * XXX KDM we use the preallocated S/G list
677 				 * here, but we'll need to change this to
678 				 * dynamic allocation if we need larger S/G
679 				 * lists.
680 				 */
681 				if (msg_info.dt.kern_sg_entries >
682 				    sizeof(io->io_hdr.remote_sglist) /
683 				    sizeof(io->io_hdr.remote_sglist[0])) {
684 					printf("%s: number of S/G entries "
685 					    "needed %u > allocated num %zd\n",
686 					    __func__,
687 					    msg_info.dt.kern_sg_entries,
688 					    sizeof(io->io_hdr.remote_sglist)/
689 					    sizeof(io->io_hdr.remote_sglist[0]));
690 
691 					/*
692 					 * XXX KDM send a message back to
693 					 * the other side to shut down the
694 					 * DMA.  The error will come back
695 					 * through via the normal channel.
696 					 */
697 					break;
698 				}
699 				sgl = io->io_hdr.remote_sglist;
700 				memset(sgl, 0,
701 				       sizeof(io->io_hdr.remote_sglist));
702 
703 				io->scsiio.kern_data_ptr = (uint8_t *)sgl;
704 
705 				io->scsiio.kern_sg_entries =
706 					msg_info.dt.kern_sg_entries;
707 				io->scsiio.rem_sg_entries =
708 					msg_info.dt.kern_sg_entries;
709 				io->scsiio.kern_data_len =
710 					msg_info.dt.kern_data_len;
711 				io->scsiio.kern_total_len =
712 					msg_info.dt.kern_total_len;
713 				io->scsiio.kern_data_resid =
714 					msg_info.dt.kern_data_resid;
715 				io->scsiio.kern_rel_offset =
716 					msg_info.dt.kern_rel_offset;
717 				/*
718 				 * Clear out per-DMA flags.
719 				 */
720 				io->io_hdr.flags &= ~CTL_FLAG_RDMA_MASK;
721 				/*
722 				 * Add per-DMA flags that are set for this
723 				 * particular DMA request.
724 				 */
725 				io->io_hdr.flags |= msg_info.dt.flags &
726 						    CTL_FLAG_RDMA_MASK;
727 			} else
728 				sgl = (struct ctl_sg_entry *)
729 					io->scsiio.kern_data_ptr;
730 
731 			for (i = msg_info.dt.sent_sg_entries, j = 0;
732 			     i < (msg_info.dt.sent_sg_entries +
733 			     msg_info.dt.cur_sg_entries); i++, j++) {
734 				sgl[i].addr = msg_info.dt.sg_list[j].addr;
735 				sgl[i].len = msg_info.dt.sg_list[j].len;
736 
737 #if 0
738 				printf("%s: L: %p,%d -> %p,%d j=%d, i=%d\n",
739 				       __func__,
740 				       msg_info.dt.sg_list[j].addr,
741 				       msg_info.dt.sg_list[j].len,
742 				       sgl[i].addr, sgl[i].len, j, i);
743 #endif
744 			}
745 #if 0
746 			memcpy(&sgl[msg_info.dt.sent_sg_entries],
747 			       msg_info.dt.sg_list,
748 			       sizeof(*sgl) * msg_info.dt.cur_sg_entries);
749 #endif
750 
751 			/*
752 			 * If this is the last piece of the I/O, we've got
753 			 * the full S/G list.  Queue processing in the thread.
754 			 * Otherwise wait for the next piece.
755 			 */
756 			if (msg_info.dt.sg_last != 0)
757 				ctl_enqueue_isc(io);
758 			break;
759 		}
760 		/* Performed on the Serializing (primary) SC, XFER mode only */
761 		case CTL_MSG_DATAMOVE_DONE: {
762 			if (msg_info.hdr.serializing_sc == NULL) {
763 				printf("%s: serializing_sc == NULL!\n",
764 				       __func__);
765 				/* XXX KDM now what? */
766 				break;
767 			}
768 			/*
769 			 * We grab the sense information here in case
770 			 * there was a failure, so we can return status
771 			 * back to the initiator.
772 			 */
773 			io = msg_info.hdr.serializing_sc;
774 			io->io_hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
775 			io->io_hdr.status = msg_info.hdr.status;
776 			io->scsiio.scsi_status = msg_info.scsi.scsi_status;
777 			io->scsiio.sense_len = msg_info.scsi.sense_len;
778 			io->scsiio.sense_residual =msg_info.scsi.sense_residual;
779 			io->io_hdr.port_status = msg_info.scsi.fetd_status;
780 			io->scsiio.residual = msg_info.scsi.residual;
781 			memcpy(&io->scsiio.sense_data,&msg_info.scsi.sense_data,
782 			       sizeof(io->scsiio.sense_data));
783 			ctl_enqueue_isc(io);
784 			break;
785 		}
786 
787 		/* Preformed on Originating SC, SER_ONLY mode */
788 		case CTL_MSG_R2R:
789 			io = msg_info.hdr.original_sc;
790 			if (io == NULL) {
791 				printf("%s: Major Bummer\n", __func__);
792 				return;
793 			} else {
794 #if 0
795 				printf("pOrig %x\n",(int) ctsio);
796 #endif
797 			}
798 			io->io_hdr.msg_type = CTL_MSG_R2R;
799 			io->io_hdr.serializing_sc = msg_info.hdr.serializing_sc;
800 			ctl_enqueue_isc(io);
801 			break;
802 
803 		/*
804 		 * Performed on Serializing(i.e. primary SC) SC in SER_ONLY
805 		 * mode.
806 		 * Performed on the Originating (i.e. secondary) SC in XFER
807 		 * mode
808 		 */
809 		case CTL_MSG_FINISH_IO:
810 			if (ctl_softc->ha_mode == CTL_HA_MODE_XFER)
811 				ctl_isc_handler_finish_xfer(ctl_softc,
812 							    &msg_info);
813 			else
814 				ctl_isc_handler_finish_ser_only(ctl_softc,
815 								&msg_info);
816 			break;
817 
818 		/* Preformed on Originating SC */
819 		case CTL_MSG_BAD_JUJU:
820 			io = msg_info.hdr.original_sc;
821 			if (io == NULL) {
822 				printf("%s: Bad JUJU!, original_sc is NULL!\n",
823 				       __func__);
824 				break;
825 			}
826 			ctl_copy_sense_data(&msg_info, io);
827 			/*
828 			 * IO should have already been cleaned up on other
829 			 * SC so clear this flag so we won't send a message
830 			 * back to finish the IO there.
831 			 */
832 			io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
833 			io->io_hdr.flags |= CTL_FLAG_IO_ACTIVE;
834 
835 			/* io = msg_info.hdr.serializing_sc; */
836 			io->io_hdr.msg_type = CTL_MSG_BAD_JUJU;
837 			ctl_enqueue_isc(io);
838 			break;
839 
840 		/* Handle resets sent from the other side */
841 		case CTL_MSG_MANAGE_TASKS: {
842 			struct ctl_taskio *taskio;
843 			taskio = (struct ctl_taskio *)ctl_alloc_io(
844 				(void *)ctl_softc->othersc_pool);
845 			if (taskio == NULL) {
846 				printf("ctl_isc_event_handler: can't allocate "
847 				       "ctl_io!\n");
848 				/* Bad Juju */
849 				/* should I just call the proper reset func
850 				   here??? */
851 				goto bailout;
852 			}
853 			ctl_zero_io((union ctl_io *)taskio);
854 			taskio->io_hdr.io_type = CTL_IO_TASK;
855 			taskio->io_hdr.flags |= CTL_FLAG_FROM_OTHER_SC;
856 			taskio->io_hdr.nexus = msg_info.hdr.nexus;
857 			taskio->task_action = msg_info.task.task_action;
858 			taskio->tag_num = msg_info.task.tag_num;
859 			taskio->tag_type = msg_info.task.tag_type;
860 #ifdef CTL_TIME_IO
861 			taskio->io_hdr.start_time = time_uptime;
862 			getbintime(&taskio->io_hdr.start_bt);
863 #if 0
864 			cs_prof_gettime(&taskio->io_hdr.start_ticks);
865 #endif
866 #endif /* CTL_TIME_IO */
867 			ctl_run_task((union ctl_io *)taskio);
868 			break;
869 		}
870 		/* Persistent Reserve action which needs attention */
871 		case CTL_MSG_PERS_ACTION:
872 			presio = (struct ctl_prio *)ctl_alloc_io(
873 				(void *)ctl_softc->othersc_pool);
874 			if (presio == NULL) {
875 				printf("ctl_isc_event_handler: can't allocate "
876 				       "ctl_io!\n");
877 				/* Bad Juju */
878 				/* Need to set busy and send msg back */
879 				goto bailout;
880 			}
881 			ctl_zero_io((union ctl_io *)presio);
882 			presio->io_hdr.msg_type = CTL_MSG_PERS_ACTION;
883 			presio->pr_msg = msg_info.pr;
884 			ctl_enqueue_isc((union ctl_io *)presio);
885 			break;
886 		case CTL_MSG_SYNC_FE:
887 			rcv_sync_msg = 1;
888 			break;
889 		case CTL_MSG_APS_LOCK: {
890 			// It's quicker to execute this then to
891 			// queue it.
892 			struct ctl_lun *lun;
893 			struct ctl_page_index *page_index;
894 			struct copan_aps_subpage *current_sp;
895 			uint32_t targ_lun;
896 
897 			targ_lun = msg_info.hdr.nexus.targ_mapped_lun;
898 			lun = ctl_softc->ctl_luns[targ_lun];
899 			mtx_lock(&lun->lun_lock);
900 			page_index = &lun->mode_pages.index[index_to_aps_page];
901 			current_sp = (struct copan_aps_subpage *)
902 				     (page_index->page_data +
903 				     (page_index->page_len * CTL_PAGE_CURRENT));
904 
905 			current_sp->lock_active = msg_info.aps.lock_flag;
906 			mtx_unlock(&lun->lun_lock);
907 		        break;
908 		}
909 		default:
910 		        printf("How did I get here?\n");
911 		}
912 	} else if (event == CTL_HA_EVT_MSG_SENT) {
913 		if (param != CTL_HA_STATUS_SUCCESS) {
914 			printf("Bad status from ctl_ha_msg_send status %d\n",
915 			       param);
916 		}
917 		return;
918 	} else if (event == CTL_HA_EVT_DISCONNECT) {
919 		printf("CTL: Got a disconnect from Isc\n");
920 		return;
921 	} else {
922 		printf("ctl_isc_event_handler: Unknown event %d\n", event);
923 		return;
924 	}
925 
926 bailout:
927 	return;
928 }
929 
930 static void
931 ctl_copy_sense_data(union ctl_ha_msg *src, union ctl_io *dest)
932 {
933 	struct scsi_sense_data *sense;
934 
935 	sense = &dest->scsiio.sense_data;
936 	bcopy(&src->scsi.sense_data, sense, sizeof(*sense));
937 	dest->scsiio.scsi_status = src->scsi.scsi_status;
938 	dest->scsiio.sense_len = src->scsi.sense_len;
939 	dest->io_hdr.status = src->hdr.status;
940 }
941 
942 static int
943 ctl_init(void)
944 {
945 	struct ctl_softc *softc;
946 	struct ctl_io_pool *internal_pool, *emergency_pool, *other_pool;
947 	struct ctl_port *port;
948         uint8_t sc_id =0;
949 	int i, error, retval;
950 	//int isc_retval;
951 
952 	retval = 0;
953 	ctl_pause_rtr = 0;
954         rcv_sync_msg = 0;
955 
956 	control_softc = malloc(sizeof(*control_softc), M_DEVBUF,
957 			       M_WAITOK | M_ZERO);
958 	softc = control_softc;
959 
960 	softc->dev = make_dev(&ctl_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600,
961 			      "cam/ctl");
962 
963 	softc->dev->si_drv1 = softc;
964 
965 	/*
966 	 * By default, return a "bad LUN" peripheral qualifier for unknown
967 	 * LUNs.  The user can override this default using the tunable or
968 	 * sysctl.  See the comment in ctl_inquiry_std() for more details.
969 	 */
970 	softc->inquiry_pq_no_lun = 1;
971 	TUNABLE_INT_FETCH("kern.cam.ctl.inquiry_pq_no_lun",
972 			  &softc->inquiry_pq_no_lun);
973 	sysctl_ctx_init(&softc->sysctl_ctx);
974 	softc->sysctl_tree = SYSCTL_ADD_NODE(&softc->sysctl_ctx,
975 		SYSCTL_STATIC_CHILDREN(_kern_cam), OID_AUTO, "ctl",
976 		CTLFLAG_RD, 0, "CAM Target Layer");
977 
978 	if (softc->sysctl_tree == NULL) {
979 		printf("%s: unable to allocate sysctl tree\n", __func__);
980 		destroy_dev(softc->dev);
981 		free(control_softc, M_DEVBUF);
982 		control_softc = NULL;
983 		return (ENOMEM);
984 	}
985 
986 	SYSCTL_ADD_INT(&softc->sysctl_ctx,
987 		       SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
988 		       "inquiry_pq_no_lun", CTLFLAG_RW,
989 		       &softc->inquiry_pq_no_lun, 0,
990 		       "Report no lun possible for invalid LUNs");
991 
992 	mtx_init(&softc->ctl_lock, "CTL mutex", NULL, MTX_DEF);
993 	mtx_init(&softc->pool_lock, "CTL pool mutex", NULL, MTX_DEF);
994 	softc->open_count = 0;
995 
996 	/*
997 	 * Default to actually sending a SYNCHRONIZE CACHE command down to
998 	 * the drive.
999 	 */
1000 	softc->flags = CTL_FLAG_REAL_SYNC;
1001 
1002 	/*
1003 	 * In Copan's HA scheme, the "master" and "slave" roles are
1004 	 * figured out through the slot the controller is in.  Although it
1005 	 * is an active/active system, someone has to be in charge.
1006  	 */
1007 #ifdef NEEDTOPORT
1008         scmicro_rw(SCMICRO_GET_SHELF_ID, &sc_id);
1009 #endif
1010 
1011         if (sc_id == 0) {
1012 		softc->flags |= CTL_FLAG_MASTER_SHELF;
1013 		persis_offset = 0;
1014 	} else
1015 		persis_offset = CTL_MAX_INITIATORS;
1016 
1017 	/*
1018 	 * XXX KDM need to figure out where we want to get our target ID
1019 	 * and WWID.  Is it different on each port?
1020 	 */
1021 	softc->target.id = 0;
1022 	softc->target.wwid[0] = 0x12345678;
1023 	softc->target.wwid[1] = 0x87654321;
1024 	STAILQ_INIT(&softc->lun_list);
1025 	STAILQ_INIT(&softc->pending_lun_queue);
1026 	STAILQ_INIT(&softc->fe_list);
1027 	STAILQ_INIT(&softc->port_list);
1028 	STAILQ_INIT(&softc->be_list);
1029 	STAILQ_INIT(&softc->io_pools);
1030 	ctl_tpc_init(softc);
1031 
1032 	if (ctl_pool_create(softc, CTL_POOL_INTERNAL, CTL_POOL_ENTRIES_INTERNAL,
1033 			    &internal_pool)!= 0){
1034 		printf("ctl: can't allocate %d entry internal pool, "
1035 		       "exiting\n", CTL_POOL_ENTRIES_INTERNAL);
1036 		return (ENOMEM);
1037 	}
1038 
1039 	if (ctl_pool_create(softc, CTL_POOL_EMERGENCY,
1040 			    CTL_POOL_ENTRIES_EMERGENCY, &emergency_pool) != 0) {
1041 		printf("ctl: can't allocate %d entry emergency pool, "
1042 		       "exiting\n", CTL_POOL_ENTRIES_EMERGENCY);
1043 		ctl_pool_free(internal_pool);
1044 		return (ENOMEM);
1045 	}
1046 
1047 	if (ctl_pool_create(softc, CTL_POOL_4OTHERSC, CTL_POOL_ENTRIES_OTHER_SC,
1048 	                    &other_pool) != 0)
1049 	{
1050 		printf("ctl: can't allocate %d entry other SC pool, "
1051 		       "exiting\n", CTL_POOL_ENTRIES_OTHER_SC);
1052 		ctl_pool_free(internal_pool);
1053 		ctl_pool_free(emergency_pool);
1054 		return (ENOMEM);
1055 	}
1056 
1057 	softc->internal_pool = internal_pool;
1058 	softc->emergency_pool = emergency_pool;
1059 	softc->othersc_pool = other_pool;
1060 
1061 	if (worker_threads <= 0)
1062 		worker_threads = max(1, mp_ncpus / 4);
1063 	if (worker_threads > CTL_MAX_THREADS)
1064 		worker_threads = CTL_MAX_THREADS;
1065 
1066 	for (i = 0; i < worker_threads; i++) {
1067 		struct ctl_thread *thr = &softc->threads[i];
1068 
1069 		mtx_init(&thr->queue_lock, "CTL queue mutex", NULL, MTX_DEF);
1070 		thr->ctl_softc = softc;
1071 		STAILQ_INIT(&thr->incoming_queue);
1072 		STAILQ_INIT(&thr->rtr_queue);
1073 		STAILQ_INIT(&thr->done_queue);
1074 		STAILQ_INIT(&thr->isc_queue);
1075 
1076 		error = kproc_kthread_add(ctl_work_thread, thr,
1077 		    &softc->ctl_proc, &thr->thread, 0, 0, "ctl", "work%d", i);
1078 		if (error != 0) {
1079 			printf("error creating CTL work thread!\n");
1080 			ctl_pool_free(internal_pool);
1081 			ctl_pool_free(emergency_pool);
1082 			ctl_pool_free(other_pool);
1083 			return (error);
1084 		}
1085 	}
1086 	error = kproc_kthread_add(ctl_lun_thread, softc,
1087 	    &softc->ctl_proc, NULL, 0, 0, "ctl", "lun");
1088 	if (error != 0) {
1089 		printf("error creating CTL lun thread!\n");
1090 		ctl_pool_free(internal_pool);
1091 		ctl_pool_free(emergency_pool);
1092 		ctl_pool_free(other_pool);
1093 		return (error);
1094 	}
1095 	if (bootverbose)
1096 		printf("ctl: CAM Target Layer loaded\n");
1097 
1098 	/*
1099 	 * Initialize the ioctl front end.
1100 	 */
1101 	ctl_frontend_register(&ioctl_frontend);
1102 	port = &softc->ioctl_info.port;
1103 	port->frontend = &ioctl_frontend;
1104 	sprintf(softc->ioctl_info.port_name, "ioctl");
1105 	port->port_type = CTL_PORT_IOCTL;
1106 	port->num_requested_ctl_io = 100;
1107 	port->port_name = softc->ioctl_info.port_name;
1108 	port->port_online = ctl_ioctl_online;
1109 	port->port_offline = ctl_ioctl_offline;
1110 	port->onoff_arg = &softc->ioctl_info;
1111 	port->lun_enable = ctl_ioctl_lun_enable;
1112 	port->lun_disable = ctl_ioctl_lun_disable;
1113 	port->targ_lun_arg = &softc->ioctl_info;
1114 	port->fe_datamove = ctl_ioctl_datamove;
1115 	port->fe_done = ctl_ioctl_done;
1116 	port->max_targets = 15;
1117 	port->max_target_id = 15;
1118 
1119 	if (ctl_port_register(&softc->ioctl_info.port,
1120 	                  (softc->flags & CTL_FLAG_MASTER_SHELF)) != 0) {
1121 		printf("ctl: ioctl front end registration failed, will "
1122 		       "continue anyway\n");
1123 	}
1124 
1125 #ifdef CTL_IO_DELAY
1126 	if (sizeof(struct callout) > CTL_TIMER_BYTES) {
1127 		printf("sizeof(struct callout) %zd > CTL_TIMER_BYTES %zd\n",
1128 		       sizeof(struct callout), CTL_TIMER_BYTES);
1129 		return (EINVAL);
1130 	}
1131 #endif /* CTL_IO_DELAY */
1132 
1133 	return (0);
1134 }
1135 
1136 void
1137 ctl_shutdown(void)
1138 {
1139 	struct ctl_softc *softc;
1140 	struct ctl_lun *lun, *next_lun;
1141 	struct ctl_io_pool *pool;
1142 
1143 	softc = (struct ctl_softc *)control_softc;
1144 
1145 	if (ctl_port_deregister(&softc->ioctl_info.port) != 0)
1146 		printf("ctl: ioctl front end deregistration failed\n");
1147 
1148 	mtx_lock(&softc->ctl_lock);
1149 
1150 	/*
1151 	 * Free up each LUN.
1152 	 */
1153 	for (lun = STAILQ_FIRST(&softc->lun_list); lun != NULL; lun = next_lun){
1154 		next_lun = STAILQ_NEXT(lun, links);
1155 		ctl_free_lun(lun);
1156 	}
1157 
1158 	mtx_unlock(&softc->ctl_lock);
1159 
1160 	ctl_frontend_deregister(&ioctl_frontend);
1161 
1162 	/*
1163 	 * This will rip the rug out from under any FETDs or anyone else
1164 	 * that has a pool allocated.  Since we increment our module
1165 	 * refcount any time someone outside the main CTL module allocates
1166 	 * a pool, we shouldn't have any problems here.  The user won't be
1167 	 * able to unload the CTL module until client modules have
1168 	 * successfully unloaded.
1169 	 */
1170 	while ((pool = STAILQ_FIRST(&softc->io_pools)) != NULL)
1171 		ctl_pool_free(pool);
1172 
1173 #if 0
1174 	ctl_shutdown_thread(softc->work_thread);
1175 	mtx_destroy(&softc->queue_lock);
1176 #endif
1177 
1178 	ctl_tpc_shutdown(softc);
1179 	mtx_destroy(&softc->pool_lock);
1180 	mtx_destroy(&softc->ctl_lock);
1181 
1182 	destroy_dev(softc->dev);
1183 
1184 	sysctl_ctx_free(&softc->sysctl_ctx);
1185 
1186 	free(control_softc, M_DEVBUF);
1187 	control_softc = NULL;
1188 
1189 	if (bootverbose)
1190 		printf("ctl: CAM Target Layer unloaded\n");
1191 }
1192 
1193 static int
1194 ctl_module_event_handler(module_t mod, int what, void *arg)
1195 {
1196 
1197 	switch (what) {
1198 	case MOD_LOAD:
1199 		return (ctl_init());
1200 	case MOD_UNLOAD:
1201 		return (EBUSY);
1202 	default:
1203 		return (EOPNOTSUPP);
1204 	}
1205 }
1206 
1207 /*
1208  * XXX KDM should we do some access checks here?  Bump a reference count to
1209  * prevent a CTL module from being unloaded while someone has it open?
1210  */
1211 static int
1212 ctl_open(struct cdev *dev, int flags, int fmt, struct thread *td)
1213 {
1214 	return (0);
1215 }
1216 
1217 static int
1218 ctl_close(struct cdev *dev, int flags, int fmt, struct thread *td)
1219 {
1220 	return (0);
1221 }
1222 
1223 int
1224 ctl_port_enable(ctl_port_type port_type)
1225 {
1226 	struct ctl_softc *softc;
1227 	struct ctl_port *port;
1228 
1229 	if (ctl_is_single == 0) {
1230 		union ctl_ha_msg msg_info;
1231 		int isc_retval;
1232 
1233 #if 0
1234 		printf("%s: HA mode, synchronizing frontend enable\n",
1235 		        __func__);
1236 #endif
1237 		msg_info.hdr.msg_type = CTL_MSG_SYNC_FE;
1238 	        if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1239 		        sizeof(msg_info), 1 )) > CTL_HA_STATUS_SUCCESS) {
1240 			printf("Sync msg send error retval %d\n", isc_retval);
1241 		}
1242 		if (!rcv_sync_msg) {
1243 			isc_retval=ctl_ha_msg_recv(CTL_HA_CHAN_CTL, &msg_info,
1244 			        sizeof(msg_info), 1);
1245 		}
1246 #if 0
1247         	printf("CTL:Frontend Enable\n");
1248 	} else {
1249 		printf("%s: single mode, skipping frontend synchronization\n",
1250 		        __func__);
1251 #endif
1252 	}
1253 
1254 	softc = control_softc;
1255 
1256 	STAILQ_FOREACH(port, &softc->port_list, links) {
1257 		if (port_type & port->port_type)
1258 		{
1259 #if 0
1260 			printf("port %d\n", port->targ_port);
1261 #endif
1262 			ctl_port_online(port);
1263 		}
1264 	}
1265 
1266 	return (0);
1267 }
1268 
1269 int
1270 ctl_port_disable(ctl_port_type port_type)
1271 {
1272 	struct ctl_softc *softc;
1273 	struct ctl_port *port;
1274 
1275 	softc = control_softc;
1276 
1277 	STAILQ_FOREACH(port, &softc->port_list, links) {
1278 		if (port_type & port->port_type)
1279 			ctl_port_offline(port);
1280 	}
1281 
1282 	return (0);
1283 }
1284 
1285 /*
1286  * Returns 0 for success, 1 for failure.
1287  * Currently the only failure mode is if there aren't enough entries
1288  * allocated.  So, in case of a failure, look at num_entries_dropped,
1289  * reallocate and try again.
1290  */
1291 int
1292 ctl_port_list(struct ctl_port_entry *entries, int num_entries_alloced,
1293 	      int *num_entries_filled, int *num_entries_dropped,
1294 	      ctl_port_type port_type, int no_virtual)
1295 {
1296 	struct ctl_softc *softc;
1297 	struct ctl_port *port;
1298 	int entries_dropped, entries_filled;
1299 	int retval;
1300 	int i;
1301 
1302 	softc = control_softc;
1303 
1304 	retval = 0;
1305 	entries_filled = 0;
1306 	entries_dropped = 0;
1307 
1308 	i = 0;
1309 	mtx_lock(&softc->ctl_lock);
1310 	STAILQ_FOREACH(port, &softc->port_list, links) {
1311 		struct ctl_port_entry *entry;
1312 
1313 		if ((port->port_type & port_type) == 0)
1314 			continue;
1315 
1316 		if ((no_virtual != 0)
1317 		 && (port->virtual_port != 0))
1318 			continue;
1319 
1320 		if (entries_filled >= num_entries_alloced) {
1321 			entries_dropped++;
1322 			continue;
1323 		}
1324 		entry = &entries[i];
1325 
1326 		entry->port_type = port->port_type;
1327 		strlcpy(entry->port_name, port->port_name,
1328 			sizeof(entry->port_name));
1329 		entry->physical_port = port->physical_port;
1330 		entry->virtual_port = port->virtual_port;
1331 		entry->wwnn = port->wwnn;
1332 		entry->wwpn = port->wwpn;
1333 
1334 		i++;
1335 		entries_filled++;
1336 	}
1337 
1338 	mtx_unlock(&softc->ctl_lock);
1339 
1340 	if (entries_dropped > 0)
1341 		retval = 1;
1342 
1343 	*num_entries_dropped = entries_dropped;
1344 	*num_entries_filled = entries_filled;
1345 
1346 	return (retval);
1347 }
1348 
1349 static void
1350 ctl_ioctl_online(void *arg)
1351 {
1352 	struct ctl_ioctl_info *ioctl_info;
1353 
1354 	ioctl_info = (struct ctl_ioctl_info *)arg;
1355 
1356 	ioctl_info->flags |= CTL_IOCTL_FLAG_ENABLED;
1357 }
1358 
1359 static void
1360 ctl_ioctl_offline(void *arg)
1361 {
1362 	struct ctl_ioctl_info *ioctl_info;
1363 
1364 	ioctl_info = (struct ctl_ioctl_info *)arg;
1365 
1366 	ioctl_info->flags &= ~CTL_IOCTL_FLAG_ENABLED;
1367 }
1368 
1369 /*
1370  * Remove an initiator by port number and initiator ID.
1371  * Returns 0 for success, -1 for failure.
1372  */
1373 int
1374 ctl_remove_initiator(struct ctl_port *port, int iid)
1375 {
1376 	struct ctl_softc *softc = control_softc;
1377 
1378 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1379 
1380 	if (iid > CTL_MAX_INIT_PER_PORT) {
1381 		printf("%s: initiator ID %u > maximun %u!\n",
1382 		       __func__, iid, CTL_MAX_INIT_PER_PORT);
1383 		return (-1);
1384 	}
1385 
1386 	mtx_lock(&softc->ctl_lock);
1387 	port->wwpn_iid[iid].in_use--;
1388 	port->wwpn_iid[iid].last_use = time_uptime;
1389 	mtx_unlock(&softc->ctl_lock);
1390 
1391 	return (0);
1392 }
1393 
1394 /*
1395  * Add an initiator to the initiator map.
1396  * Returns iid for success, < 0 for failure.
1397  */
1398 int
1399 ctl_add_initiator(struct ctl_port *port, int iid, uint64_t wwpn, char *name)
1400 {
1401 	struct ctl_softc *softc = control_softc;
1402 	time_t best_time;
1403 	int i, best;
1404 
1405 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
1406 
1407 	if (iid >= CTL_MAX_INIT_PER_PORT) {
1408 		printf("%s: WWPN %#jx initiator ID %u > maximum %u!\n",
1409 		       __func__, wwpn, iid, CTL_MAX_INIT_PER_PORT);
1410 		free(name, M_CTL);
1411 		return (-1);
1412 	}
1413 
1414 	mtx_lock(&softc->ctl_lock);
1415 
1416 	if (iid < 0 && (wwpn != 0 || name != NULL)) {
1417 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1418 			if (wwpn != 0 && wwpn == port->wwpn_iid[i].wwpn) {
1419 				iid = i;
1420 				break;
1421 			}
1422 			if (name != NULL && port->wwpn_iid[i].name != NULL &&
1423 			    strcmp(name, port->wwpn_iid[i].name) == 0) {
1424 				iid = i;
1425 				break;
1426 			}
1427 		}
1428 	}
1429 
1430 	if (iid < 0) {
1431 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1432 			if (port->wwpn_iid[i].in_use == 0 &&
1433 			    port->wwpn_iid[i].wwpn == 0 &&
1434 			    port->wwpn_iid[i].name == NULL) {
1435 				iid = i;
1436 				break;
1437 			}
1438 		}
1439 	}
1440 
1441 	if (iid < 0) {
1442 		best = -1;
1443 		best_time = INT32_MAX;
1444 		for (i = 0; i < CTL_MAX_INIT_PER_PORT; i++) {
1445 			if (port->wwpn_iid[i].in_use == 0) {
1446 				if (port->wwpn_iid[i].last_use < best_time) {
1447 					best = i;
1448 					best_time = port->wwpn_iid[i].last_use;
1449 				}
1450 			}
1451 		}
1452 		iid = best;
1453 	}
1454 
1455 	if (iid < 0) {
1456 		mtx_unlock(&softc->ctl_lock);
1457 		free(name, M_CTL);
1458 		return (-2);
1459 	}
1460 
1461 	if (port->wwpn_iid[iid].in_use > 0 && (wwpn != 0 || name != NULL)) {
1462 		/*
1463 		 * This is not an error yet.
1464 		 */
1465 		if (wwpn != 0 && wwpn == port->wwpn_iid[iid].wwpn) {
1466 #if 0
1467 			printf("%s: port %d iid %u WWPN %#jx arrived"
1468 			    " again\n", __func__, port->targ_port,
1469 			    iid, (uintmax_t)wwpn);
1470 #endif
1471 			goto take;
1472 		}
1473 		if (name != NULL && port->wwpn_iid[iid].name != NULL &&
1474 		    strcmp(name, port->wwpn_iid[iid].name) == 0) {
1475 #if 0
1476 			printf("%s: port %d iid %u name '%s' arrived"
1477 			    " again\n", __func__, port->targ_port,
1478 			    iid, name);
1479 #endif
1480 			goto take;
1481 		}
1482 
1483 		/*
1484 		 * This is an error, but what do we do about it?  The
1485 		 * driver is telling us we have a new WWPN for this
1486 		 * initiator ID, so we pretty much need to use it.
1487 		 */
1488 		printf("%s: port %d iid %u WWPN %#jx '%s' arrived,"
1489 		    " but WWPN %#jx '%s' is still at that address\n",
1490 		    __func__, port->targ_port, iid, wwpn, name,
1491 		    (uintmax_t)port->wwpn_iid[iid].wwpn,
1492 		    port->wwpn_iid[iid].name);
1493 
1494 		/*
1495 		 * XXX KDM clear have_ca and ua_pending on each LUN for
1496 		 * this initiator.
1497 		 */
1498 	}
1499 take:
1500 	free(port->wwpn_iid[iid].name, M_CTL);
1501 	port->wwpn_iid[iid].name = name;
1502 	port->wwpn_iid[iid].wwpn = wwpn;
1503 	port->wwpn_iid[iid].in_use++;
1504 	mtx_unlock(&softc->ctl_lock);
1505 
1506 	return (iid);
1507 }
1508 
1509 static int
1510 ctl_create_iid(struct ctl_port *port, int iid, uint8_t *buf)
1511 {
1512 	int len;
1513 
1514 	switch (port->port_type) {
1515 	case CTL_PORT_FC:
1516 	{
1517 		struct scsi_transportid_fcp *id =
1518 		    (struct scsi_transportid_fcp *)buf;
1519 		if (port->wwpn_iid[iid].wwpn == 0)
1520 			return (0);
1521 		memset(id, 0, sizeof(*id));
1522 		id->format_protocol = SCSI_PROTO_FC;
1523 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->n_port_name);
1524 		return (sizeof(*id));
1525 	}
1526 	case CTL_PORT_ISCSI:
1527 	{
1528 		struct scsi_transportid_iscsi_port *id =
1529 		    (struct scsi_transportid_iscsi_port *)buf;
1530 		if (port->wwpn_iid[iid].name == NULL)
1531 			return (0);
1532 		memset(id, 0, 256);
1533 		id->format_protocol = SCSI_TRN_ISCSI_FORMAT_PORT |
1534 		    SCSI_PROTO_ISCSI;
1535 		len = strlcpy(id->iscsi_name, port->wwpn_iid[iid].name, 252) + 1;
1536 		len = roundup2(min(len, 252), 4);
1537 		scsi_ulto2b(len, id->additional_length);
1538 		return (sizeof(*id) + len);
1539 	}
1540 	case CTL_PORT_SAS:
1541 	{
1542 		struct scsi_transportid_sas *id =
1543 		    (struct scsi_transportid_sas *)buf;
1544 		if (port->wwpn_iid[iid].wwpn == 0)
1545 			return (0);
1546 		memset(id, 0, sizeof(*id));
1547 		id->format_protocol = SCSI_PROTO_SAS;
1548 		scsi_u64to8b(port->wwpn_iid[iid].wwpn, id->sas_address);
1549 		return (sizeof(*id));
1550 	}
1551 	default:
1552 	{
1553 		struct scsi_transportid_spi *id =
1554 		    (struct scsi_transportid_spi *)buf;
1555 		memset(id, 0, sizeof(*id));
1556 		id->format_protocol = SCSI_PROTO_SPI;
1557 		scsi_ulto2b(iid, id->scsi_addr);
1558 		scsi_ulto2b(port->targ_port, id->rel_trgt_port_id);
1559 		return (sizeof(*id));
1560 	}
1561 	}
1562 }
1563 
1564 static int
1565 ctl_ioctl_lun_enable(void *arg, struct ctl_id targ_id, int lun_id)
1566 {
1567 	return (0);
1568 }
1569 
1570 static int
1571 ctl_ioctl_lun_disable(void *arg, struct ctl_id targ_id, int lun_id)
1572 {
1573 	return (0);
1574 }
1575 
1576 /*
1577  * Data movement routine for the CTL ioctl frontend port.
1578  */
1579 static int
1580 ctl_ioctl_do_datamove(struct ctl_scsiio *ctsio)
1581 {
1582 	struct ctl_sg_entry *ext_sglist, *kern_sglist;
1583 	struct ctl_sg_entry ext_entry, kern_entry;
1584 	int ext_sglen, ext_sg_entries, kern_sg_entries;
1585 	int ext_sg_start, ext_offset;
1586 	int len_to_copy, len_copied;
1587 	int kern_watermark, ext_watermark;
1588 	int ext_sglist_malloced;
1589 	int i, j;
1590 
1591 	ext_sglist_malloced = 0;
1592 	ext_sg_start = 0;
1593 	ext_offset = 0;
1594 
1595 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove\n"));
1596 
1597 	/*
1598 	 * If this flag is set, fake the data transfer.
1599 	 */
1600 	if (ctsio->io_hdr.flags & CTL_FLAG_NO_DATAMOVE) {
1601 		ctsio->ext_data_filled = ctsio->ext_data_len;
1602 		goto bailout;
1603 	}
1604 
1605 	/*
1606 	 * To simplify things here, if we have a single buffer, stick it in
1607 	 * a S/G entry and just make it a single entry S/G list.
1608 	 */
1609 	if (ctsio->io_hdr.flags & CTL_FLAG_EDPTR_SGLIST) {
1610 		int len_seen;
1611 
1612 		ext_sglen = ctsio->ext_sg_entries * sizeof(*ext_sglist);
1613 
1614 		ext_sglist = (struct ctl_sg_entry *)malloc(ext_sglen, M_CTL,
1615 							   M_WAITOK);
1616 		ext_sglist_malloced = 1;
1617 		if (copyin(ctsio->ext_data_ptr, ext_sglist,
1618 				   ext_sglen) != 0) {
1619 			ctl_set_internal_failure(ctsio,
1620 						 /*sks_valid*/ 0,
1621 						 /*retry_count*/ 0);
1622 			goto bailout;
1623 		}
1624 		ext_sg_entries = ctsio->ext_sg_entries;
1625 		len_seen = 0;
1626 		for (i = 0; i < ext_sg_entries; i++) {
1627 			if ((len_seen + ext_sglist[i].len) >=
1628 			     ctsio->ext_data_filled) {
1629 				ext_sg_start = i;
1630 				ext_offset = ctsio->ext_data_filled - len_seen;
1631 				break;
1632 			}
1633 			len_seen += ext_sglist[i].len;
1634 		}
1635 	} else {
1636 		ext_sglist = &ext_entry;
1637 		ext_sglist->addr = ctsio->ext_data_ptr;
1638 		ext_sglist->len = ctsio->ext_data_len;
1639 		ext_sg_entries = 1;
1640 		ext_sg_start = 0;
1641 		ext_offset = ctsio->ext_data_filled;
1642 	}
1643 
1644 	if (ctsio->kern_sg_entries > 0) {
1645 		kern_sglist = (struct ctl_sg_entry *)ctsio->kern_data_ptr;
1646 		kern_sg_entries = ctsio->kern_sg_entries;
1647 	} else {
1648 		kern_sglist = &kern_entry;
1649 		kern_sglist->addr = ctsio->kern_data_ptr;
1650 		kern_sglist->len = ctsio->kern_data_len;
1651 		kern_sg_entries = 1;
1652 	}
1653 
1654 
1655 	kern_watermark = 0;
1656 	ext_watermark = ext_offset;
1657 	len_copied = 0;
1658 	for (i = ext_sg_start, j = 0;
1659 	     i < ext_sg_entries && j < kern_sg_entries;) {
1660 		uint8_t *ext_ptr, *kern_ptr;
1661 
1662 		len_to_copy = ctl_min(ext_sglist[i].len - ext_watermark,
1663 				      kern_sglist[j].len - kern_watermark);
1664 
1665 		ext_ptr = (uint8_t *)ext_sglist[i].addr;
1666 		ext_ptr = ext_ptr + ext_watermark;
1667 		if (ctsio->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
1668 			/*
1669 			 * XXX KDM fix this!
1670 			 */
1671 			panic("need to implement bus address support");
1672 #if 0
1673 			kern_ptr = bus_to_virt(kern_sglist[j].addr);
1674 #endif
1675 		} else
1676 			kern_ptr = (uint8_t *)kern_sglist[j].addr;
1677 		kern_ptr = kern_ptr + kern_watermark;
1678 
1679 		kern_watermark += len_to_copy;
1680 		ext_watermark += len_to_copy;
1681 
1682 		if ((ctsio->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
1683 		     CTL_FLAG_DATA_IN) {
1684 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1685 					 "bytes to user\n", len_to_copy));
1686 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1687 					 "to %p\n", kern_ptr, ext_ptr));
1688 			if (copyout(kern_ptr, ext_ptr, len_to_copy) != 0) {
1689 				ctl_set_internal_failure(ctsio,
1690 							 /*sks_valid*/ 0,
1691 							 /*retry_count*/ 0);
1692 				goto bailout;
1693 			}
1694 		} else {
1695 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: copying %d "
1696 					 "bytes from user\n", len_to_copy));
1697 			CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: from %p "
1698 					 "to %p\n", ext_ptr, kern_ptr));
1699 			if (copyin(ext_ptr, kern_ptr, len_to_copy)!= 0){
1700 				ctl_set_internal_failure(ctsio,
1701 							 /*sks_valid*/ 0,
1702 							 /*retry_count*/0);
1703 				goto bailout;
1704 			}
1705 		}
1706 
1707 		len_copied += len_to_copy;
1708 
1709 		if (ext_sglist[i].len == ext_watermark) {
1710 			i++;
1711 			ext_watermark = 0;
1712 		}
1713 
1714 		if (kern_sglist[j].len == kern_watermark) {
1715 			j++;
1716 			kern_watermark = 0;
1717 		}
1718 	}
1719 
1720 	ctsio->ext_data_filled += len_copied;
1721 
1722 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_sg_entries: %d, "
1723 			 "kern_sg_entries: %d\n", ext_sg_entries,
1724 			 kern_sg_entries));
1725 	CTL_DEBUG_PRINT(("ctl_ioctl_do_datamove: ext_data_len = %d, "
1726 			 "kern_data_len = %d\n", ctsio->ext_data_len,
1727 			 ctsio->kern_data_len));
1728 
1729 
1730 	/* XXX KDM set residual?? */
1731 bailout:
1732 
1733 	if (ext_sglist_malloced != 0)
1734 		free(ext_sglist, M_CTL);
1735 
1736 	return (CTL_RETVAL_COMPLETE);
1737 }
1738 
1739 /*
1740  * Serialize a command that went down the "wrong" side, and so was sent to
1741  * this controller for execution.  The logic is a little different than the
1742  * standard case in ctl_scsiio_precheck().  Errors in this case need to get
1743  * sent back to the other side, but in the success case, we execute the
1744  * command on this side (XFER mode) or tell the other side to execute it
1745  * (SER_ONLY mode).
1746  */
1747 static int
1748 ctl_serialize_other_sc_cmd(struct ctl_scsiio *ctsio)
1749 {
1750 	struct ctl_softc *ctl_softc;
1751 	union ctl_ha_msg msg_info;
1752 	struct ctl_lun *lun;
1753 	int retval = 0;
1754 	uint32_t targ_lun;
1755 
1756 	ctl_softc = control_softc;
1757 
1758 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
1759 	lun = ctl_softc->ctl_luns[targ_lun];
1760 	if (lun==NULL)
1761 	{
1762 		/*
1763 		 * Why isn't LUN defined? The other side wouldn't
1764 		 * send a cmd if the LUN is undefined.
1765 		 */
1766 		printf("%s: Bad JUJU!, LUN is NULL!\n", __func__);
1767 
1768 		/* "Logical unit not supported" */
1769 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1770 				   lun,
1771 				   /*sense_format*/SSD_TYPE_NONE,
1772 				   /*current_error*/ 1,
1773 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1774 				   /*asc*/ 0x25,
1775 				   /*ascq*/ 0x00,
1776 				   SSD_ELEM_NONE);
1777 
1778 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1779 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1780 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1781 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1782 		msg_info.hdr.serializing_sc = NULL;
1783 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1784 	        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1785 				sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1786 		}
1787 		return(1);
1788 
1789 	}
1790 
1791 	mtx_lock(&lun->lun_lock);
1792     	TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1793 
1794 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
1795 		(union ctl_io *)TAILQ_PREV(&ctsio->io_hdr, ctl_ooaq,
1796 		 ooa_links))) {
1797 	case CTL_ACTION_BLOCK:
1798 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
1799 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
1800 				  blocked_links);
1801 		break;
1802 	case CTL_ACTION_PASS:
1803 	case CTL_ACTION_SKIP:
1804 		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
1805 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
1806 			ctl_enqueue_rtr((union ctl_io *)ctsio);
1807 		} else {
1808 
1809 			/* send msg back to other side */
1810 			msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1811 			msg_info.hdr.serializing_sc = (union ctl_io *)ctsio;
1812 			msg_info.hdr.msg_type = CTL_MSG_R2R;
1813 #if 0
1814 			printf("2. pOrig %x\n", (int)msg_info.hdr.original_sc);
1815 #endif
1816 		        if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1817 			    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1818 			}
1819 		}
1820 		break;
1821 	case CTL_ACTION_OVERLAP:
1822 		/* OVERLAPPED COMMANDS ATTEMPTED */
1823 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1824 				   lun,
1825 				   /*sense_format*/SSD_TYPE_NONE,
1826 				   /*current_error*/ 1,
1827 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1828 				   /*asc*/ 0x4E,
1829 				   /*ascq*/ 0x00,
1830 				   SSD_ELEM_NONE);
1831 
1832 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1833 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1834 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1835 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1836 		msg_info.hdr.serializing_sc = NULL;
1837 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1838 #if 0
1839 		printf("BAD JUJU:Major Bummer Overlap\n");
1840 #endif
1841 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1842 		retval = 1;
1843 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1844 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1845 		}
1846 		break;
1847 	case CTL_ACTION_OVERLAP_TAG:
1848 		/* TAGGED OVERLAPPED COMMANDS (NN = QUEUE TAG) */
1849 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1850 				   lun,
1851 				   /*sense_format*/SSD_TYPE_NONE,
1852 				   /*current_error*/ 1,
1853 				   /*sense_key*/ SSD_KEY_ILLEGAL_REQUEST,
1854 				   /*asc*/ 0x4D,
1855 				   /*ascq*/ ctsio->tag_num & 0xff,
1856 				   SSD_ELEM_NONE);
1857 
1858 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1859 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1860 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1861 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1862 		msg_info.hdr.serializing_sc = NULL;
1863 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1864 #if 0
1865 		printf("BAD JUJU:Major Bummer Overlap Tag\n");
1866 #endif
1867 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1868 		retval = 1;
1869 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1870 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1871 		}
1872 		break;
1873 	case CTL_ACTION_ERROR:
1874 	default:
1875 		/* "Internal target failure" */
1876 		ctl_set_sense_data(&msg_info.scsi.sense_data,
1877 				   lun,
1878 				   /*sense_format*/SSD_TYPE_NONE,
1879 				   /*current_error*/ 1,
1880 				   /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
1881 				   /*asc*/ 0x44,
1882 				   /*ascq*/ 0x00,
1883 				   SSD_ELEM_NONE);
1884 
1885 		msg_info.scsi.sense_len = SSD_FULL_SIZE;
1886 		msg_info.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
1887 		msg_info.hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
1888 		msg_info.hdr.original_sc = ctsio->io_hdr.original_sc;
1889 		msg_info.hdr.serializing_sc = NULL;
1890 		msg_info.hdr.msg_type = CTL_MSG_BAD_JUJU;
1891 #if 0
1892 		printf("BAD JUJU:Major Bummer HW Error\n");
1893 #endif
1894 		TAILQ_REMOVE(&lun->ooa_queue, &ctsio->io_hdr, ooa_links);
1895 		retval = 1;
1896 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_info,
1897 		    sizeof(msg_info), 0 ) > CTL_HA_STATUS_SUCCESS) {
1898 		}
1899 		break;
1900 	}
1901 	mtx_unlock(&lun->lun_lock);
1902 	return (retval);
1903 }
1904 
1905 static int
1906 ctl_ioctl_submit_wait(union ctl_io *io)
1907 {
1908 	struct ctl_fe_ioctl_params params;
1909 	ctl_fe_ioctl_state last_state;
1910 	int done, retval;
1911 
1912 	retval = 0;
1913 
1914 	bzero(&params, sizeof(params));
1915 
1916 	mtx_init(&params.ioctl_mtx, "ctliocmtx", NULL, MTX_DEF);
1917 	cv_init(&params.sem, "ctlioccv");
1918 	params.state = CTL_IOCTL_INPROG;
1919 	last_state = params.state;
1920 
1921 	io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr = &params;
1922 
1923 	CTL_DEBUG_PRINT(("ctl_ioctl_submit_wait\n"));
1924 
1925 	/* This shouldn't happen */
1926 	if ((retval = ctl_queue(io)) != CTL_RETVAL_COMPLETE)
1927 		return (retval);
1928 
1929 	done = 0;
1930 
1931 	do {
1932 		mtx_lock(&params.ioctl_mtx);
1933 		/*
1934 		 * Check the state here, and don't sleep if the state has
1935 		 * already changed (i.e. wakeup has already occured, but we
1936 		 * weren't waiting yet).
1937 		 */
1938 		if (params.state == last_state) {
1939 			/* XXX KDM cv_wait_sig instead? */
1940 			cv_wait(&params.sem, &params.ioctl_mtx);
1941 		}
1942 		last_state = params.state;
1943 
1944 		switch (params.state) {
1945 		case CTL_IOCTL_INPROG:
1946 			/* Why did we wake up? */
1947 			/* XXX KDM error here? */
1948 			mtx_unlock(&params.ioctl_mtx);
1949 			break;
1950 		case CTL_IOCTL_DATAMOVE:
1951 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DATAMOVE\n"));
1952 
1953 			/*
1954 			 * change last_state back to INPROG to avoid
1955 			 * deadlock on subsequent data moves.
1956 			 */
1957 			params.state = last_state = CTL_IOCTL_INPROG;
1958 
1959 			mtx_unlock(&params.ioctl_mtx);
1960 			ctl_ioctl_do_datamove(&io->scsiio);
1961 			/*
1962 			 * Note that in some cases, most notably writes,
1963 			 * this will queue the I/O and call us back later.
1964 			 * In other cases, generally reads, this routine
1965 			 * will immediately call back and wake us up,
1966 			 * probably using our own context.
1967 			 */
1968 			io->scsiio.be_move_done(io);
1969 			break;
1970 		case CTL_IOCTL_DONE:
1971 			mtx_unlock(&params.ioctl_mtx);
1972 			CTL_DEBUG_PRINT(("got CTL_IOCTL_DONE\n"));
1973 			done = 1;
1974 			break;
1975 		default:
1976 			mtx_unlock(&params.ioctl_mtx);
1977 			/* XXX KDM error here? */
1978 			break;
1979 		}
1980 	} while (done == 0);
1981 
1982 	mtx_destroy(&params.ioctl_mtx);
1983 	cv_destroy(&params.sem);
1984 
1985 	return (CTL_RETVAL_COMPLETE);
1986 }
1987 
1988 static void
1989 ctl_ioctl_datamove(union ctl_io *io)
1990 {
1991 	struct ctl_fe_ioctl_params *params;
1992 
1993 	params = (struct ctl_fe_ioctl_params *)
1994 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
1995 
1996 	mtx_lock(&params->ioctl_mtx);
1997 	params->state = CTL_IOCTL_DATAMOVE;
1998 	cv_broadcast(&params->sem);
1999 	mtx_unlock(&params->ioctl_mtx);
2000 }
2001 
2002 static void
2003 ctl_ioctl_done(union ctl_io *io)
2004 {
2005 	struct ctl_fe_ioctl_params *params;
2006 
2007 	params = (struct ctl_fe_ioctl_params *)
2008 		io->io_hdr.ctl_private[CTL_PRIV_FRONTEND].ptr;
2009 
2010 	mtx_lock(&params->ioctl_mtx);
2011 	params->state = CTL_IOCTL_DONE;
2012 	cv_broadcast(&params->sem);
2013 	mtx_unlock(&params->ioctl_mtx);
2014 }
2015 
2016 static void
2017 ctl_ioctl_hard_startstop_callback(void *arg, struct cfi_metatask *metatask)
2018 {
2019 	struct ctl_fe_ioctl_startstop_info *sd_info;
2020 
2021 	sd_info = (struct ctl_fe_ioctl_startstop_info *)arg;
2022 
2023 	sd_info->hs_info.status = metatask->status;
2024 	sd_info->hs_info.total_luns = metatask->taskinfo.startstop.total_luns;
2025 	sd_info->hs_info.luns_complete =
2026 		metatask->taskinfo.startstop.luns_complete;
2027 	sd_info->hs_info.luns_failed = metatask->taskinfo.startstop.luns_failed;
2028 
2029 	cv_broadcast(&sd_info->sem);
2030 }
2031 
2032 static void
2033 ctl_ioctl_bbrread_callback(void *arg, struct cfi_metatask *metatask)
2034 {
2035 	struct ctl_fe_ioctl_bbrread_info *fe_bbr_info;
2036 
2037 	fe_bbr_info = (struct ctl_fe_ioctl_bbrread_info *)arg;
2038 
2039 	mtx_lock(fe_bbr_info->lock);
2040 	fe_bbr_info->bbr_info->status = metatask->status;
2041 	fe_bbr_info->bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2042 	fe_bbr_info->wakeup_done = 1;
2043 	mtx_unlock(fe_bbr_info->lock);
2044 
2045 	cv_broadcast(&fe_bbr_info->sem);
2046 }
2047 
2048 /*
2049  * Returns 0 for success, errno for failure.
2050  */
2051 static int
2052 ctl_ioctl_fill_ooa(struct ctl_lun *lun, uint32_t *cur_fill_num,
2053 		   struct ctl_ooa *ooa_hdr, struct ctl_ooa_entry *kern_entries)
2054 {
2055 	union ctl_io *io;
2056 	int retval;
2057 
2058 	retval = 0;
2059 
2060 	mtx_lock(&lun->lun_lock);
2061 	for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); (io != NULL);
2062 	     (*cur_fill_num)++, io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2063 	     ooa_links)) {
2064 		struct ctl_ooa_entry *entry;
2065 
2066 		/*
2067 		 * If we've got more than we can fit, just count the
2068 		 * remaining entries.
2069 		 */
2070 		if (*cur_fill_num >= ooa_hdr->alloc_num)
2071 			continue;
2072 
2073 		entry = &kern_entries[*cur_fill_num];
2074 
2075 		entry->tag_num = io->scsiio.tag_num;
2076 		entry->lun_num = lun->lun;
2077 #ifdef CTL_TIME_IO
2078 		entry->start_bt = io->io_hdr.start_bt;
2079 #endif
2080 		bcopy(io->scsiio.cdb, entry->cdb, io->scsiio.cdb_len);
2081 		entry->cdb_len = io->scsiio.cdb_len;
2082 		if (io->io_hdr.flags & CTL_FLAG_BLOCKED)
2083 			entry->cmd_flags |= CTL_OOACMD_FLAG_BLOCKED;
2084 
2085 		if (io->io_hdr.flags & CTL_FLAG_DMA_INPROG)
2086 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA;
2087 
2088 		if (io->io_hdr.flags & CTL_FLAG_ABORT)
2089 			entry->cmd_flags |= CTL_OOACMD_FLAG_ABORT;
2090 
2091 		if (io->io_hdr.flags & CTL_FLAG_IS_WAS_ON_RTR)
2092 			entry->cmd_flags |= CTL_OOACMD_FLAG_RTR;
2093 
2094 		if (io->io_hdr.flags & CTL_FLAG_DMA_QUEUED)
2095 			entry->cmd_flags |= CTL_OOACMD_FLAG_DMA_QUEUED;
2096 	}
2097 	mtx_unlock(&lun->lun_lock);
2098 
2099 	return (retval);
2100 }
2101 
2102 static void *
2103 ctl_copyin_alloc(void *user_addr, int len, char *error_str,
2104 		 size_t error_str_len)
2105 {
2106 	void *kptr;
2107 
2108 	kptr = malloc(len, M_CTL, M_WAITOK | M_ZERO);
2109 
2110 	if (copyin(user_addr, kptr, len) != 0) {
2111 		snprintf(error_str, error_str_len, "Error copying %d bytes "
2112 			 "from user address %p to kernel address %p", len,
2113 			 user_addr, kptr);
2114 		free(kptr, M_CTL);
2115 		return (NULL);
2116 	}
2117 
2118 	return (kptr);
2119 }
2120 
2121 static void
2122 ctl_free_args(int num_args, struct ctl_be_arg *args)
2123 {
2124 	int i;
2125 
2126 	if (args == NULL)
2127 		return;
2128 
2129 	for (i = 0; i < num_args; i++) {
2130 		free(args[i].kname, M_CTL);
2131 		free(args[i].kvalue, M_CTL);
2132 	}
2133 
2134 	free(args, M_CTL);
2135 }
2136 
2137 static struct ctl_be_arg *
2138 ctl_copyin_args(int num_args, struct ctl_be_arg *uargs,
2139 		char *error_str, size_t error_str_len)
2140 {
2141 	struct ctl_be_arg *args;
2142 	int i;
2143 
2144 	args = ctl_copyin_alloc(uargs, num_args * sizeof(*args),
2145 				error_str, error_str_len);
2146 
2147 	if (args == NULL)
2148 		goto bailout;
2149 
2150 	for (i = 0; i < num_args; i++) {
2151 		args[i].kname = NULL;
2152 		args[i].kvalue = NULL;
2153 	}
2154 
2155 	for (i = 0; i < num_args; i++) {
2156 		uint8_t *tmpptr;
2157 
2158 		args[i].kname = ctl_copyin_alloc(args[i].name,
2159 			args[i].namelen, error_str, error_str_len);
2160 		if (args[i].kname == NULL)
2161 			goto bailout;
2162 
2163 		if (args[i].kname[args[i].namelen - 1] != '\0') {
2164 			snprintf(error_str, error_str_len, "Argument %d "
2165 				 "name is not NUL-terminated", i);
2166 			goto bailout;
2167 		}
2168 
2169 		if (args[i].flags & CTL_BEARG_RD) {
2170 			tmpptr = ctl_copyin_alloc(args[i].value,
2171 				args[i].vallen, error_str, error_str_len);
2172 			if (tmpptr == NULL)
2173 				goto bailout;
2174 			if ((args[i].flags & CTL_BEARG_ASCII)
2175 			 && (tmpptr[args[i].vallen - 1] != '\0')) {
2176 				snprintf(error_str, error_str_len, "Argument "
2177 				    "%d value is not NUL-terminated", i);
2178 				goto bailout;
2179 			}
2180 			args[i].kvalue = tmpptr;
2181 		} else {
2182 			args[i].kvalue = malloc(args[i].vallen,
2183 			    M_CTL, M_WAITOK | M_ZERO);
2184 		}
2185 	}
2186 
2187 	return (args);
2188 bailout:
2189 
2190 	ctl_free_args(num_args, args);
2191 
2192 	return (NULL);
2193 }
2194 
2195 static void
2196 ctl_copyout_args(int num_args, struct ctl_be_arg *args)
2197 {
2198 	int i;
2199 
2200 	for (i = 0; i < num_args; i++) {
2201 		if (args[i].flags & CTL_BEARG_WR)
2202 			copyout(args[i].kvalue, args[i].value, args[i].vallen);
2203 	}
2204 }
2205 
2206 /*
2207  * Escape characters that are illegal or not recommended in XML.
2208  */
2209 int
2210 ctl_sbuf_printf_esc(struct sbuf *sb, char *str)
2211 {
2212 	int retval;
2213 
2214 	retval = 0;
2215 
2216 	for (; *str; str++) {
2217 		switch (*str) {
2218 		case '&':
2219 			retval = sbuf_printf(sb, "&amp;");
2220 			break;
2221 		case '>':
2222 			retval = sbuf_printf(sb, "&gt;");
2223 			break;
2224 		case '<':
2225 			retval = sbuf_printf(sb, "&lt;");
2226 			break;
2227 		default:
2228 			retval = sbuf_putc(sb, *str);
2229 			break;
2230 		}
2231 
2232 		if (retval != 0)
2233 			break;
2234 
2235 	}
2236 
2237 	return (retval);
2238 }
2239 
2240 static int
2241 ctl_ioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag,
2242 	  struct thread *td)
2243 {
2244 	struct ctl_softc *softc;
2245 	int retval;
2246 
2247 	softc = control_softc;
2248 
2249 	retval = 0;
2250 
2251 	switch (cmd) {
2252 	case CTL_IO: {
2253 		union ctl_io *io;
2254 		void *pool_tmp;
2255 
2256 		/*
2257 		 * If we haven't been "enabled", don't allow any SCSI I/O
2258 		 * to this FETD.
2259 		 */
2260 		if ((softc->ioctl_info.flags & CTL_IOCTL_FLAG_ENABLED) == 0) {
2261 			retval = EPERM;
2262 			break;
2263 		}
2264 
2265 		io = ctl_alloc_io(softc->ioctl_info.port.ctl_pool_ref);
2266 		if (io == NULL) {
2267 			printf("ctl_ioctl: can't allocate ctl_io!\n");
2268 			retval = ENOSPC;
2269 			break;
2270 		}
2271 
2272 		/*
2273 		 * Need to save the pool reference so it doesn't get
2274 		 * spammed by the user's ctl_io.
2275 		 */
2276 		pool_tmp = io->io_hdr.pool;
2277 
2278 		memcpy(io, (void *)addr, sizeof(*io));
2279 
2280 		io->io_hdr.pool = pool_tmp;
2281 		/*
2282 		 * No status yet, so make sure the status is set properly.
2283 		 */
2284 		io->io_hdr.status = CTL_STATUS_NONE;
2285 
2286 		/*
2287 		 * The user sets the initiator ID, target and LUN IDs.
2288 		 */
2289 		io->io_hdr.nexus.targ_port = softc->ioctl_info.port.targ_port;
2290 		io->io_hdr.flags |= CTL_FLAG_USER_REQ;
2291 		if ((io->io_hdr.io_type == CTL_IO_SCSI)
2292 		 && (io->scsiio.tag_type != CTL_TAG_UNTAGGED))
2293 			io->scsiio.tag_num = softc->ioctl_info.cur_tag_num++;
2294 
2295 		retval = ctl_ioctl_submit_wait(io);
2296 
2297 		if (retval != 0) {
2298 			ctl_free_io(io);
2299 			break;
2300 		}
2301 
2302 		memcpy((void *)addr, io, sizeof(*io));
2303 
2304 		/* return this to our pool */
2305 		ctl_free_io(io);
2306 
2307 		break;
2308 	}
2309 	case CTL_ENABLE_PORT:
2310 	case CTL_DISABLE_PORT:
2311 	case CTL_SET_PORT_WWNS: {
2312 		struct ctl_port *port;
2313 		struct ctl_port_entry *entry;
2314 
2315 		entry = (struct ctl_port_entry *)addr;
2316 
2317 		mtx_lock(&softc->ctl_lock);
2318 		STAILQ_FOREACH(port, &softc->port_list, links) {
2319 			int action, done;
2320 
2321 			action = 0;
2322 			done = 0;
2323 
2324 			if ((entry->port_type == CTL_PORT_NONE)
2325 			 && (entry->targ_port == port->targ_port)) {
2326 				/*
2327 				 * If the user only wants to enable or
2328 				 * disable or set WWNs on a specific port,
2329 				 * do the operation and we're done.
2330 				 */
2331 				action = 1;
2332 				done = 1;
2333 			} else if (entry->port_type & port->port_type) {
2334 				/*
2335 				 * Compare the user's type mask with the
2336 				 * particular frontend type to see if we
2337 				 * have a match.
2338 				 */
2339 				action = 1;
2340 				done = 0;
2341 
2342 				/*
2343 				 * Make sure the user isn't trying to set
2344 				 * WWNs on multiple ports at the same time.
2345 				 */
2346 				if (cmd == CTL_SET_PORT_WWNS) {
2347 					printf("%s: Can't set WWNs on "
2348 					       "multiple ports\n", __func__);
2349 					retval = EINVAL;
2350 					break;
2351 				}
2352 			}
2353 			if (action != 0) {
2354 				/*
2355 				 * XXX KDM we have to drop the lock here,
2356 				 * because the online/offline operations
2357 				 * can potentially block.  We need to
2358 				 * reference count the frontends so they
2359 				 * can't go away,
2360 				 */
2361 				mtx_unlock(&softc->ctl_lock);
2362 
2363 				if (cmd == CTL_ENABLE_PORT) {
2364 					struct ctl_lun *lun;
2365 
2366 					STAILQ_FOREACH(lun, &softc->lun_list,
2367 						       links) {
2368 						port->lun_enable(port->targ_lun_arg,
2369 						    lun->target,
2370 						    lun->lun);
2371 					}
2372 
2373 					ctl_port_online(port);
2374 				} else if (cmd == CTL_DISABLE_PORT) {
2375 					struct ctl_lun *lun;
2376 
2377 					ctl_port_offline(port);
2378 
2379 					STAILQ_FOREACH(lun, &softc->lun_list,
2380 						       links) {
2381 						port->lun_disable(
2382 						    port->targ_lun_arg,
2383 						    lun->target,
2384 						    lun->lun);
2385 					}
2386 				}
2387 
2388 				mtx_lock(&softc->ctl_lock);
2389 
2390 				if (cmd == CTL_SET_PORT_WWNS)
2391 					ctl_port_set_wwns(port,
2392 					    (entry->flags & CTL_PORT_WWNN_VALID) ?
2393 					    1 : 0, entry->wwnn,
2394 					    (entry->flags & CTL_PORT_WWPN_VALID) ?
2395 					    1 : 0, entry->wwpn);
2396 			}
2397 			if (done != 0)
2398 				break;
2399 		}
2400 		mtx_unlock(&softc->ctl_lock);
2401 		break;
2402 	}
2403 	case CTL_GET_PORT_LIST: {
2404 		struct ctl_port *port;
2405 		struct ctl_port_list *list;
2406 		int i;
2407 
2408 		list = (struct ctl_port_list *)addr;
2409 
2410 		if (list->alloc_len != (list->alloc_num *
2411 		    sizeof(struct ctl_port_entry))) {
2412 			printf("%s: CTL_GET_PORT_LIST: alloc_len %u != "
2413 			       "alloc_num %u * sizeof(struct ctl_port_entry) "
2414 			       "%zu\n", __func__, list->alloc_len,
2415 			       list->alloc_num, sizeof(struct ctl_port_entry));
2416 			retval = EINVAL;
2417 			break;
2418 		}
2419 		list->fill_len = 0;
2420 		list->fill_num = 0;
2421 		list->dropped_num = 0;
2422 		i = 0;
2423 		mtx_lock(&softc->ctl_lock);
2424 		STAILQ_FOREACH(port, &softc->port_list, links) {
2425 			struct ctl_port_entry entry, *list_entry;
2426 
2427 			if (list->fill_num >= list->alloc_num) {
2428 				list->dropped_num++;
2429 				continue;
2430 			}
2431 
2432 			entry.port_type = port->port_type;
2433 			strlcpy(entry.port_name, port->port_name,
2434 				sizeof(entry.port_name));
2435 			entry.targ_port = port->targ_port;
2436 			entry.physical_port = port->physical_port;
2437 			entry.virtual_port = port->virtual_port;
2438 			entry.wwnn = port->wwnn;
2439 			entry.wwpn = port->wwpn;
2440 			if (port->status & CTL_PORT_STATUS_ONLINE)
2441 				entry.online = 1;
2442 			else
2443 				entry.online = 0;
2444 
2445 			list_entry = &list->entries[i];
2446 
2447 			retval = copyout(&entry, list_entry, sizeof(entry));
2448 			if (retval != 0) {
2449 				printf("%s: CTL_GET_PORT_LIST: copyout "
2450 				       "returned %d\n", __func__, retval);
2451 				break;
2452 			}
2453 			i++;
2454 			list->fill_num++;
2455 			list->fill_len += sizeof(entry);
2456 		}
2457 		mtx_unlock(&softc->ctl_lock);
2458 
2459 		/*
2460 		 * If this is non-zero, we had a copyout fault, so there's
2461 		 * probably no point in attempting to set the status inside
2462 		 * the structure.
2463 		 */
2464 		if (retval != 0)
2465 			break;
2466 
2467 		if (list->dropped_num > 0)
2468 			list->status = CTL_PORT_LIST_NEED_MORE_SPACE;
2469 		else
2470 			list->status = CTL_PORT_LIST_OK;
2471 		break;
2472 	}
2473 	case CTL_DUMP_OOA: {
2474 		struct ctl_lun *lun;
2475 		union ctl_io *io;
2476 		char printbuf[128];
2477 		struct sbuf sb;
2478 
2479 		mtx_lock(&softc->ctl_lock);
2480 		printf("Dumping OOA queues:\n");
2481 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
2482 			mtx_lock(&lun->lun_lock);
2483 			for (io = (union ctl_io *)TAILQ_FIRST(
2484 			     &lun->ooa_queue); io != NULL;
2485 			     io = (union ctl_io *)TAILQ_NEXT(&io->io_hdr,
2486 			     ooa_links)) {
2487 				sbuf_new(&sb, printbuf, sizeof(printbuf),
2488 					 SBUF_FIXEDLEN);
2489 				sbuf_printf(&sb, "LUN %jd tag 0x%04x%s%s%s%s: ",
2490 					    (intmax_t)lun->lun,
2491 					    io->scsiio.tag_num,
2492 					    (io->io_hdr.flags &
2493 					    CTL_FLAG_BLOCKED) ? "" : " BLOCKED",
2494 					    (io->io_hdr.flags &
2495 					    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
2496 					    (io->io_hdr.flags &
2497 					    CTL_FLAG_ABORT) ? " ABORT" : "",
2498 			                    (io->io_hdr.flags &
2499 		                        CTL_FLAG_IS_WAS_ON_RTR) ? " RTR" : "");
2500 				ctl_scsi_command_string(&io->scsiio, NULL, &sb);
2501 				sbuf_finish(&sb);
2502 				printf("%s\n", sbuf_data(&sb));
2503 			}
2504 			mtx_unlock(&lun->lun_lock);
2505 		}
2506 		printf("OOA queues dump done\n");
2507 		mtx_unlock(&softc->ctl_lock);
2508 		break;
2509 	}
2510 	case CTL_GET_OOA: {
2511 		struct ctl_lun *lun;
2512 		struct ctl_ooa *ooa_hdr;
2513 		struct ctl_ooa_entry *entries;
2514 		uint32_t cur_fill_num;
2515 
2516 		ooa_hdr = (struct ctl_ooa *)addr;
2517 
2518 		if ((ooa_hdr->alloc_len == 0)
2519 		 || (ooa_hdr->alloc_num == 0)) {
2520 			printf("%s: CTL_GET_OOA: alloc len %u and alloc num %u "
2521 			       "must be non-zero\n", __func__,
2522 			       ooa_hdr->alloc_len, ooa_hdr->alloc_num);
2523 			retval = EINVAL;
2524 			break;
2525 		}
2526 
2527 		if (ooa_hdr->alloc_len != (ooa_hdr->alloc_num *
2528 		    sizeof(struct ctl_ooa_entry))) {
2529 			printf("%s: CTL_GET_OOA: alloc len %u must be alloc "
2530 			       "num %d * sizeof(struct ctl_ooa_entry) %zd\n",
2531 			       __func__, ooa_hdr->alloc_len,
2532 			       ooa_hdr->alloc_num,sizeof(struct ctl_ooa_entry));
2533 			retval = EINVAL;
2534 			break;
2535 		}
2536 
2537 		entries = malloc(ooa_hdr->alloc_len, M_CTL, M_WAITOK | M_ZERO);
2538 		if (entries == NULL) {
2539 			printf("%s: could not allocate %d bytes for OOA "
2540 			       "dump\n", __func__, ooa_hdr->alloc_len);
2541 			retval = ENOMEM;
2542 			break;
2543 		}
2544 
2545 		mtx_lock(&softc->ctl_lock);
2546 		if (((ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) == 0)
2547 		 && ((ooa_hdr->lun_num >= CTL_MAX_LUNS)
2548 		  || (softc->ctl_luns[ooa_hdr->lun_num] == NULL))) {
2549 			mtx_unlock(&softc->ctl_lock);
2550 			free(entries, M_CTL);
2551 			printf("%s: CTL_GET_OOA: invalid LUN %ju\n",
2552 			       __func__, (uintmax_t)ooa_hdr->lun_num);
2553 			retval = EINVAL;
2554 			break;
2555 		}
2556 
2557 		cur_fill_num = 0;
2558 
2559 		if (ooa_hdr->flags & CTL_OOA_FLAG_ALL_LUNS) {
2560 			STAILQ_FOREACH(lun, &softc->lun_list, links) {
2561 				retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,
2562 					ooa_hdr, entries);
2563 				if (retval != 0)
2564 					break;
2565 			}
2566 			if (retval != 0) {
2567 				mtx_unlock(&softc->ctl_lock);
2568 				free(entries, M_CTL);
2569 				break;
2570 			}
2571 		} else {
2572 			lun = softc->ctl_luns[ooa_hdr->lun_num];
2573 
2574 			retval = ctl_ioctl_fill_ooa(lun, &cur_fill_num,ooa_hdr,
2575 						    entries);
2576 		}
2577 		mtx_unlock(&softc->ctl_lock);
2578 
2579 		ooa_hdr->fill_num = min(cur_fill_num, ooa_hdr->alloc_num);
2580 		ooa_hdr->fill_len = ooa_hdr->fill_num *
2581 			sizeof(struct ctl_ooa_entry);
2582 		retval = copyout(entries, ooa_hdr->entries, ooa_hdr->fill_len);
2583 		if (retval != 0) {
2584 			printf("%s: error copying out %d bytes for OOA dump\n",
2585 			       __func__, ooa_hdr->fill_len);
2586 		}
2587 
2588 		getbintime(&ooa_hdr->cur_bt);
2589 
2590 		if (cur_fill_num > ooa_hdr->alloc_num) {
2591 			ooa_hdr->dropped_num = cur_fill_num -ooa_hdr->alloc_num;
2592 			ooa_hdr->status = CTL_OOA_NEED_MORE_SPACE;
2593 		} else {
2594 			ooa_hdr->dropped_num = 0;
2595 			ooa_hdr->status = CTL_OOA_OK;
2596 		}
2597 
2598 		free(entries, M_CTL);
2599 		break;
2600 	}
2601 	case CTL_CHECK_OOA: {
2602 		union ctl_io *io;
2603 		struct ctl_lun *lun;
2604 		struct ctl_ooa_info *ooa_info;
2605 
2606 
2607 		ooa_info = (struct ctl_ooa_info *)addr;
2608 
2609 		if (ooa_info->lun_id >= CTL_MAX_LUNS) {
2610 			ooa_info->status = CTL_OOA_INVALID_LUN;
2611 			break;
2612 		}
2613 		mtx_lock(&softc->ctl_lock);
2614 		lun = softc->ctl_luns[ooa_info->lun_id];
2615 		if (lun == NULL) {
2616 			mtx_unlock(&softc->ctl_lock);
2617 			ooa_info->status = CTL_OOA_INVALID_LUN;
2618 			break;
2619 		}
2620 		mtx_lock(&lun->lun_lock);
2621 		mtx_unlock(&softc->ctl_lock);
2622 		ooa_info->num_entries = 0;
2623 		for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
2624 		     io != NULL; io = (union ctl_io *)TAILQ_NEXT(
2625 		     &io->io_hdr, ooa_links)) {
2626 			ooa_info->num_entries++;
2627 		}
2628 		mtx_unlock(&lun->lun_lock);
2629 
2630 		ooa_info->status = CTL_OOA_SUCCESS;
2631 
2632 		break;
2633 	}
2634 	case CTL_HARD_START:
2635 	case CTL_HARD_STOP: {
2636 		struct ctl_fe_ioctl_startstop_info ss_info;
2637 		struct cfi_metatask *metatask;
2638 		struct mtx hs_mtx;
2639 
2640 		mtx_init(&hs_mtx, "HS Mutex", NULL, MTX_DEF);
2641 
2642 		cv_init(&ss_info.sem, "hard start/stop cv" );
2643 
2644 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2645 		if (metatask == NULL) {
2646 			retval = ENOMEM;
2647 			mtx_destroy(&hs_mtx);
2648 			break;
2649 		}
2650 
2651 		if (cmd == CTL_HARD_START)
2652 			metatask->tasktype = CFI_TASK_STARTUP;
2653 		else
2654 			metatask->tasktype = CFI_TASK_SHUTDOWN;
2655 
2656 		metatask->callback = ctl_ioctl_hard_startstop_callback;
2657 		metatask->callback_arg = &ss_info;
2658 
2659 		cfi_action(metatask);
2660 
2661 		/* Wait for the callback */
2662 		mtx_lock(&hs_mtx);
2663 		cv_wait_sig(&ss_info.sem, &hs_mtx);
2664 		mtx_unlock(&hs_mtx);
2665 
2666 		/*
2667 		 * All information has been copied from the metatask by the
2668 		 * time cv_broadcast() is called, so we free the metatask here.
2669 		 */
2670 		cfi_free_metatask(metatask);
2671 
2672 		memcpy((void *)addr, &ss_info.hs_info, sizeof(ss_info.hs_info));
2673 
2674 		mtx_destroy(&hs_mtx);
2675 		break;
2676 	}
2677 	case CTL_BBRREAD: {
2678 		struct ctl_bbrread_info *bbr_info;
2679 		struct ctl_fe_ioctl_bbrread_info fe_bbr_info;
2680 		struct mtx bbr_mtx;
2681 		struct cfi_metatask *metatask;
2682 
2683 		bbr_info = (struct ctl_bbrread_info *)addr;
2684 
2685 		bzero(&fe_bbr_info, sizeof(fe_bbr_info));
2686 
2687 		bzero(&bbr_mtx, sizeof(bbr_mtx));
2688 		mtx_init(&bbr_mtx, "BBR Mutex", NULL, MTX_DEF);
2689 
2690 		fe_bbr_info.bbr_info = bbr_info;
2691 		fe_bbr_info.lock = &bbr_mtx;
2692 
2693 		cv_init(&fe_bbr_info.sem, "BBR read cv");
2694 		metatask = cfi_alloc_metatask(/*can_wait*/ 1);
2695 
2696 		if (metatask == NULL) {
2697 			mtx_destroy(&bbr_mtx);
2698 			cv_destroy(&fe_bbr_info.sem);
2699 			retval = ENOMEM;
2700 			break;
2701 		}
2702 		metatask->tasktype = CFI_TASK_BBRREAD;
2703 		metatask->callback = ctl_ioctl_bbrread_callback;
2704 		metatask->callback_arg = &fe_bbr_info;
2705 		metatask->taskinfo.bbrread.lun_num = bbr_info->lun_num;
2706 		metatask->taskinfo.bbrread.lba = bbr_info->lba;
2707 		metatask->taskinfo.bbrread.len = bbr_info->len;
2708 
2709 		cfi_action(metatask);
2710 
2711 		mtx_lock(&bbr_mtx);
2712 		while (fe_bbr_info.wakeup_done == 0)
2713 			cv_wait_sig(&fe_bbr_info.sem, &bbr_mtx);
2714 		mtx_unlock(&bbr_mtx);
2715 
2716 		bbr_info->status = metatask->status;
2717 		bbr_info->bbr_status = metatask->taskinfo.bbrread.status;
2718 		bbr_info->scsi_status = metatask->taskinfo.bbrread.scsi_status;
2719 		memcpy(&bbr_info->sense_data,
2720 		       &metatask->taskinfo.bbrread.sense_data,
2721 		       ctl_min(sizeof(bbr_info->sense_data),
2722 			       sizeof(metatask->taskinfo.bbrread.sense_data)));
2723 
2724 		cfi_free_metatask(metatask);
2725 
2726 		mtx_destroy(&bbr_mtx);
2727 		cv_destroy(&fe_bbr_info.sem);
2728 
2729 		break;
2730 	}
2731 	case CTL_DELAY_IO: {
2732 		struct ctl_io_delay_info *delay_info;
2733 #ifdef CTL_IO_DELAY
2734 		struct ctl_lun *lun;
2735 #endif /* CTL_IO_DELAY */
2736 
2737 		delay_info = (struct ctl_io_delay_info *)addr;
2738 
2739 #ifdef CTL_IO_DELAY
2740 		mtx_lock(&softc->ctl_lock);
2741 
2742 		if ((delay_info->lun_id >= CTL_MAX_LUNS)
2743 		 || (softc->ctl_luns[delay_info->lun_id] == NULL)) {
2744 			delay_info->status = CTL_DELAY_STATUS_INVALID_LUN;
2745 		} else {
2746 			lun = softc->ctl_luns[delay_info->lun_id];
2747 			mtx_lock(&lun->lun_lock);
2748 
2749 			delay_info->status = CTL_DELAY_STATUS_OK;
2750 
2751 			switch (delay_info->delay_type) {
2752 			case CTL_DELAY_TYPE_CONT:
2753 				break;
2754 			case CTL_DELAY_TYPE_ONESHOT:
2755 				break;
2756 			default:
2757 				delay_info->status =
2758 					CTL_DELAY_STATUS_INVALID_TYPE;
2759 				break;
2760 			}
2761 
2762 			switch (delay_info->delay_loc) {
2763 			case CTL_DELAY_LOC_DATAMOVE:
2764 				lun->delay_info.datamove_type =
2765 					delay_info->delay_type;
2766 				lun->delay_info.datamove_delay =
2767 					delay_info->delay_secs;
2768 				break;
2769 			case CTL_DELAY_LOC_DONE:
2770 				lun->delay_info.done_type =
2771 					delay_info->delay_type;
2772 				lun->delay_info.done_delay =
2773 					delay_info->delay_secs;
2774 				break;
2775 			default:
2776 				delay_info->status =
2777 					CTL_DELAY_STATUS_INVALID_LOC;
2778 				break;
2779 			}
2780 			mtx_unlock(&lun->lun_lock);
2781 		}
2782 
2783 		mtx_unlock(&softc->ctl_lock);
2784 #else
2785 		delay_info->status = CTL_DELAY_STATUS_NOT_IMPLEMENTED;
2786 #endif /* CTL_IO_DELAY */
2787 		break;
2788 	}
2789 	case CTL_REALSYNC_SET: {
2790 		int *syncstate;
2791 
2792 		syncstate = (int *)addr;
2793 
2794 		mtx_lock(&softc->ctl_lock);
2795 		switch (*syncstate) {
2796 		case 0:
2797 			softc->flags &= ~CTL_FLAG_REAL_SYNC;
2798 			break;
2799 		case 1:
2800 			softc->flags |= CTL_FLAG_REAL_SYNC;
2801 			break;
2802 		default:
2803 			retval = EINVAL;
2804 			break;
2805 		}
2806 		mtx_unlock(&softc->ctl_lock);
2807 		break;
2808 	}
2809 	case CTL_REALSYNC_GET: {
2810 		int *syncstate;
2811 
2812 		syncstate = (int*)addr;
2813 
2814 		mtx_lock(&softc->ctl_lock);
2815 		if (softc->flags & CTL_FLAG_REAL_SYNC)
2816 			*syncstate = 1;
2817 		else
2818 			*syncstate = 0;
2819 		mtx_unlock(&softc->ctl_lock);
2820 
2821 		break;
2822 	}
2823 	case CTL_SETSYNC:
2824 	case CTL_GETSYNC: {
2825 		struct ctl_sync_info *sync_info;
2826 		struct ctl_lun *lun;
2827 
2828 		sync_info = (struct ctl_sync_info *)addr;
2829 
2830 		mtx_lock(&softc->ctl_lock);
2831 		lun = softc->ctl_luns[sync_info->lun_id];
2832 		if (lun == NULL) {
2833 			mtx_unlock(&softc->ctl_lock);
2834 			sync_info->status = CTL_GS_SYNC_NO_LUN;
2835 		}
2836 		/*
2837 		 * Get or set the sync interval.  We're not bounds checking
2838 		 * in the set case, hopefully the user won't do something
2839 		 * silly.
2840 		 */
2841 		mtx_lock(&lun->lun_lock);
2842 		mtx_unlock(&softc->ctl_lock);
2843 		if (cmd == CTL_GETSYNC)
2844 			sync_info->sync_interval = lun->sync_interval;
2845 		else
2846 			lun->sync_interval = sync_info->sync_interval;
2847 		mtx_unlock(&lun->lun_lock);
2848 
2849 		sync_info->status = CTL_GS_SYNC_OK;
2850 
2851 		break;
2852 	}
2853 	case CTL_GETSTATS: {
2854 		struct ctl_stats *stats;
2855 		struct ctl_lun *lun;
2856 		int i;
2857 
2858 		stats = (struct ctl_stats *)addr;
2859 
2860 		if ((sizeof(struct ctl_lun_io_stats) * softc->num_luns) >
2861 		     stats->alloc_len) {
2862 			stats->status = CTL_SS_NEED_MORE_SPACE;
2863 			stats->num_luns = softc->num_luns;
2864 			break;
2865 		}
2866 		/*
2867 		 * XXX KDM no locking here.  If the LUN list changes,
2868 		 * things can blow up.
2869 		 */
2870 		for (i = 0, lun = STAILQ_FIRST(&softc->lun_list); lun != NULL;
2871 		     i++, lun = STAILQ_NEXT(lun, links)) {
2872 			retval = copyout(&lun->stats, &stats->lun_stats[i],
2873 					 sizeof(lun->stats));
2874 			if (retval != 0)
2875 				break;
2876 		}
2877 		stats->num_luns = softc->num_luns;
2878 		stats->fill_len = sizeof(struct ctl_lun_io_stats) *
2879 				 softc->num_luns;
2880 		stats->status = CTL_SS_OK;
2881 #ifdef CTL_TIME_IO
2882 		stats->flags = CTL_STATS_FLAG_TIME_VALID;
2883 #else
2884 		stats->flags = CTL_STATS_FLAG_NONE;
2885 #endif
2886 		getnanouptime(&stats->timestamp);
2887 		break;
2888 	}
2889 	case CTL_ERROR_INJECT: {
2890 		struct ctl_error_desc *err_desc, *new_err_desc;
2891 		struct ctl_lun *lun;
2892 
2893 		err_desc = (struct ctl_error_desc *)addr;
2894 
2895 		new_err_desc = malloc(sizeof(*new_err_desc), M_CTL,
2896 				      M_WAITOK | M_ZERO);
2897 		bcopy(err_desc, new_err_desc, sizeof(*new_err_desc));
2898 
2899 		mtx_lock(&softc->ctl_lock);
2900 		lun = softc->ctl_luns[err_desc->lun_id];
2901 		if (lun == NULL) {
2902 			mtx_unlock(&softc->ctl_lock);
2903 			free(new_err_desc, M_CTL);
2904 			printf("%s: CTL_ERROR_INJECT: invalid LUN %ju\n",
2905 			       __func__, (uintmax_t)err_desc->lun_id);
2906 			retval = EINVAL;
2907 			break;
2908 		}
2909 		mtx_lock(&lun->lun_lock);
2910 		mtx_unlock(&softc->ctl_lock);
2911 
2912 		/*
2913 		 * We could do some checking here to verify the validity
2914 		 * of the request, but given the complexity of error
2915 		 * injection requests, the checking logic would be fairly
2916 		 * complex.
2917 		 *
2918 		 * For now, if the request is invalid, it just won't get
2919 		 * executed and might get deleted.
2920 		 */
2921 		STAILQ_INSERT_TAIL(&lun->error_list, new_err_desc, links);
2922 
2923 		/*
2924 		 * XXX KDM check to make sure the serial number is unique,
2925 		 * in case we somehow manage to wrap.  That shouldn't
2926 		 * happen for a very long time, but it's the right thing to
2927 		 * do.
2928 		 */
2929 		new_err_desc->serial = lun->error_serial;
2930 		err_desc->serial = lun->error_serial;
2931 		lun->error_serial++;
2932 
2933 		mtx_unlock(&lun->lun_lock);
2934 		break;
2935 	}
2936 	case CTL_ERROR_INJECT_DELETE: {
2937 		struct ctl_error_desc *delete_desc, *desc, *desc2;
2938 		struct ctl_lun *lun;
2939 		int delete_done;
2940 
2941 		delete_desc = (struct ctl_error_desc *)addr;
2942 		delete_done = 0;
2943 
2944 		mtx_lock(&softc->ctl_lock);
2945 		lun = softc->ctl_luns[delete_desc->lun_id];
2946 		if (lun == NULL) {
2947 			mtx_unlock(&softc->ctl_lock);
2948 			printf("%s: CTL_ERROR_INJECT_DELETE: invalid LUN %ju\n",
2949 			       __func__, (uintmax_t)delete_desc->lun_id);
2950 			retval = EINVAL;
2951 			break;
2952 		}
2953 		mtx_lock(&lun->lun_lock);
2954 		mtx_unlock(&softc->ctl_lock);
2955 		STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
2956 			if (desc->serial != delete_desc->serial)
2957 				continue;
2958 
2959 			STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc,
2960 				      links);
2961 			free(desc, M_CTL);
2962 			delete_done = 1;
2963 		}
2964 		mtx_unlock(&lun->lun_lock);
2965 		if (delete_done == 0) {
2966 			printf("%s: CTL_ERROR_INJECT_DELETE: can't find "
2967 			       "error serial %ju on LUN %u\n", __func__,
2968 			       delete_desc->serial, delete_desc->lun_id);
2969 			retval = EINVAL;
2970 			break;
2971 		}
2972 		break;
2973 	}
2974 	case CTL_DUMP_STRUCTS: {
2975 		int i, j, k, idx;
2976 		struct ctl_port *port;
2977 		struct ctl_frontend *fe;
2978 
2979 		mtx_lock(&softc->ctl_lock);
2980 		printf("CTL Persistent Reservation information start:\n");
2981 		for (i = 0; i < CTL_MAX_LUNS; i++) {
2982 			struct ctl_lun *lun;
2983 
2984 			lun = softc->ctl_luns[i];
2985 
2986 			if ((lun == NULL)
2987 			 || ((lun->flags & CTL_LUN_DISABLED) != 0))
2988 				continue;
2989 
2990 			for (j = 0; j < (CTL_MAX_PORTS * 2); j++) {
2991 				for (k = 0; k < CTL_MAX_INIT_PER_PORT; k++){
2992 					idx = j * CTL_MAX_INIT_PER_PORT + k;
2993 					if (lun->per_res[idx].registered == 0)
2994 						continue;
2995 					printf("  LUN %d port %d iid %d key "
2996 					       "%#jx\n", i, j, k,
2997 					       (uintmax_t)scsi_8btou64(
2998 					       lun->per_res[idx].res_key.key));
2999 				}
3000 			}
3001 		}
3002 		printf("CTL Persistent Reservation information end\n");
3003 		printf("CTL Ports:\n");
3004 		STAILQ_FOREACH(port, &softc->port_list, links) {
3005 			printf("  Port %d '%s' Frontend '%s' Type %u pp %d vp %d WWNN "
3006 			       "%#jx WWPN %#jx\n", port->targ_port, port->port_name,
3007 			       port->frontend->name, port->port_type,
3008 			       port->physical_port, port->virtual_port,
3009 			       (uintmax_t)port->wwnn, (uintmax_t)port->wwpn);
3010 			for (j = 0; j < CTL_MAX_INIT_PER_PORT; j++) {
3011 				if (port->wwpn_iid[j].in_use == 0 &&
3012 				    port->wwpn_iid[j].wwpn == 0 &&
3013 				    port->wwpn_iid[j].name == NULL)
3014 					continue;
3015 
3016 				printf("    iid %u use %d WWPN %#jx '%s'\n",
3017 				    j, port->wwpn_iid[j].in_use,
3018 				    (uintmax_t)port->wwpn_iid[j].wwpn,
3019 				    port->wwpn_iid[j].name);
3020 			}
3021 		}
3022 		printf("CTL Port information end\n");
3023 		mtx_unlock(&softc->ctl_lock);
3024 		/*
3025 		 * XXX KDM calling this without a lock.  We'd likely want
3026 		 * to drop the lock before calling the frontend's dump
3027 		 * routine anyway.
3028 		 */
3029 		printf("CTL Frontends:\n");
3030 		STAILQ_FOREACH(fe, &softc->fe_list, links) {
3031 			printf("  Frontend '%s'\n", fe->name);
3032 			if (fe->fe_dump != NULL)
3033 				fe->fe_dump();
3034 		}
3035 		printf("CTL Frontend information end\n");
3036 		break;
3037 	}
3038 	case CTL_LUN_REQ: {
3039 		struct ctl_lun_req *lun_req;
3040 		struct ctl_backend_driver *backend;
3041 
3042 		lun_req = (struct ctl_lun_req *)addr;
3043 
3044 		backend = ctl_backend_find(lun_req->backend);
3045 		if (backend == NULL) {
3046 			lun_req->status = CTL_LUN_ERROR;
3047 			snprintf(lun_req->error_str,
3048 				 sizeof(lun_req->error_str),
3049 				 "Backend \"%s\" not found.",
3050 				 lun_req->backend);
3051 			break;
3052 		}
3053 		if (lun_req->num_be_args > 0) {
3054 			lun_req->kern_be_args = ctl_copyin_args(
3055 				lun_req->num_be_args,
3056 				lun_req->be_args,
3057 				lun_req->error_str,
3058 				sizeof(lun_req->error_str));
3059 			if (lun_req->kern_be_args == NULL) {
3060 				lun_req->status = CTL_LUN_ERROR;
3061 				break;
3062 			}
3063 		}
3064 
3065 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3066 
3067 		if (lun_req->num_be_args > 0) {
3068 			ctl_copyout_args(lun_req->num_be_args,
3069 				      lun_req->kern_be_args);
3070 			ctl_free_args(lun_req->num_be_args,
3071 				      lun_req->kern_be_args);
3072 		}
3073 		break;
3074 	}
3075 	case CTL_LUN_LIST: {
3076 		struct sbuf *sb;
3077 		struct ctl_lun *lun;
3078 		struct ctl_lun_list *list;
3079 		struct ctl_option *opt;
3080 
3081 		list = (struct ctl_lun_list *)addr;
3082 
3083 		/*
3084 		 * Allocate a fixed length sbuf here, based on the length
3085 		 * of the user's buffer.  We could allocate an auto-extending
3086 		 * buffer, and then tell the user how much larger our
3087 		 * amount of data is than his buffer, but that presents
3088 		 * some problems:
3089 		 *
3090 		 * 1.  The sbuf(9) routines use a blocking malloc, and so
3091 		 *     we can't hold a lock while calling them with an
3092 		 *     auto-extending buffer.
3093  		 *
3094 		 * 2.  There is not currently a LUN reference counting
3095 		 *     mechanism, outside of outstanding transactions on
3096 		 *     the LUN's OOA queue.  So a LUN could go away on us
3097 		 *     while we're getting the LUN number, backend-specific
3098 		 *     information, etc.  Thus, given the way things
3099 		 *     currently work, we need to hold the CTL lock while
3100 		 *     grabbing LUN information.
3101 		 *
3102 		 * So, from the user's standpoint, the best thing to do is
3103 		 * allocate what he thinks is a reasonable buffer length,
3104 		 * and then if he gets a CTL_LUN_LIST_NEED_MORE_SPACE error,
3105 		 * double the buffer length and try again.  (And repeat
3106 		 * that until he succeeds.)
3107 		 */
3108 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3109 		if (sb == NULL) {
3110 			list->status = CTL_LUN_LIST_ERROR;
3111 			snprintf(list->error_str, sizeof(list->error_str),
3112 				 "Unable to allocate %d bytes for LUN list",
3113 				 list->alloc_len);
3114 			break;
3115 		}
3116 
3117 		sbuf_printf(sb, "<ctllunlist>\n");
3118 
3119 		mtx_lock(&softc->ctl_lock);
3120 		STAILQ_FOREACH(lun, &softc->lun_list, links) {
3121 			mtx_lock(&lun->lun_lock);
3122 			retval = sbuf_printf(sb, "<lun id=\"%ju\">\n",
3123 					     (uintmax_t)lun->lun);
3124 
3125 			/*
3126 			 * Bail out as soon as we see that we've overfilled
3127 			 * the buffer.
3128 			 */
3129 			if (retval != 0)
3130 				break;
3131 
3132 			retval = sbuf_printf(sb, "\t<backend_type>%s"
3133 					     "</backend_type>\n",
3134 					     (lun->backend == NULL) ?  "none" :
3135 					     lun->backend->name);
3136 
3137 			if (retval != 0)
3138 				break;
3139 
3140 			retval = sbuf_printf(sb, "\t<lun_type>%d</lun_type>\n",
3141 					     lun->be_lun->lun_type);
3142 
3143 			if (retval != 0)
3144 				break;
3145 
3146 			if (lun->backend == NULL) {
3147 				retval = sbuf_printf(sb, "</lun>\n");
3148 				if (retval != 0)
3149 					break;
3150 				continue;
3151 			}
3152 
3153 			retval = sbuf_printf(sb, "\t<size>%ju</size>\n",
3154 					     (lun->be_lun->maxlba > 0) ?
3155 					     lun->be_lun->maxlba + 1 : 0);
3156 
3157 			if (retval != 0)
3158 				break;
3159 
3160 			retval = sbuf_printf(sb, "\t<blocksize>%u</blocksize>\n",
3161 					     lun->be_lun->blocksize);
3162 
3163 			if (retval != 0)
3164 				break;
3165 
3166 			retval = sbuf_printf(sb, "\t<serial_number>");
3167 
3168 			if (retval != 0)
3169 				break;
3170 
3171 			retval = ctl_sbuf_printf_esc(sb,
3172 						     lun->be_lun->serial_num);
3173 
3174 			if (retval != 0)
3175 				break;
3176 
3177 			retval = sbuf_printf(sb, "</serial_number>\n");
3178 
3179 			if (retval != 0)
3180 				break;
3181 
3182 			retval = sbuf_printf(sb, "\t<device_id>");
3183 
3184 			if (retval != 0)
3185 				break;
3186 
3187 			retval = ctl_sbuf_printf_esc(sb,lun->be_lun->device_id);
3188 
3189 			if (retval != 0)
3190 				break;
3191 
3192 			retval = sbuf_printf(sb, "</device_id>\n");
3193 
3194 			if (retval != 0)
3195 				break;
3196 
3197 			if (lun->backend->lun_info != NULL) {
3198 				retval = lun->backend->lun_info(lun->be_lun->be_lun, sb);
3199 				if (retval != 0)
3200 					break;
3201 			}
3202 			STAILQ_FOREACH(opt, &lun->be_lun->options, links) {
3203 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3204 				    opt->name, opt->value, opt->name);
3205 				if (retval != 0)
3206 					break;
3207 			}
3208 
3209 			retval = sbuf_printf(sb, "</lun>\n");
3210 
3211 			if (retval != 0)
3212 				break;
3213 			mtx_unlock(&lun->lun_lock);
3214 		}
3215 		if (lun != NULL)
3216 			mtx_unlock(&lun->lun_lock);
3217 		mtx_unlock(&softc->ctl_lock);
3218 
3219 		if ((retval != 0)
3220 		 || ((retval = sbuf_printf(sb, "</ctllunlist>\n")) != 0)) {
3221 			retval = 0;
3222 			sbuf_delete(sb);
3223 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3224 			snprintf(list->error_str, sizeof(list->error_str),
3225 				 "Out of space, %d bytes is too small",
3226 				 list->alloc_len);
3227 			break;
3228 		}
3229 
3230 		sbuf_finish(sb);
3231 
3232 		retval = copyout(sbuf_data(sb), list->lun_xml,
3233 				 sbuf_len(sb) + 1);
3234 
3235 		list->fill_len = sbuf_len(sb) + 1;
3236 		list->status = CTL_LUN_LIST_OK;
3237 		sbuf_delete(sb);
3238 		break;
3239 	}
3240 	case CTL_ISCSI: {
3241 		struct ctl_iscsi *ci;
3242 		struct ctl_frontend *fe;
3243 
3244 		ci = (struct ctl_iscsi *)addr;
3245 
3246 		fe = ctl_frontend_find("iscsi");
3247 		if (fe == NULL) {
3248 			ci->status = CTL_ISCSI_ERROR;
3249 			snprintf(ci->error_str, sizeof(ci->error_str),
3250 			    "Frontend \"iscsi\" not found.");
3251 			break;
3252 		}
3253 
3254 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3255 		break;
3256 	}
3257 	case CTL_PORT_REQ: {
3258 		struct ctl_req *req;
3259 		struct ctl_frontend *fe;
3260 
3261 		req = (struct ctl_req *)addr;
3262 
3263 		fe = ctl_frontend_find(req->driver);
3264 		if (fe == NULL) {
3265 			req->status = CTL_LUN_ERROR;
3266 			snprintf(req->error_str, sizeof(req->error_str),
3267 			    "Frontend \"%s\" not found.", req->driver);
3268 			break;
3269 		}
3270 		if (req->num_args > 0) {
3271 			req->kern_args = ctl_copyin_args(req->num_args,
3272 			    req->args, req->error_str, sizeof(req->error_str));
3273 			if (req->kern_args == NULL) {
3274 				req->status = CTL_LUN_ERROR;
3275 				break;
3276 			}
3277 		}
3278 
3279 		retval = fe->ioctl(dev, cmd, addr, flag, td);
3280 
3281 		if (req->num_args > 0) {
3282 			ctl_copyout_args(req->num_args, req->kern_args);
3283 			ctl_free_args(req->num_args, req->kern_args);
3284 		}
3285 		break;
3286 	}
3287 	case CTL_PORT_LIST: {
3288 		struct sbuf *sb;
3289 		struct ctl_port *port;
3290 		struct ctl_lun_list *list;
3291 		struct ctl_option *opt;
3292 
3293 		list = (struct ctl_lun_list *)addr;
3294 
3295 		sb = sbuf_new(NULL, NULL, list->alloc_len, SBUF_FIXEDLEN);
3296 		if (sb == NULL) {
3297 			list->status = CTL_LUN_LIST_ERROR;
3298 			snprintf(list->error_str, sizeof(list->error_str),
3299 				 "Unable to allocate %d bytes for LUN list",
3300 				 list->alloc_len);
3301 			break;
3302 		}
3303 
3304 		sbuf_printf(sb, "<ctlportlist>\n");
3305 
3306 		mtx_lock(&softc->ctl_lock);
3307 		STAILQ_FOREACH(port, &softc->port_list, links) {
3308 			retval = sbuf_printf(sb, "<targ_port id=\"%ju\">\n",
3309 					     (uintmax_t)port->targ_port);
3310 
3311 			/*
3312 			 * Bail out as soon as we see that we've overfilled
3313 			 * the buffer.
3314 			 */
3315 			if (retval != 0)
3316 				break;
3317 
3318 			retval = sbuf_printf(sb, "\t<frontend_type>%s"
3319 			    "</frontend_type>\n", port->frontend->name);
3320 			if (retval != 0)
3321 				break;
3322 
3323 			retval = sbuf_printf(sb, "\t<port_type>%d</port_type>\n",
3324 					     port->port_type);
3325 			if (retval != 0)
3326 				break;
3327 
3328 			retval = sbuf_printf(sb, "\t<online>%s</online>\n",
3329 			    (port->status & CTL_PORT_STATUS_ONLINE) ? "YES" : "NO");
3330 			if (retval != 0)
3331 				break;
3332 
3333 			retval = sbuf_printf(sb, "\t<port_name>%s</port_name>\n",
3334 			    port->port_name);
3335 			if (retval != 0)
3336 				break;
3337 
3338 			retval = sbuf_printf(sb, "\t<physical_port>%d</physical_port>\n",
3339 			    port->physical_port);
3340 			if (retval != 0)
3341 				break;
3342 
3343 			retval = sbuf_printf(sb, "\t<virtual_port>%d</virtual_port>\n",
3344 			    port->virtual_port);
3345 			if (retval != 0)
3346 				break;
3347 
3348 			retval = sbuf_printf(sb, "\t<wwnn>%#jx</wwnn>\n",
3349 			    (uintmax_t)port->wwnn);
3350 			if (retval != 0)
3351 				break;
3352 
3353 			retval = sbuf_printf(sb, "\t<wwpn>%#jx</wwpn>\n",
3354 			    (uintmax_t)port->wwpn);
3355 			if (retval != 0)
3356 				break;
3357 
3358 			if (port->port_info != NULL) {
3359 				retval = port->port_info(port->onoff_arg, sb);
3360 				if (retval != 0)
3361 					break;
3362 			}
3363 			STAILQ_FOREACH(opt, &port->options, links) {
3364 				retval = sbuf_printf(sb, "\t<%s>%s</%s>\n",
3365 				    opt->name, opt->value, opt->name);
3366 				if (retval != 0)
3367 					break;
3368 			}
3369 
3370 			retval = sbuf_printf(sb, "</targ_port>\n");
3371 			if (retval != 0)
3372 				break;
3373 		}
3374 		mtx_unlock(&softc->ctl_lock);
3375 
3376 		if ((retval != 0)
3377 		 || ((retval = sbuf_printf(sb, "</ctlportlist>\n")) != 0)) {
3378 			retval = 0;
3379 			sbuf_delete(sb);
3380 			list->status = CTL_LUN_LIST_NEED_MORE_SPACE;
3381 			snprintf(list->error_str, sizeof(list->error_str),
3382 				 "Out of space, %d bytes is too small",
3383 				 list->alloc_len);
3384 			break;
3385 		}
3386 
3387 		sbuf_finish(sb);
3388 
3389 		retval = copyout(sbuf_data(sb), list->lun_xml,
3390 				 sbuf_len(sb) + 1);
3391 
3392 		list->fill_len = sbuf_len(sb) + 1;
3393 		list->status = CTL_LUN_LIST_OK;
3394 		sbuf_delete(sb);
3395 		break;
3396 	}
3397 	default: {
3398 		/* XXX KDM should we fix this? */
3399 #if 0
3400 		struct ctl_backend_driver *backend;
3401 		unsigned int type;
3402 		int found;
3403 
3404 		found = 0;
3405 
3406 		/*
3407 		 * We encode the backend type as the ioctl type for backend
3408 		 * ioctls.  So parse it out here, and then search for a
3409 		 * backend of this type.
3410 		 */
3411 		type = _IOC_TYPE(cmd);
3412 
3413 		STAILQ_FOREACH(backend, &softc->be_list, links) {
3414 			if (backend->type == type) {
3415 				found = 1;
3416 				break;
3417 			}
3418 		}
3419 		if (found == 0) {
3420 			printf("ctl: unknown ioctl command %#lx or backend "
3421 			       "%d\n", cmd, type);
3422 			retval = EINVAL;
3423 			break;
3424 		}
3425 		retval = backend->ioctl(dev, cmd, addr, flag, td);
3426 #endif
3427 		retval = ENOTTY;
3428 		break;
3429 	}
3430 	}
3431 	return (retval);
3432 }
3433 
3434 uint32_t
3435 ctl_get_initindex(struct ctl_nexus *nexus)
3436 {
3437 	if (nexus->targ_port < CTL_MAX_PORTS)
3438 		return (nexus->initid.id +
3439 			(nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3440 	else
3441 		return (nexus->initid.id +
3442 		       ((nexus->targ_port - CTL_MAX_PORTS) *
3443 			CTL_MAX_INIT_PER_PORT));
3444 }
3445 
3446 uint32_t
3447 ctl_get_resindex(struct ctl_nexus *nexus)
3448 {
3449 	return (nexus->initid.id + (nexus->targ_port * CTL_MAX_INIT_PER_PORT));
3450 }
3451 
3452 uint32_t
3453 ctl_port_idx(int port_num)
3454 {
3455 	if (port_num < CTL_MAX_PORTS)
3456 		return(port_num);
3457 	else
3458 		return(port_num - CTL_MAX_PORTS);
3459 }
3460 
3461 static uint32_t
3462 ctl_map_lun(int port_num, uint32_t lun_id)
3463 {
3464 	struct ctl_port *port;
3465 
3466 	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3467 	if (port == NULL)
3468 		return (UINT32_MAX);
3469 	if (port->lun_map == NULL)
3470 		return (lun_id);
3471 	return (port->lun_map(port->targ_lun_arg, lun_id));
3472 }
3473 
3474 static uint32_t
3475 ctl_map_lun_back(int port_num, uint32_t lun_id)
3476 {
3477 	struct ctl_port *port;
3478 	uint32_t i;
3479 
3480 	port = control_softc->ctl_ports[ctl_port_idx(port_num)];
3481 	if (port->lun_map == NULL)
3482 		return (lun_id);
3483 	for (i = 0; i < CTL_MAX_LUNS; i++) {
3484 		if (port->lun_map(port->targ_lun_arg, i) == lun_id)
3485 			return (i);
3486 	}
3487 	return (UINT32_MAX);
3488 }
3489 
3490 /*
3491  * Note:  This only works for bitmask sizes that are at least 32 bits, and
3492  * that are a power of 2.
3493  */
3494 int
3495 ctl_ffz(uint32_t *mask, uint32_t size)
3496 {
3497 	uint32_t num_chunks, num_pieces;
3498 	int i, j;
3499 
3500 	num_chunks = (size >> 5);
3501 	if (num_chunks == 0)
3502 		num_chunks++;
3503 	num_pieces = ctl_min((sizeof(uint32_t) * 8), size);
3504 
3505 	for (i = 0; i < num_chunks; i++) {
3506 		for (j = 0; j < num_pieces; j++) {
3507 			if ((mask[i] & (1 << j)) == 0)
3508 				return ((i << 5) + j);
3509 		}
3510 	}
3511 
3512 	return (-1);
3513 }
3514 
3515 int
3516 ctl_set_mask(uint32_t *mask, uint32_t bit)
3517 {
3518 	uint32_t chunk, piece;
3519 
3520 	chunk = bit >> 5;
3521 	piece = bit % (sizeof(uint32_t) * 8);
3522 
3523 	if ((mask[chunk] & (1 << piece)) != 0)
3524 		return (-1);
3525 	else
3526 		mask[chunk] |= (1 << piece);
3527 
3528 	return (0);
3529 }
3530 
3531 int
3532 ctl_clear_mask(uint32_t *mask, uint32_t bit)
3533 {
3534 	uint32_t chunk, piece;
3535 
3536 	chunk = bit >> 5;
3537 	piece = bit % (sizeof(uint32_t) * 8);
3538 
3539 	if ((mask[chunk] & (1 << piece)) == 0)
3540 		return (-1);
3541 	else
3542 		mask[chunk] &= ~(1 << piece);
3543 
3544 	return (0);
3545 }
3546 
3547 int
3548 ctl_is_set(uint32_t *mask, uint32_t bit)
3549 {
3550 	uint32_t chunk, piece;
3551 
3552 	chunk = bit >> 5;
3553 	piece = bit % (sizeof(uint32_t) * 8);
3554 
3555 	if ((mask[chunk] & (1 << piece)) == 0)
3556 		return (0);
3557 	else
3558 		return (1);
3559 }
3560 
3561 #ifdef unused
3562 /*
3563  * The bus, target and lun are optional, they can be filled in later.
3564  * can_wait is used to determine whether we can wait on the malloc or not.
3565  */
3566 union ctl_io*
3567 ctl_malloc_io(ctl_io_type io_type, uint32_t targ_port, uint32_t targ_target,
3568 	      uint32_t targ_lun, int can_wait)
3569 {
3570 	union ctl_io *io;
3571 
3572 	if (can_wait)
3573 		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_WAITOK);
3574 	else
3575 		io = (union ctl_io *)malloc(sizeof(*io), M_CTL, M_NOWAIT);
3576 
3577 	if (io != NULL) {
3578 		io->io_hdr.io_type = io_type;
3579 		io->io_hdr.targ_port = targ_port;
3580 		/*
3581 		 * XXX KDM this needs to change/go away.  We need to move
3582 		 * to a preallocated pool of ctl_scsiio structures.
3583 		 */
3584 		io->io_hdr.nexus.targ_target.id = targ_target;
3585 		io->io_hdr.nexus.targ_lun = targ_lun;
3586 	}
3587 
3588 	return (io);
3589 }
3590 
3591 void
3592 ctl_kfree_io(union ctl_io *io)
3593 {
3594 	free(io, M_CTL);
3595 }
3596 #endif /* unused */
3597 
3598 /*
3599  * ctl_softc, pool_type, total_ctl_io are passed in.
3600  * npool is passed out.
3601  */
3602 int
3603 ctl_pool_create(struct ctl_softc *ctl_softc, ctl_pool_type pool_type,
3604 		uint32_t total_ctl_io, struct ctl_io_pool **npool)
3605 {
3606 	uint32_t i;
3607 	union ctl_io *cur_io, *next_io;
3608 	struct ctl_io_pool *pool;
3609 	int retval;
3610 
3611 	retval = 0;
3612 
3613 	pool = (struct ctl_io_pool *)malloc(sizeof(*pool), M_CTL,
3614 					    M_NOWAIT | M_ZERO);
3615 	if (pool == NULL) {
3616 		retval = ENOMEM;
3617 		goto bailout;
3618 	}
3619 
3620 	pool->type = pool_type;
3621 	pool->ctl_softc = ctl_softc;
3622 
3623 	mtx_lock(&ctl_softc->pool_lock);
3624 	pool->id = ctl_softc->cur_pool_id++;
3625 	mtx_unlock(&ctl_softc->pool_lock);
3626 
3627 	pool->flags = CTL_POOL_FLAG_NONE;
3628 	pool->refcount = 1;		/* Reference for validity. */
3629 	STAILQ_INIT(&pool->free_queue);
3630 
3631 	/*
3632 	 * XXX KDM other options here:
3633 	 * - allocate a page at a time
3634 	 * - allocate one big chunk of memory.
3635 	 * Page allocation might work well, but would take a little more
3636 	 * tracking.
3637 	 */
3638 	for (i = 0; i < total_ctl_io; i++) {
3639 		cur_io = (union ctl_io *)malloc(sizeof(*cur_io), M_CTLIO,
3640 						M_NOWAIT);
3641 		if (cur_io == NULL) {
3642 			retval = ENOMEM;
3643 			break;
3644 		}
3645 		cur_io->io_hdr.pool = pool;
3646 		STAILQ_INSERT_TAIL(&pool->free_queue, &cur_io->io_hdr, links);
3647 		pool->total_ctl_io++;
3648 		pool->free_ctl_io++;
3649 	}
3650 
3651 	if (retval != 0) {
3652 		for (cur_io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3653 		     cur_io != NULL; cur_io = next_io) {
3654 			next_io = (union ctl_io *)STAILQ_NEXT(&cur_io->io_hdr,
3655 							      links);
3656 			STAILQ_REMOVE(&pool->free_queue, &cur_io->io_hdr,
3657 				      ctl_io_hdr, links);
3658 			free(cur_io, M_CTLIO);
3659 		}
3660 
3661 		free(pool, M_CTL);
3662 		goto bailout;
3663 	}
3664 	mtx_lock(&ctl_softc->pool_lock);
3665 	ctl_softc->num_pools++;
3666 	STAILQ_INSERT_TAIL(&ctl_softc->io_pools, pool, links);
3667 	/*
3668 	 * Increment our usage count if this is an external consumer, so we
3669 	 * can't get unloaded until the external consumer (most likely a
3670 	 * FETD) unloads and frees his pool.
3671 	 *
3672 	 * XXX KDM will this increment the caller's module use count, or
3673 	 * mine?
3674 	 */
3675 #if 0
3676 	if ((pool_type != CTL_POOL_EMERGENCY)
3677 	 && (pool_type != CTL_POOL_INTERNAL)
3678 	 && (pool_type != CTL_POOL_4OTHERSC))
3679 		MOD_INC_USE_COUNT;
3680 #endif
3681 
3682 	mtx_unlock(&ctl_softc->pool_lock);
3683 
3684 	*npool = pool;
3685 
3686 bailout:
3687 
3688 	return (retval);
3689 }
3690 
3691 static int
3692 ctl_pool_acquire(struct ctl_io_pool *pool)
3693 {
3694 
3695 	mtx_assert(&pool->ctl_softc->pool_lock, MA_OWNED);
3696 
3697 	if (pool->flags & CTL_POOL_FLAG_INVALID)
3698 		return (EINVAL);
3699 
3700 	pool->refcount++;
3701 
3702 	return (0);
3703 }
3704 
3705 static void
3706 ctl_pool_release(struct ctl_io_pool *pool)
3707 {
3708 	struct ctl_softc *ctl_softc = pool->ctl_softc;
3709 	union ctl_io *io;
3710 
3711 	mtx_assert(&ctl_softc->pool_lock, MA_OWNED);
3712 
3713 	if (--pool->refcount != 0)
3714 		return;
3715 
3716 	while ((io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue)) != NULL) {
3717 		STAILQ_REMOVE(&pool->free_queue, &io->io_hdr, ctl_io_hdr,
3718 			      links);
3719 		free(io, M_CTLIO);
3720 	}
3721 
3722 	STAILQ_REMOVE(&ctl_softc->io_pools, pool, ctl_io_pool, links);
3723 	ctl_softc->num_pools--;
3724 
3725 	/*
3726 	 * XXX KDM will this decrement the caller's usage count or mine?
3727 	 */
3728 #if 0
3729 	if ((pool->type != CTL_POOL_EMERGENCY)
3730 	 && (pool->type != CTL_POOL_INTERNAL)
3731 	 && (pool->type != CTL_POOL_4OTHERSC))
3732 		MOD_DEC_USE_COUNT;
3733 #endif
3734 
3735 	free(pool, M_CTL);
3736 }
3737 
3738 void
3739 ctl_pool_free(struct ctl_io_pool *pool)
3740 {
3741 	struct ctl_softc *ctl_softc;
3742 
3743 	if (pool == NULL)
3744 		return;
3745 
3746 	ctl_softc = pool->ctl_softc;
3747 	mtx_lock(&ctl_softc->pool_lock);
3748 	pool->flags |= CTL_POOL_FLAG_INVALID;
3749 	ctl_pool_release(pool);
3750 	mtx_unlock(&ctl_softc->pool_lock);
3751 }
3752 
3753 /*
3754  * This routine does not block (except for spinlocks of course).
3755  * It tries to allocate a ctl_io union from the caller's pool as quickly as
3756  * possible.
3757  */
3758 union ctl_io *
3759 ctl_alloc_io(void *pool_ref)
3760 {
3761 	union ctl_io *io;
3762 	struct ctl_softc *ctl_softc;
3763 	struct ctl_io_pool *pool, *npool;
3764 	struct ctl_io_pool *emergency_pool;
3765 
3766 	pool = (struct ctl_io_pool *)pool_ref;
3767 
3768 	if (pool == NULL) {
3769 		printf("%s: pool is NULL\n", __func__);
3770 		return (NULL);
3771 	}
3772 
3773 	emergency_pool = NULL;
3774 
3775 	ctl_softc = pool->ctl_softc;
3776 
3777 	mtx_lock(&ctl_softc->pool_lock);
3778 	/*
3779 	 * First, try to get the io structure from the user's pool.
3780 	 */
3781 	if (ctl_pool_acquire(pool) == 0) {
3782 		io = (union ctl_io *)STAILQ_FIRST(&pool->free_queue);
3783 		if (io != NULL) {
3784 			STAILQ_REMOVE_HEAD(&pool->free_queue, links);
3785 			pool->total_allocated++;
3786 			pool->free_ctl_io--;
3787 			mtx_unlock(&ctl_softc->pool_lock);
3788 			return (io);
3789 		} else
3790 			ctl_pool_release(pool);
3791 	}
3792 	/*
3793 	 * If he doesn't have any io structures left, search for an
3794 	 * emergency pool and grab one from there.
3795 	 */
3796 	STAILQ_FOREACH(npool, &ctl_softc->io_pools, links) {
3797 		if (npool->type != CTL_POOL_EMERGENCY)
3798 			continue;
3799 
3800 		if (ctl_pool_acquire(npool) != 0)
3801 			continue;
3802 
3803 		emergency_pool = npool;
3804 
3805 		io = (union ctl_io *)STAILQ_FIRST(&npool->free_queue);
3806 		if (io != NULL) {
3807 			STAILQ_REMOVE_HEAD(&npool->free_queue, links);
3808 			npool->total_allocated++;
3809 			npool->free_ctl_io--;
3810 			mtx_unlock(&ctl_softc->pool_lock);
3811 			return (io);
3812 		} else
3813 			ctl_pool_release(npool);
3814 	}
3815 
3816 	/* Drop the spinlock before we malloc */
3817 	mtx_unlock(&ctl_softc->pool_lock);
3818 
3819 	/*
3820 	 * The emergency pool (if it exists) didn't have one, so try an
3821 	 * atomic (i.e. nonblocking) malloc and see if we get lucky.
3822 	 */
3823 	io = (union ctl_io *)malloc(sizeof(*io), M_CTLIO, M_NOWAIT);
3824 	if (io != NULL) {
3825 		/*
3826 		 * If the emergency pool exists but is empty, add this
3827 		 * ctl_io to its list when it gets freed.
3828 		 */
3829 		if (emergency_pool != NULL) {
3830 			mtx_lock(&ctl_softc->pool_lock);
3831 			if (ctl_pool_acquire(emergency_pool) == 0) {
3832 				io->io_hdr.pool = emergency_pool;
3833 				emergency_pool->total_ctl_io++;
3834 				/*
3835 				 * Need to bump this, otherwise
3836 				 * total_allocated and total_freed won't
3837 				 * match when we no longer have anything
3838 				 * outstanding.
3839 				 */
3840 				emergency_pool->total_allocated++;
3841 			}
3842 			mtx_unlock(&ctl_softc->pool_lock);
3843 		} else
3844 			io->io_hdr.pool = NULL;
3845 	}
3846 
3847 	return (io);
3848 }
3849 
3850 void
3851 ctl_free_io(union ctl_io *io)
3852 {
3853 	if (io == NULL)
3854 		return;
3855 
3856 	/*
3857 	 * If this ctl_io has a pool, return it to that pool.
3858 	 */
3859 	if (io->io_hdr.pool != NULL) {
3860 		struct ctl_io_pool *pool;
3861 
3862 		pool = (struct ctl_io_pool *)io->io_hdr.pool;
3863 		mtx_lock(&pool->ctl_softc->pool_lock);
3864 		io->io_hdr.io_type = 0xff;
3865 		STAILQ_INSERT_TAIL(&pool->free_queue, &io->io_hdr, links);
3866 		pool->total_freed++;
3867 		pool->free_ctl_io++;
3868 		ctl_pool_release(pool);
3869 		mtx_unlock(&pool->ctl_softc->pool_lock);
3870 	} else {
3871 		/*
3872 		 * Otherwise, just free it.  We probably malloced it and
3873 		 * the emergency pool wasn't available.
3874 		 */
3875 		free(io, M_CTLIO);
3876 	}
3877 
3878 }
3879 
3880 void
3881 ctl_zero_io(union ctl_io *io)
3882 {
3883 	void *pool_ref;
3884 
3885 	if (io == NULL)
3886 		return;
3887 
3888 	/*
3889 	 * May need to preserve linked list pointers at some point too.
3890 	 */
3891 	pool_ref = io->io_hdr.pool;
3892 
3893 	memset(io, 0, sizeof(*io));
3894 
3895 	io->io_hdr.pool = pool_ref;
3896 }
3897 
3898 /*
3899  * This routine is currently used for internal copies of ctl_ios that need
3900  * to persist for some reason after we've already returned status to the
3901  * FETD.  (Thus the flag set.)
3902  *
3903  * XXX XXX
3904  * Note that this makes a blind copy of all fields in the ctl_io, except
3905  * for the pool reference.  This includes any memory that has been
3906  * allocated!  That memory will no longer be valid after done has been
3907  * called, so this would be VERY DANGEROUS for command that actually does
3908  * any reads or writes.  Right now (11/7/2005), this is only used for immediate
3909  * start and stop commands, which don't transfer any data, so this is not a
3910  * problem.  If it is used for anything else, the caller would also need to
3911  * allocate data buffer space and this routine would need to be modified to
3912  * copy the data buffer(s) as well.
3913  */
3914 void
3915 ctl_copy_io(union ctl_io *src, union ctl_io *dest)
3916 {
3917 	void *pool_ref;
3918 
3919 	if ((src == NULL)
3920 	 || (dest == NULL))
3921 		return;
3922 
3923 	/*
3924 	 * May need to preserve linked list pointers at some point too.
3925 	 */
3926 	pool_ref = dest->io_hdr.pool;
3927 
3928 	memcpy(dest, src, ctl_min(sizeof(*src), sizeof(*dest)));
3929 
3930 	dest->io_hdr.pool = pool_ref;
3931 	/*
3932 	 * We need to know that this is an internal copy, and doesn't need
3933 	 * to get passed back to the FETD that allocated it.
3934 	 */
3935 	dest->io_hdr.flags |= CTL_FLAG_INT_COPY;
3936 }
3937 
3938 #ifdef NEEDTOPORT
3939 static void
3940 ctl_update_power_subpage(struct copan_power_subpage *page)
3941 {
3942 	int num_luns, num_partitions, config_type;
3943 	struct ctl_softc *softc;
3944 	cs_BOOL_t aor_present, shelf_50pct_power;
3945 	cs_raidset_personality_t rs_type;
3946 	int max_active_luns;
3947 
3948 	softc = control_softc;
3949 
3950 	/* subtract out the processor LUN */
3951 	num_luns = softc->num_luns - 1;
3952 	/*
3953 	 * Default to 7 LUNs active, which was the only number we allowed
3954 	 * in the past.
3955 	 */
3956 	max_active_luns = 7;
3957 
3958 	num_partitions = config_GetRsPartitionInfo();
3959 	config_type = config_GetConfigType();
3960 	shelf_50pct_power = config_GetShelfPowerMode();
3961 	aor_present = config_IsAorRsPresent();
3962 
3963 	rs_type = ddb_GetRsRaidType(1);
3964 	if ((rs_type != CS_RAIDSET_PERSONALITY_RAID5)
3965 	 && (rs_type != CS_RAIDSET_PERSONALITY_RAID1)) {
3966 		EPRINT(0, "Unsupported RS type %d!", rs_type);
3967 	}
3968 
3969 
3970 	page->total_luns = num_luns;
3971 
3972 	switch (config_type) {
3973 	case 40:
3974 		/*
3975 		 * In a 40 drive configuration, it doesn't matter what DC
3976 		 * cards we have, whether we have AOR enabled or not,
3977 		 * partitioning or not, or what type of RAIDset we have.
3978 		 * In that scenario, we can power up every LUN we present
3979 		 * to the user.
3980 		 */
3981 		max_active_luns = num_luns;
3982 
3983 		break;
3984 	case 64:
3985 		if (shelf_50pct_power == CS_FALSE) {
3986 			/* 25% power */
3987 			if (aor_present == CS_TRUE) {
3988 				if (rs_type ==
3989 				     CS_RAIDSET_PERSONALITY_RAID5) {
3990 					max_active_luns = 7;
3991 				} else if (rs_type ==
3992 					 CS_RAIDSET_PERSONALITY_RAID1){
3993 					max_active_luns = 14;
3994 				} else {
3995 					/* XXX KDM now what?? */
3996 				}
3997 			} else {
3998 				if (rs_type ==
3999 				     CS_RAIDSET_PERSONALITY_RAID5) {
4000 					max_active_luns = 8;
4001 				} else if (rs_type ==
4002 					 CS_RAIDSET_PERSONALITY_RAID1){
4003 					max_active_luns = 16;
4004 				} else {
4005 					/* XXX KDM now what?? */
4006 				}
4007 			}
4008 		} else {
4009 			/* 50% power */
4010 			/*
4011 			 * With 50% power in a 64 drive configuration, we
4012 			 * can power all LUNs we present.
4013 			 */
4014 			max_active_luns = num_luns;
4015 		}
4016 		break;
4017 	case 112:
4018 		if (shelf_50pct_power == CS_FALSE) {
4019 			/* 25% power */
4020 			if (aor_present == CS_TRUE) {
4021 				if (rs_type ==
4022 				     CS_RAIDSET_PERSONALITY_RAID5) {
4023 					max_active_luns = 7;
4024 				} else if (rs_type ==
4025 					 CS_RAIDSET_PERSONALITY_RAID1){
4026 					max_active_luns = 14;
4027 				} else {
4028 					/* XXX KDM now what?? */
4029 				}
4030 			} else {
4031 				if (rs_type ==
4032 				     CS_RAIDSET_PERSONALITY_RAID5) {
4033 					max_active_luns = 8;
4034 				} else if (rs_type ==
4035 					 CS_RAIDSET_PERSONALITY_RAID1){
4036 					max_active_luns = 16;
4037 				} else {
4038 					/* XXX KDM now what?? */
4039 				}
4040 			}
4041 		} else {
4042 			/* 50% power */
4043 			if (aor_present == CS_TRUE) {
4044 				if (rs_type ==
4045 				     CS_RAIDSET_PERSONALITY_RAID5) {
4046 					max_active_luns = 14;
4047 				} else if (rs_type ==
4048 					 CS_RAIDSET_PERSONALITY_RAID1){
4049 					/*
4050 					 * We're assuming here that disk
4051 					 * caching is enabled, and so we're
4052 					 * able to power up half of each
4053 					 * LUN, and cache all writes.
4054 					 */
4055 					max_active_luns = num_luns;
4056 				} else {
4057 					/* XXX KDM now what?? */
4058 				}
4059 			} else {
4060 				if (rs_type ==
4061 				     CS_RAIDSET_PERSONALITY_RAID5) {
4062 					max_active_luns = 15;
4063 				} else if (rs_type ==
4064 					 CS_RAIDSET_PERSONALITY_RAID1){
4065 					max_active_luns = 30;
4066 				} else {
4067 					/* XXX KDM now what?? */
4068 				}
4069 			}
4070 		}
4071 		break;
4072 	default:
4073 		/*
4074 		 * In this case, we have an unknown configuration, so we
4075 		 * just use the default from above.
4076 		 */
4077 		break;
4078 	}
4079 
4080 	page->max_active_luns = max_active_luns;
4081 #if 0
4082 	printk("%s: total_luns = %d, max_active_luns = %d\n", __func__,
4083 	       page->total_luns, page->max_active_luns);
4084 #endif
4085 }
4086 #endif /* NEEDTOPORT */
4087 
4088 /*
4089  * This routine could be used in the future to load default and/or saved
4090  * mode page parameters for a particuar lun.
4091  */
4092 static int
4093 ctl_init_page_index(struct ctl_lun *lun)
4094 {
4095 	int i;
4096 	struct ctl_page_index *page_index;
4097 	struct ctl_softc *softc;
4098 	const char *value;
4099 
4100 	memcpy(&lun->mode_pages.index, page_index_template,
4101 	       sizeof(page_index_template));
4102 
4103 	softc = lun->ctl_softc;
4104 
4105 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
4106 
4107 		page_index = &lun->mode_pages.index[i];
4108 		/*
4109 		 * If this is a disk-only mode page, there's no point in
4110 		 * setting it up.  For some pages, we have to have some
4111 		 * basic information about the disk in order to calculate the
4112 		 * mode page data.
4113 		 */
4114 		if ((lun->be_lun->lun_type != T_DIRECT)
4115 		 && (page_index->page_flags & CTL_PAGE_FLAG_DISK_ONLY))
4116 			continue;
4117 
4118 		switch (page_index->page_code & SMPH_PC_MASK) {
4119 		case SMS_FORMAT_DEVICE_PAGE: {
4120 			struct scsi_format_page *format_page;
4121 
4122 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4123 				panic("subpage is incorrect!");
4124 
4125 			/*
4126 			 * Sectors per track are set above.  Bytes per
4127 			 * sector need to be set here on a per-LUN basis.
4128 			 */
4129 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_CURRENT],
4130 			       &format_page_default,
4131 			       sizeof(format_page_default));
4132 			memcpy(&lun->mode_pages.format_page[
4133 			       CTL_PAGE_CHANGEABLE], &format_page_changeable,
4134 			       sizeof(format_page_changeable));
4135 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_DEFAULT],
4136 			       &format_page_default,
4137 			       sizeof(format_page_default));
4138 			memcpy(&lun->mode_pages.format_page[CTL_PAGE_SAVED],
4139 			       &format_page_default,
4140 			       sizeof(format_page_default));
4141 
4142 			format_page = &lun->mode_pages.format_page[
4143 				CTL_PAGE_CURRENT];
4144 			scsi_ulto2b(lun->be_lun->blocksize,
4145 				    format_page->bytes_per_sector);
4146 
4147 			format_page = &lun->mode_pages.format_page[
4148 				CTL_PAGE_DEFAULT];
4149 			scsi_ulto2b(lun->be_lun->blocksize,
4150 				    format_page->bytes_per_sector);
4151 
4152 			format_page = &lun->mode_pages.format_page[
4153 				CTL_PAGE_SAVED];
4154 			scsi_ulto2b(lun->be_lun->blocksize,
4155 				    format_page->bytes_per_sector);
4156 
4157 			page_index->page_data =
4158 				(uint8_t *)lun->mode_pages.format_page;
4159 			break;
4160 		}
4161 		case SMS_RIGID_DISK_PAGE: {
4162 			struct scsi_rigid_disk_page *rigid_disk_page;
4163 			uint32_t sectors_per_cylinder;
4164 			uint64_t cylinders;
4165 #ifndef	__XSCALE__
4166 			int shift;
4167 #endif /* !__XSCALE__ */
4168 
4169 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4170 				panic("invalid subpage value %d",
4171 				      page_index->subpage);
4172 
4173 			/*
4174 			 * Rotation rate and sectors per track are set
4175 			 * above.  We calculate the cylinders here based on
4176 			 * capacity.  Due to the number of heads and
4177 			 * sectors per track we're using, smaller arrays
4178 			 * may turn out to have 0 cylinders.  Linux and
4179 			 * FreeBSD don't pay attention to these mode pages
4180 			 * to figure out capacity, but Solaris does.  It
4181 			 * seems to deal with 0 cylinders just fine, and
4182 			 * works out a fake geometry based on the capacity.
4183 			 */
4184 			memcpy(&lun->mode_pages.rigid_disk_page[
4185 			       CTL_PAGE_CURRENT], &rigid_disk_page_default,
4186 			       sizeof(rigid_disk_page_default));
4187 			memcpy(&lun->mode_pages.rigid_disk_page[
4188 			       CTL_PAGE_CHANGEABLE],&rigid_disk_page_changeable,
4189 			       sizeof(rigid_disk_page_changeable));
4190 			memcpy(&lun->mode_pages.rigid_disk_page[
4191 			       CTL_PAGE_DEFAULT], &rigid_disk_page_default,
4192 			       sizeof(rigid_disk_page_default));
4193 			memcpy(&lun->mode_pages.rigid_disk_page[
4194 			       CTL_PAGE_SAVED], &rigid_disk_page_default,
4195 			       sizeof(rigid_disk_page_default));
4196 
4197 			sectors_per_cylinder = CTL_DEFAULT_SECTORS_PER_TRACK *
4198 				CTL_DEFAULT_HEADS;
4199 
4200 			/*
4201 			 * The divide method here will be more accurate,
4202 			 * probably, but results in floating point being
4203 			 * used in the kernel on i386 (__udivdi3()).  On the
4204 			 * XScale, though, __udivdi3() is implemented in
4205 			 * software.
4206 			 *
4207 			 * The shift method for cylinder calculation is
4208 			 * accurate if sectors_per_cylinder is a power of
4209 			 * 2.  Otherwise it might be slightly off -- you
4210 			 * might have a bit of a truncation problem.
4211 			 */
4212 #ifdef	__XSCALE__
4213 			cylinders = (lun->be_lun->maxlba + 1) /
4214 				sectors_per_cylinder;
4215 #else
4216 			for (shift = 31; shift > 0; shift--) {
4217 				if (sectors_per_cylinder & (1 << shift))
4218 					break;
4219 			}
4220 			cylinders = (lun->be_lun->maxlba + 1) >> shift;
4221 #endif
4222 
4223 			/*
4224 			 * We've basically got 3 bytes, or 24 bits for the
4225 			 * cylinder size in the mode page.  If we're over,
4226 			 * just round down to 2^24.
4227 			 */
4228 			if (cylinders > 0xffffff)
4229 				cylinders = 0xffffff;
4230 
4231 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4232 				CTL_PAGE_CURRENT];
4233 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4234 
4235 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4236 				CTL_PAGE_DEFAULT];
4237 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4238 
4239 			rigid_disk_page = &lun->mode_pages.rigid_disk_page[
4240 				CTL_PAGE_SAVED];
4241 			scsi_ulto3b(cylinders, rigid_disk_page->cylinders);
4242 
4243 			page_index->page_data =
4244 				(uint8_t *)lun->mode_pages.rigid_disk_page;
4245 			break;
4246 		}
4247 		case SMS_CACHING_PAGE: {
4248 			struct scsi_caching_page *caching_page;
4249 
4250 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4251 				panic("invalid subpage value %d",
4252 				      page_index->subpage);
4253 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_DEFAULT],
4254 			       &caching_page_default,
4255 			       sizeof(caching_page_default));
4256 			memcpy(&lun->mode_pages.caching_page[
4257 			       CTL_PAGE_CHANGEABLE], &caching_page_changeable,
4258 			       sizeof(caching_page_changeable));
4259 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4260 			       &caching_page_default,
4261 			       sizeof(caching_page_default));
4262 			caching_page = &lun->mode_pages.caching_page[
4263 			    CTL_PAGE_SAVED];
4264 			value = ctl_get_opt(&lun->be_lun->options, "writecache");
4265 			if (value != NULL && strcmp(value, "off") == 0)
4266 				caching_page->flags1 &= ~SCP_WCE;
4267 			value = ctl_get_opt(&lun->be_lun->options, "readcache");
4268 			if (value != NULL && strcmp(value, "off") == 0)
4269 				caching_page->flags1 |= SCP_RCD;
4270 			memcpy(&lun->mode_pages.caching_page[CTL_PAGE_CURRENT],
4271 			       &lun->mode_pages.caching_page[CTL_PAGE_SAVED],
4272 			       sizeof(caching_page_default));
4273 			page_index->page_data =
4274 				(uint8_t *)lun->mode_pages.caching_page;
4275 			break;
4276 		}
4277 		case SMS_CONTROL_MODE_PAGE: {
4278 			struct scsi_control_page *control_page;
4279 
4280 			if (page_index->subpage != SMS_SUBPAGE_PAGE_0)
4281 				panic("invalid subpage value %d",
4282 				      page_index->subpage);
4283 
4284 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_DEFAULT],
4285 			       &control_page_default,
4286 			       sizeof(control_page_default));
4287 			memcpy(&lun->mode_pages.control_page[
4288 			       CTL_PAGE_CHANGEABLE], &control_page_changeable,
4289 			       sizeof(control_page_changeable));
4290 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_SAVED],
4291 			       &control_page_default,
4292 			       sizeof(control_page_default));
4293 			control_page = &lun->mode_pages.control_page[
4294 			    CTL_PAGE_SAVED];
4295 			value = ctl_get_opt(&lun->be_lun->options, "reordering");
4296 			if (value != NULL && strcmp(value, "unrestricted") == 0) {
4297 				control_page->queue_flags &= ~SCP_QUEUE_ALG_MASK;
4298 				control_page->queue_flags |= SCP_QUEUE_ALG_UNRESTRICTED;
4299 			}
4300 			memcpy(&lun->mode_pages.control_page[CTL_PAGE_CURRENT],
4301 			       &lun->mode_pages.control_page[CTL_PAGE_SAVED],
4302 			       sizeof(control_page_default));
4303 			page_index->page_data =
4304 				(uint8_t *)lun->mode_pages.control_page;
4305 			break;
4306 
4307 		}
4308 		case SMS_VENDOR_SPECIFIC_PAGE:{
4309 			switch (page_index->subpage) {
4310 			case PWR_SUBPAGE_CODE: {
4311 				struct copan_power_subpage *current_page,
4312 							   *saved_page;
4313 
4314 				memcpy(&lun->mode_pages.power_subpage[
4315 				       CTL_PAGE_CURRENT],
4316 				       &power_page_default,
4317 				       sizeof(power_page_default));
4318 				memcpy(&lun->mode_pages.power_subpage[
4319 				       CTL_PAGE_CHANGEABLE],
4320 				       &power_page_changeable,
4321 				       sizeof(power_page_changeable));
4322 				memcpy(&lun->mode_pages.power_subpage[
4323 				       CTL_PAGE_DEFAULT],
4324 				       &power_page_default,
4325 				       sizeof(power_page_default));
4326 				memcpy(&lun->mode_pages.power_subpage[
4327 				       CTL_PAGE_SAVED],
4328 				       &power_page_default,
4329 				       sizeof(power_page_default));
4330 				page_index->page_data =
4331 				    (uint8_t *)lun->mode_pages.power_subpage;
4332 
4333 				current_page = (struct copan_power_subpage *)
4334 					(page_index->page_data +
4335 					 (page_index->page_len *
4336 					  CTL_PAGE_CURRENT));
4337 			        saved_page = (struct copan_power_subpage *)
4338 				        (page_index->page_data +
4339 					 (page_index->page_len *
4340 					  CTL_PAGE_SAVED));
4341 				break;
4342 			}
4343 			case APS_SUBPAGE_CODE: {
4344 				struct copan_aps_subpage *current_page,
4345 							 *saved_page;
4346 
4347 				// This gets set multiple times but
4348 				// it should always be the same. It's
4349 				// only done during init so who cares.
4350 				index_to_aps_page = i;
4351 
4352 				memcpy(&lun->mode_pages.aps_subpage[
4353 				       CTL_PAGE_CURRENT],
4354 				       &aps_page_default,
4355 				       sizeof(aps_page_default));
4356 				memcpy(&lun->mode_pages.aps_subpage[
4357 				       CTL_PAGE_CHANGEABLE],
4358 				       &aps_page_changeable,
4359 				       sizeof(aps_page_changeable));
4360 				memcpy(&lun->mode_pages.aps_subpage[
4361 				       CTL_PAGE_DEFAULT],
4362 				       &aps_page_default,
4363 				       sizeof(aps_page_default));
4364 				memcpy(&lun->mode_pages.aps_subpage[
4365 				       CTL_PAGE_SAVED],
4366 				       &aps_page_default,
4367 				       sizeof(aps_page_default));
4368 				page_index->page_data =
4369 					(uint8_t *)lun->mode_pages.aps_subpage;
4370 
4371 				current_page = (struct copan_aps_subpage *)
4372 					(page_index->page_data +
4373 					 (page_index->page_len *
4374 					  CTL_PAGE_CURRENT));
4375 				saved_page = (struct copan_aps_subpage *)
4376 					(page_index->page_data +
4377 					 (page_index->page_len *
4378 					  CTL_PAGE_SAVED));
4379 				break;
4380 			}
4381 			case DBGCNF_SUBPAGE_CODE: {
4382 				struct copan_debugconf_subpage *current_page,
4383 							       *saved_page;
4384 
4385 				memcpy(&lun->mode_pages.debugconf_subpage[
4386 				       CTL_PAGE_CURRENT],
4387 				       &debugconf_page_default,
4388 				       sizeof(debugconf_page_default));
4389 				memcpy(&lun->mode_pages.debugconf_subpage[
4390 				       CTL_PAGE_CHANGEABLE],
4391 				       &debugconf_page_changeable,
4392 				       sizeof(debugconf_page_changeable));
4393 				memcpy(&lun->mode_pages.debugconf_subpage[
4394 				       CTL_PAGE_DEFAULT],
4395 				       &debugconf_page_default,
4396 				       sizeof(debugconf_page_default));
4397 				memcpy(&lun->mode_pages.debugconf_subpage[
4398 				       CTL_PAGE_SAVED],
4399 				       &debugconf_page_default,
4400 				       sizeof(debugconf_page_default));
4401 				page_index->page_data =
4402 					(uint8_t *)lun->mode_pages.debugconf_subpage;
4403 
4404 				current_page = (struct copan_debugconf_subpage *)
4405 					(page_index->page_data +
4406 					 (page_index->page_len *
4407 					  CTL_PAGE_CURRENT));
4408 				saved_page = (struct copan_debugconf_subpage *)
4409 					(page_index->page_data +
4410 					 (page_index->page_len *
4411 					  CTL_PAGE_SAVED));
4412 				break;
4413 			}
4414 			default:
4415 				panic("invalid subpage value %d",
4416 				      page_index->subpage);
4417 				break;
4418 			}
4419    			break;
4420 		}
4421 		default:
4422 			panic("invalid page value %d",
4423 			      page_index->page_code & SMPH_PC_MASK);
4424 			break;
4425     	}
4426 	}
4427 
4428 	return (CTL_RETVAL_COMPLETE);
4429 }
4430 
4431 /*
4432  * LUN allocation.
4433  *
4434  * Requirements:
4435  * - caller allocates and zeros LUN storage, or passes in a NULL LUN if he
4436  *   wants us to allocate the LUN and he can block.
4437  * - ctl_softc is always set
4438  * - be_lun is set if the LUN has a backend (needed for disk LUNs)
4439  *
4440  * Returns 0 for success, non-zero (errno) for failure.
4441  */
4442 static int
4443 ctl_alloc_lun(struct ctl_softc *ctl_softc, struct ctl_lun *ctl_lun,
4444 	      struct ctl_be_lun *const be_lun, struct ctl_id target_id)
4445 {
4446 	struct ctl_lun *nlun, *lun;
4447 	struct ctl_port *port;
4448 	struct scsi_vpd_id_descriptor *desc;
4449 	struct scsi_vpd_id_t10 *t10id;
4450 	const char *eui, *naa, *scsiname, *vendor, *value;
4451 	int lun_number, i, lun_malloced;
4452 	int devidlen, idlen1, idlen2 = 0, len;
4453 
4454 	if (be_lun == NULL)
4455 		return (EINVAL);
4456 
4457 	/*
4458 	 * We currently only support Direct Access or Processor LUN types.
4459 	 */
4460 	switch (be_lun->lun_type) {
4461 	case T_DIRECT:
4462 		break;
4463 	case T_PROCESSOR:
4464 		break;
4465 	case T_SEQUENTIAL:
4466 	case T_CHANGER:
4467 	default:
4468 		be_lun->lun_config_status(be_lun->be_lun,
4469 					  CTL_LUN_CONFIG_FAILURE);
4470 		break;
4471 	}
4472 	if (ctl_lun == NULL) {
4473 		lun = malloc(sizeof(*lun), M_CTL, M_WAITOK);
4474 		lun_malloced = 1;
4475 	} else {
4476 		lun_malloced = 0;
4477 		lun = ctl_lun;
4478 	}
4479 
4480 	memset(lun, 0, sizeof(*lun));
4481 	if (lun_malloced)
4482 		lun->flags = CTL_LUN_MALLOCED;
4483 
4484 	/* Generate LUN ID. */
4485 	devidlen = max(CTL_DEVID_MIN_LEN,
4486 	    strnlen(be_lun->device_id, CTL_DEVID_LEN));
4487 	idlen1 = sizeof(*t10id) + devidlen;
4488 	len = sizeof(struct scsi_vpd_id_descriptor) + idlen1;
4489 	scsiname = ctl_get_opt(&be_lun->options, "scsiname");
4490 	if (scsiname != NULL) {
4491 		idlen2 = roundup2(strlen(scsiname) + 1, 4);
4492 		len += sizeof(struct scsi_vpd_id_descriptor) + idlen2;
4493 	}
4494 	eui = ctl_get_opt(&be_lun->options, "eui");
4495 	if (eui != NULL) {
4496 		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4497 	}
4498 	naa = ctl_get_opt(&be_lun->options, "naa");
4499 	if (naa != NULL) {
4500 		len += sizeof(struct scsi_vpd_id_descriptor) + 8;
4501 	}
4502 	lun->lun_devid = malloc(sizeof(struct ctl_devid) + len,
4503 	    M_CTL, M_WAITOK | M_ZERO);
4504 	lun->lun_devid->len = len;
4505 	desc = (struct scsi_vpd_id_descriptor *)lun->lun_devid->data;
4506 	desc->proto_codeset = SVPD_ID_CODESET_ASCII;
4507 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN | SVPD_ID_TYPE_T10;
4508 	desc->length = idlen1;
4509 	t10id = (struct scsi_vpd_id_t10 *)&desc->identifier[0];
4510 	memset(t10id->vendor, ' ', sizeof(t10id->vendor));
4511 	if ((vendor = ctl_get_opt(&be_lun->options, "vendor")) == NULL) {
4512 		strncpy((char *)t10id->vendor, CTL_VENDOR, sizeof(t10id->vendor));
4513 	} else {
4514 		strncpy(t10id->vendor, vendor,
4515 		    min(sizeof(t10id->vendor), strlen(vendor)));
4516 	}
4517 	strncpy((char *)t10id->vendor_spec_id,
4518 	    (char *)be_lun->device_id, devidlen);
4519 	if (scsiname != NULL) {
4520 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4521 		    desc->length);
4522 		desc->proto_codeset = SVPD_ID_CODESET_UTF8;
4523 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4524 		    SVPD_ID_TYPE_SCSI_NAME;
4525 		desc->length = idlen2;
4526 		strlcpy(desc->identifier, scsiname, idlen2);
4527 	}
4528 	if (eui != NULL) {
4529 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4530 		    desc->length);
4531 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4532 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4533 		    SVPD_ID_TYPE_EUI64;
4534 		desc->length = 8;
4535 		scsi_u64to8b(strtouq(eui, NULL, 0), desc->identifier);
4536 	}
4537 	if (naa != NULL) {
4538 		desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
4539 		    desc->length);
4540 		desc->proto_codeset = SVPD_ID_CODESET_BINARY;
4541 		desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_LUN |
4542 		    SVPD_ID_TYPE_NAA;
4543 		desc->length = 8;
4544 		scsi_u64to8b(strtouq(naa, NULL, 0), desc->identifier);
4545 	}
4546 
4547 	mtx_lock(&ctl_softc->ctl_lock);
4548 	/*
4549 	 * See if the caller requested a particular LUN number.  If so, see
4550 	 * if it is available.  Otherwise, allocate the first available LUN.
4551 	 */
4552 	if (be_lun->flags & CTL_LUN_FLAG_ID_REQ) {
4553 		if ((be_lun->req_lun_id > (CTL_MAX_LUNS - 1))
4554 		 || (ctl_is_set(ctl_softc->ctl_lun_mask, be_lun->req_lun_id))) {
4555 			mtx_unlock(&ctl_softc->ctl_lock);
4556 			if (be_lun->req_lun_id > (CTL_MAX_LUNS - 1)) {
4557 				printf("ctl: requested LUN ID %d is higher "
4558 				       "than CTL_MAX_LUNS - 1 (%d)\n",
4559 				       be_lun->req_lun_id, CTL_MAX_LUNS - 1);
4560 			} else {
4561 				/*
4562 				 * XXX KDM return an error, or just assign
4563 				 * another LUN ID in this case??
4564 				 */
4565 				printf("ctl: requested LUN ID %d is already "
4566 				       "in use\n", be_lun->req_lun_id);
4567 			}
4568 			if (lun->flags & CTL_LUN_MALLOCED)
4569 				free(lun, M_CTL);
4570 			be_lun->lun_config_status(be_lun->be_lun,
4571 						  CTL_LUN_CONFIG_FAILURE);
4572 			return (ENOSPC);
4573 		}
4574 		lun_number = be_lun->req_lun_id;
4575 	} else {
4576 		lun_number = ctl_ffz(ctl_softc->ctl_lun_mask, CTL_MAX_LUNS);
4577 		if (lun_number == -1) {
4578 			mtx_unlock(&ctl_softc->ctl_lock);
4579 			printf("ctl: can't allocate LUN on target %ju, out of "
4580 			       "LUNs\n", (uintmax_t)target_id.id);
4581 			if (lun->flags & CTL_LUN_MALLOCED)
4582 				free(lun, M_CTL);
4583 			be_lun->lun_config_status(be_lun->be_lun,
4584 						  CTL_LUN_CONFIG_FAILURE);
4585 			return (ENOSPC);
4586 		}
4587 	}
4588 	ctl_set_mask(ctl_softc->ctl_lun_mask, lun_number);
4589 
4590 	mtx_init(&lun->lun_lock, "CTL LUN", NULL, MTX_DEF);
4591 	lun->target = target_id;
4592 	lun->lun = lun_number;
4593 	lun->be_lun = be_lun;
4594 	/*
4595 	 * The processor LUN is always enabled.  Disk LUNs come on line
4596 	 * disabled, and must be enabled by the backend.
4597 	 */
4598 	lun->flags |= CTL_LUN_DISABLED;
4599 	lun->backend = be_lun->be;
4600 	be_lun->ctl_lun = lun;
4601 	be_lun->lun_id = lun_number;
4602 	atomic_add_int(&be_lun->be->num_luns, 1);
4603 	if (be_lun->flags & CTL_LUN_FLAG_POWERED_OFF)
4604 		lun->flags |= CTL_LUN_STOPPED;
4605 
4606 	if (be_lun->flags & CTL_LUN_FLAG_INOPERABLE)
4607 		lun->flags |= CTL_LUN_INOPERABLE;
4608 
4609 	if (be_lun->flags & CTL_LUN_FLAG_PRIMARY)
4610 		lun->flags |= CTL_LUN_PRIMARY_SC;
4611 
4612 	value = ctl_get_opt(&be_lun->options, "readonly");
4613 	if (value != NULL && strcmp(value, "on") == 0)
4614 		lun->flags |= CTL_LUN_READONLY;
4615 
4616 	lun->ctl_softc = ctl_softc;
4617 	TAILQ_INIT(&lun->ooa_queue);
4618 	TAILQ_INIT(&lun->blocked_queue);
4619 	STAILQ_INIT(&lun->error_list);
4620 	ctl_tpc_lun_init(lun);
4621 
4622 	/*
4623 	 * Initialize the mode page index.
4624 	 */
4625 	ctl_init_page_index(lun);
4626 
4627 	/*
4628 	 * Set the poweron UA for all initiators on this LUN only.
4629 	 */
4630 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
4631 		lun->pending_ua[i] = CTL_UA_POWERON;
4632 
4633 	/*
4634 	 * Now, before we insert this lun on the lun list, set the lun
4635 	 * inventory changed UA for all other luns.
4636 	 */
4637 	STAILQ_FOREACH(nlun, &ctl_softc->lun_list, links) {
4638 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4639 			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4640 		}
4641 	}
4642 
4643 	STAILQ_INSERT_TAIL(&ctl_softc->lun_list, lun, links);
4644 
4645 	ctl_softc->ctl_luns[lun_number] = lun;
4646 
4647 	ctl_softc->num_luns++;
4648 
4649 	/* Setup statistics gathering */
4650 	lun->stats.device_type = be_lun->lun_type;
4651 	lun->stats.lun_number = lun_number;
4652 	if (lun->stats.device_type == T_DIRECT)
4653 		lun->stats.blocksize = be_lun->blocksize;
4654 	else
4655 		lun->stats.flags = CTL_LUN_STATS_NO_BLOCKSIZE;
4656 	for (i = 0;i < CTL_MAX_PORTS;i++)
4657 		lun->stats.ports[i].targ_port = i;
4658 
4659 	mtx_unlock(&ctl_softc->ctl_lock);
4660 
4661 	lun->be_lun->lun_config_status(lun->be_lun->be_lun, CTL_LUN_CONFIG_OK);
4662 
4663 	/*
4664 	 * Run through each registered FETD and bring it online if it isn't
4665 	 * already.  Enable the target ID if it hasn't been enabled, and
4666 	 * enable this particular LUN.
4667 	 */
4668 	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4669 		int retval;
4670 
4671 		retval = port->lun_enable(port->targ_lun_arg, target_id,lun_number);
4672 		if (retval != 0) {
4673 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4674 			       "%d for lun_enable on target %ju lun %d\n",
4675 			       port->port_name, port->targ_port, retval,
4676 			       (uintmax_t)target_id.id, lun_number);
4677 		} else
4678 			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4679 	}
4680 	return (0);
4681 }
4682 
4683 /*
4684  * Delete a LUN.
4685  * Assumptions:
4686  * - LUN has already been marked invalid and any pending I/O has been taken
4687  *   care of.
4688  */
4689 static int
4690 ctl_free_lun(struct ctl_lun *lun)
4691 {
4692 	struct ctl_softc *softc;
4693 #if 0
4694 	struct ctl_port *port;
4695 #endif
4696 	struct ctl_lun *nlun;
4697 	int i;
4698 
4699 	softc = lun->ctl_softc;
4700 
4701 	mtx_assert(&softc->ctl_lock, MA_OWNED);
4702 
4703 	STAILQ_REMOVE(&softc->lun_list, lun, ctl_lun, links);
4704 
4705 	ctl_clear_mask(softc->ctl_lun_mask, lun->lun);
4706 
4707 	softc->ctl_luns[lun->lun] = NULL;
4708 
4709 	if (!TAILQ_EMPTY(&lun->ooa_queue))
4710 		panic("Freeing a LUN %p with outstanding I/O!!\n", lun);
4711 
4712 	softc->num_luns--;
4713 
4714 	/*
4715 	 * XXX KDM this scheme only works for a single target/multiple LUN
4716 	 * setup.  It needs to be revamped for a multiple target scheme.
4717 	 *
4718 	 * XXX KDM this results in port->lun_disable() getting called twice,
4719 	 * once when ctl_disable_lun() is called, and a second time here.
4720 	 * We really need to re-think the LUN disable semantics.  There
4721 	 * should probably be several steps/levels to LUN removal:
4722 	 *  - disable
4723 	 *  - invalidate
4724 	 *  - free
4725  	 *
4726 	 * Right now we only have a disable method when communicating to
4727 	 * the front end ports, at least for individual LUNs.
4728 	 */
4729 #if 0
4730 	STAILQ_FOREACH(port, &softc->port_list, links) {
4731 		int retval;
4732 
4733 		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4734 					 lun->lun);
4735 		if (retval != 0) {
4736 			printf("ctl_free_lun: FETD %s port %d returned error "
4737 			       "%d for lun_disable on target %ju lun %jd\n",
4738 			       port->port_name, port->targ_port, retval,
4739 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4740 		}
4741 
4742 		if (STAILQ_FIRST(&softc->lun_list) == NULL) {
4743 			port->status &= ~CTL_PORT_STATUS_LUN_ONLINE;
4744 
4745 			retval = port->targ_disable(port->targ_lun_arg,lun->target);
4746 			if (retval != 0) {
4747 				printf("ctl_free_lun: FETD %s port %d "
4748 				       "returned error %d for targ_disable on "
4749 				       "target %ju\n", port->port_name,
4750 				       port->targ_port, retval,
4751 				       (uintmax_t)lun->target.id);
4752 			} else
4753 				port->status &= ~CTL_PORT_STATUS_TARG_ONLINE;
4754 
4755 			if ((port->status & CTL_PORT_STATUS_TARG_ONLINE) != 0)
4756 				continue;
4757 
4758 #if 0
4759 			port->port_offline(port->onoff_arg);
4760 			port->status &= ~CTL_PORT_STATUS_ONLINE;
4761 #endif
4762 		}
4763 	}
4764 #endif
4765 
4766 	/*
4767 	 * Tell the backend to free resources, if this LUN has a backend.
4768 	 */
4769 	atomic_subtract_int(&lun->be_lun->be->num_luns, 1);
4770 	lun->be_lun->lun_shutdown(lun->be_lun->be_lun);
4771 
4772 	ctl_tpc_lun_shutdown(lun);
4773 	mtx_destroy(&lun->lun_lock);
4774 	free(lun->lun_devid, M_CTL);
4775 	if (lun->flags & CTL_LUN_MALLOCED)
4776 		free(lun, M_CTL);
4777 
4778 	STAILQ_FOREACH(nlun, &softc->lun_list, links) {
4779 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
4780 			nlun->pending_ua[i] |= CTL_UA_LUN_CHANGE;
4781 		}
4782 	}
4783 
4784 	return (0);
4785 }
4786 
4787 static void
4788 ctl_create_lun(struct ctl_be_lun *be_lun)
4789 {
4790 	struct ctl_softc *ctl_softc;
4791 
4792 	ctl_softc = control_softc;
4793 
4794 	/*
4795 	 * ctl_alloc_lun() should handle all potential failure cases.
4796 	 */
4797 	ctl_alloc_lun(ctl_softc, NULL, be_lun, ctl_softc->target);
4798 }
4799 
4800 int
4801 ctl_add_lun(struct ctl_be_lun *be_lun)
4802 {
4803 	struct ctl_softc *ctl_softc = control_softc;
4804 
4805 	mtx_lock(&ctl_softc->ctl_lock);
4806 	STAILQ_INSERT_TAIL(&ctl_softc->pending_lun_queue, be_lun, links);
4807 	mtx_unlock(&ctl_softc->ctl_lock);
4808 	wakeup(&ctl_softc->pending_lun_queue);
4809 
4810 	return (0);
4811 }
4812 
4813 int
4814 ctl_enable_lun(struct ctl_be_lun *be_lun)
4815 {
4816 	struct ctl_softc *ctl_softc;
4817 	struct ctl_port *port, *nport;
4818 	struct ctl_lun *lun;
4819 	int retval;
4820 
4821 	ctl_softc = control_softc;
4822 
4823 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4824 
4825 	mtx_lock(&ctl_softc->ctl_lock);
4826 	mtx_lock(&lun->lun_lock);
4827 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
4828 		/*
4829 		 * eh?  Why did we get called if the LUN is already
4830 		 * enabled?
4831 		 */
4832 		mtx_unlock(&lun->lun_lock);
4833 		mtx_unlock(&ctl_softc->ctl_lock);
4834 		return (0);
4835 	}
4836 	lun->flags &= ~CTL_LUN_DISABLED;
4837 	mtx_unlock(&lun->lun_lock);
4838 
4839 	for (port = STAILQ_FIRST(&ctl_softc->port_list); port != NULL; port = nport) {
4840 		nport = STAILQ_NEXT(port, links);
4841 
4842 		/*
4843 		 * Drop the lock while we call the FETD's enable routine.
4844 		 * This can lead to a callback into CTL (at least in the
4845 		 * case of the internal initiator frontend.
4846 		 */
4847 		mtx_unlock(&ctl_softc->ctl_lock);
4848 		retval = port->lun_enable(port->targ_lun_arg, lun->target,lun->lun);
4849 		mtx_lock(&ctl_softc->ctl_lock);
4850 		if (retval != 0) {
4851 			printf("%s: FETD %s port %d returned error "
4852 			       "%d for lun_enable on target %ju lun %jd\n",
4853 			       __func__, port->port_name, port->targ_port, retval,
4854 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4855 		}
4856 #if 0
4857 		 else {
4858             /* NOTE:  TODO:  why does lun enable affect port status? */
4859 			port->status |= CTL_PORT_STATUS_LUN_ONLINE;
4860 		}
4861 #endif
4862 	}
4863 
4864 	mtx_unlock(&ctl_softc->ctl_lock);
4865 
4866 	return (0);
4867 }
4868 
4869 int
4870 ctl_disable_lun(struct ctl_be_lun *be_lun)
4871 {
4872 	struct ctl_softc *ctl_softc;
4873 	struct ctl_port *port;
4874 	struct ctl_lun *lun;
4875 	int retval;
4876 
4877 	ctl_softc = control_softc;
4878 
4879 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4880 
4881 	mtx_lock(&ctl_softc->ctl_lock);
4882 	mtx_lock(&lun->lun_lock);
4883 	if (lun->flags & CTL_LUN_DISABLED) {
4884 		mtx_unlock(&lun->lun_lock);
4885 		mtx_unlock(&ctl_softc->ctl_lock);
4886 		return (0);
4887 	}
4888 	lun->flags |= CTL_LUN_DISABLED;
4889 	mtx_unlock(&lun->lun_lock);
4890 
4891 	STAILQ_FOREACH(port, &ctl_softc->port_list, links) {
4892 		mtx_unlock(&ctl_softc->ctl_lock);
4893 		/*
4894 		 * Drop the lock before we call the frontend's disable
4895 		 * routine, to avoid lock order reversals.
4896 		 *
4897 		 * XXX KDM what happens if the frontend list changes while
4898 		 * we're traversing it?  It's unlikely, but should be handled.
4899 		 */
4900 		retval = port->lun_disable(port->targ_lun_arg, lun->target,
4901 					 lun->lun);
4902 		mtx_lock(&ctl_softc->ctl_lock);
4903 		if (retval != 0) {
4904 			printf("ctl_alloc_lun: FETD %s port %d returned error "
4905 			       "%d for lun_disable on target %ju lun %jd\n",
4906 			       port->port_name, port->targ_port, retval,
4907 			       (uintmax_t)lun->target.id, (intmax_t)lun->lun);
4908 		}
4909 	}
4910 
4911 	mtx_unlock(&ctl_softc->ctl_lock);
4912 
4913 	return (0);
4914 }
4915 
4916 int
4917 ctl_start_lun(struct ctl_be_lun *be_lun)
4918 {
4919 	struct ctl_softc *ctl_softc;
4920 	struct ctl_lun *lun;
4921 
4922 	ctl_softc = control_softc;
4923 
4924 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4925 
4926 	mtx_lock(&lun->lun_lock);
4927 	lun->flags &= ~CTL_LUN_STOPPED;
4928 	mtx_unlock(&lun->lun_lock);
4929 
4930 	return (0);
4931 }
4932 
4933 int
4934 ctl_stop_lun(struct ctl_be_lun *be_lun)
4935 {
4936 	struct ctl_softc *ctl_softc;
4937 	struct ctl_lun *lun;
4938 
4939 	ctl_softc = control_softc;
4940 
4941 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4942 
4943 	mtx_lock(&lun->lun_lock);
4944 	lun->flags |= CTL_LUN_STOPPED;
4945 	mtx_unlock(&lun->lun_lock);
4946 
4947 	return (0);
4948 }
4949 
4950 int
4951 ctl_lun_offline(struct ctl_be_lun *be_lun)
4952 {
4953 	struct ctl_softc *ctl_softc;
4954 	struct ctl_lun *lun;
4955 
4956 	ctl_softc = control_softc;
4957 
4958 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4959 
4960 	mtx_lock(&lun->lun_lock);
4961 	lun->flags |= CTL_LUN_OFFLINE;
4962 	mtx_unlock(&lun->lun_lock);
4963 
4964 	return (0);
4965 }
4966 
4967 int
4968 ctl_lun_online(struct ctl_be_lun *be_lun)
4969 {
4970 	struct ctl_softc *ctl_softc;
4971 	struct ctl_lun *lun;
4972 
4973 	ctl_softc = control_softc;
4974 
4975 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4976 
4977 	mtx_lock(&lun->lun_lock);
4978 	lun->flags &= ~CTL_LUN_OFFLINE;
4979 	mtx_unlock(&lun->lun_lock);
4980 
4981 	return (0);
4982 }
4983 
4984 int
4985 ctl_invalidate_lun(struct ctl_be_lun *be_lun)
4986 {
4987 	struct ctl_softc *ctl_softc;
4988 	struct ctl_lun *lun;
4989 
4990 	ctl_softc = control_softc;
4991 
4992 	lun = (struct ctl_lun *)be_lun->ctl_lun;
4993 
4994 	mtx_lock(&lun->lun_lock);
4995 
4996 	/*
4997 	 * The LUN needs to be disabled before it can be marked invalid.
4998 	 */
4999 	if ((lun->flags & CTL_LUN_DISABLED) == 0) {
5000 		mtx_unlock(&lun->lun_lock);
5001 		return (-1);
5002 	}
5003 	/*
5004 	 * Mark the LUN invalid.
5005 	 */
5006 	lun->flags |= CTL_LUN_INVALID;
5007 
5008 	/*
5009 	 * If there is nothing in the OOA queue, go ahead and free the LUN.
5010 	 * If we have something in the OOA queue, we'll free it when the
5011 	 * last I/O completes.
5012 	 */
5013 	if (TAILQ_EMPTY(&lun->ooa_queue)) {
5014 		mtx_unlock(&lun->lun_lock);
5015 		mtx_lock(&ctl_softc->ctl_lock);
5016 		ctl_free_lun(lun);
5017 		mtx_unlock(&ctl_softc->ctl_lock);
5018 	} else
5019 		mtx_unlock(&lun->lun_lock);
5020 
5021 	return (0);
5022 }
5023 
5024 int
5025 ctl_lun_inoperable(struct ctl_be_lun *be_lun)
5026 {
5027 	struct ctl_softc *ctl_softc;
5028 	struct ctl_lun *lun;
5029 
5030 	ctl_softc = control_softc;
5031 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5032 
5033 	mtx_lock(&lun->lun_lock);
5034 	lun->flags |= CTL_LUN_INOPERABLE;
5035 	mtx_unlock(&lun->lun_lock);
5036 
5037 	return (0);
5038 }
5039 
5040 int
5041 ctl_lun_operable(struct ctl_be_lun *be_lun)
5042 {
5043 	struct ctl_softc *ctl_softc;
5044 	struct ctl_lun *lun;
5045 
5046 	ctl_softc = control_softc;
5047 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5048 
5049 	mtx_lock(&lun->lun_lock);
5050 	lun->flags &= ~CTL_LUN_INOPERABLE;
5051 	mtx_unlock(&lun->lun_lock);
5052 
5053 	return (0);
5054 }
5055 
5056 int
5057 ctl_lun_power_lock(struct ctl_be_lun *be_lun, struct ctl_nexus *nexus,
5058 		   int lock)
5059 {
5060 	struct ctl_softc *softc;
5061 	struct ctl_lun *lun;
5062 	struct copan_aps_subpage *current_sp;
5063 	struct ctl_page_index *page_index;
5064 	int i;
5065 
5066 	softc = control_softc;
5067 
5068 	mtx_lock(&softc->ctl_lock);
5069 
5070 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5071 	mtx_lock(&lun->lun_lock);
5072 
5073 	page_index = NULL;
5074 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
5075 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
5076 		     APS_PAGE_CODE)
5077 			continue;
5078 
5079 		if (lun->mode_pages.index[i].subpage != APS_SUBPAGE_CODE)
5080 			continue;
5081 		page_index = &lun->mode_pages.index[i];
5082 	}
5083 
5084 	if (page_index == NULL) {
5085 		mtx_unlock(&lun->lun_lock);
5086 		mtx_unlock(&softc->ctl_lock);
5087 		printf("%s: APS subpage not found for lun %ju!\n", __func__,
5088 		       (uintmax_t)lun->lun);
5089 		return (1);
5090 	}
5091 #if 0
5092 	if ((softc->aps_locked_lun != 0)
5093 	 && (softc->aps_locked_lun != lun->lun)) {
5094 		printf("%s: attempt to lock LUN %llu when %llu is already "
5095 		       "locked\n");
5096 		mtx_unlock(&lun->lun_lock);
5097 		mtx_unlock(&softc->ctl_lock);
5098 		return (1);
5099 	}
5100 #endif
5101 
5102 	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
5103 		(page_index->page_len * CTL_PAGE_CURRENT));
5104 
5105 	if (lock != 0) {
5106 		current_sp->lock_active = APS_LOCK_ACTIVE;
5107 		softc->aps_locked_lun = lun->lun;
5108 	} else {
5109 		current_sp->lock_active = 0;
5110 		softc->aps_locked_lun = 0;
5111 	}
5112 
5113 
5114 	/*
5115 	 * If we're in HA mode, try to send the lock message to the other
5116 	 * side.
5117 	 */
5118 	if (ctl_is_single == 0) {
5119 		int isc_retval;
5120 		union ctl_ha_msg lock_msg;
5121 
5122 		lock_msg.hdr.nexus = *nexus;
5123 		lock_msg.hdr.msg_type = CTL_MSG_APS_LOCK;
5124 		if (lock != 0)
5125 			lock_msg.aps.lock_flag = 1;
5126 		else
5127 			lock_msg.aps.lock_flag = 0;
5128 		isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &lock_msg,
5129 					 sizeof(lock_msg), 0);
5130 		if (isc_retval > CTL_HA_STATUS_SUCCESS) {
5131 			printf("%s: APS (lock=%d) error returned from "
5132 			       "ctl_ha_msg_send: %d\n", __func__, lock, isc_retval);
5133 			mtx_unlock(&lun->lun_lock);
5134 			mtx_unlock(&softc->ctl_lock);
5135 			return (1);
5136 		}
5137 	}
5138 
5139 	mtx_unlock(&lun->lun_lock);
5140 	mtx_unlock(&softc->ctl_lock);
5141 
5142 	return (0);
5143 }
5144 
5145 void
5146 ctl_lun_capacity_changed(struct ctl_be_lun *be_lun)
5147 {
5148 	struct ctl_lun *lun;
5149 	struct ctl_softc *softc;
5150 	int i;
5151 
5152 	softc = control_softc;
5153 
5154 	lun = (struct ctl_lun *)be_lun->ctl_lun;
5155 
5156 	mtx_lock(&lun->lun_lock);
5157 
5158 	for (i = 0; i < CTL_MAX_INITIATORS; i++)
5159 		lun->pending_ua[i] |= CTL_UA_CAPACITY_CHANGED;
5160 
5161 	mtx_unlock(&lun->lun_lock);
5162 }
5163 
5164 /*
5165  * Backend "memory move is complete" callback for requests that never
5166  * make it down to say RAIDCore's configuration code.
5167  */
5168 int
5169 ctl_config_move_done(union ctl_io *io)
5170 {
5171 	int retval;
5172 
5173 	retval = CTL_RETVAL_COMPLETE;
5174 
5175 
5176 	CTL_DEBUG_PRINT(("ctl_config_move_done\n"));
5177 	/*
5178 	 * XXX KDM this shouldn't happen, but what if it does?
5179 	 */
5180 	if (io->io_hdr.io_type != CTL_IO_SCSI)
5181 		panic("I/O type isn't CTL_IO_SCSI!");
5182 
5183 	if ((io->io_hdr.port_status == 0)
5184 	 && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5185 	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE))
5186 		io->io_hdr.status = CTL_SUCCESS;
5187 	else if ((io->io_hdr.port_status != 0)
5188 	      && ((io->io_hdr.flags & CTL_FLAG_ABORT) == 0)
5189 	      && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE)){
5190 		/*
5191 		 * For hardware error sense keys, the sense key
5192 		 * specific value is defined to be a retry count,
5193 		 * but we use it to pass back an internal FETD
5194 		 * error code.  XXX KDM  Hopefully the FETD is only
5195 		 * using 16 bits for an error code, since that's
5196 		 * all the space we have in the sks field.
5197 		 */
5198 		ctl_set_internal_failure(&io->scsiio,
5199 					 /*sks_valid*/ 1,
5200 					 /*retry_count*/
5201 					 io->io_hdr.port_status);
5202 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5203 			free(io->scsiio.kern_data_ptr, M_CTL);
5204 		ctl_done(io);
5205 		goto bailout;
5206 	}
5207 
5208 	if (((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN)
5209 	 || ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
5210 	 || ((io->io_hdr.flags & CTL_FLAG_ABORT) != 0)) {
5211 		/*
5212 		 * XXX KDM just assuming a single pointer here, and not a
5213 		 * S/G list.  If we start using S/G lists for config data,
5214 		 * we'll need to know how to clean them up here as well.
5215 		 */
5216 		if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5217 			free(io->scsiio.kern_data_ptr, M_CTL);
5218 		/* Hopefully the user has already set the status... */
5219 		ctl_done(io);
5220 	} else {
5221 		/*
5222 		 * XXX KDM now we need to continue data movement.  Some
5223 		 * options:
5224 		 * - call ctl_scsiio() again?  We don't do this for data
5225 		 *   writes, because for those at least we know ahead of
5226 		 *   time where the write will go and how long it is.  For
5227 		 *   config writes, though, that information is largely
5228 		 *   contained within the write itself, thus we need to
5229 		 *   parse out the data again.
5230 		 *
5231 		 * - Call some other function once the data is in?
5232 		 */
5233 
5234 		/*
5235 		 * XXX KDM call ctl_scsiio() again for now, and check flag
5236 		 * bits to see whether we're allocated or not.
5237 		 */
5238 		retval = ctl_scsiio(&io->scsiio);
5239 	}
5240 bailout:
5241 	return (retval);
5242 }
5243 
5244 /*
5245  * This gets called by a backend driver when it is done with a
5246  * data_submit method.
5247  */
5248 void
5249 ctl_data_submit_done(union ctl_io *io)
5250 {
5251 	/*
5252 	 * If the IO_CONT flag is set, we need to call the supplied
5253 	 * function to continue processing the I/O, instead of completing
5254 	 * the I/O just yet.
5255 	 *
5256 	 * If there is an error, though, we don't want to keep processing.
5257 	 * Instead, just send status back to the initiator.
5258 	 */
5259 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5260 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5261 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5262 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5263 		io->scsiio.io_cont(io);
5264 		return;
5265 	}
5266 	ctl_done(io);
5267 }
5268 
5269 /*
5270  * This gets called by a backend driver when it is done with a
5271  * configuration write.
5272  */
5273 void
5274 ctl_config_write_done(union ctl_io *io)
5275 {
5276 	uint8_t *buf;
5277 
5278 	/*
5279 	 * If the IO_CONT flag is set, we need to call the supplied
5280 	 * function to continue processing the I/O, instead of completing
5281 	 * the I/O just yet.
5282 	 *
5283 	 * If there is an error, though, we don't want to keep processing.
5284 	 * Instead, just send status back to the initiator.
5285 	 */
5286 	if ((io->io_hdr.flags & CTL_FLAG_IO_CONT) &&
5287 	    (io->io_hdr.flags & CTL_FLAG_ABORT) == 0 &&
5288 	    ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_STATUS_NONE ||
5289 	     (io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS)) {
5290 		io->scsiio.io_cont(io);
5291 		return;
5292 	}
5293 	/*
5294 	 * Since a configuration write can be done for commands that actually
5295 	 * have data allocated, like write buffer, and commands that have
5296 	 * no data, like start/stop unit, we need to check here.
5297 	 */
5298 	if (io->io_hdr.flags & CTL_FLAG_ALLOCATED)
5299 		buf = io->scsiio.kern_data_ptr;
5300 	else
5301 		buf = NULL;
5302 	ctl_done(io);
5303 	if (buf)
5304 		free(buf, M_CTL);
5305 }
5306 
5307 /*
5308  * SCSI release command.
5309  */
5310 int
5311 ctl_scsi_release(struct ctl_scsiio *ctsio)
5312 {
5313 	int length, longid, thirdparty_id, resv_id;
5314 	struct ctl_softc *ctl_softc;
5315 	struct ctl_lun *lun;
5316 	uint32_t residx;
5317 
5318 	length = 0;
5319 	resv_id = 0;
5320 
5321 	CTL_DEBUG_PRINT(("ctl_scsi_release\n"));
5322 
5323 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5324 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5325 	ctl_softc = control_softc;
5326 
5327 	switch (ctsio->cdb[0]) {
5328 	case RELEASE_10: {
5329 		struct scsi_release_10 *cdb;
5330 
5331 		cdb = (struct scsi_release_10 *)ctsio->cdb;
5332 
5333 		if (cdb->byte2 & SR10_LONGID)
5334 			longid = 1;
5335 		else
5336 			thirdparty_id = cdb->thirdparty_id;
5337 
5338 		resv_id = cdb->resv_id;
5339 		length = scsi_2btoul(cdb->length);
5340 		break;
5341 	}
5342 	}
5343 
5344 
5345 	/*
5346 	 * XXX KDM right now, we only support LUN reservation.  We don't
5347 	 * support 3rd party reservations, or extent reservations, which
5348 	 * might actually need the parameter list.  If we've gotten this
5349 	 * far, we've got a LUN reservation.  Anything else got kicked out
5350 	 * above.  So, according to SPC, ignore the length.
5351 	 */
5352 	length = 0;
5353 
5354 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5355 	 && (length > 0)) {
5356 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5357 		ctsio->kern_data_len = length;
5358 		ctsio->kern_total_len = length;
5359 		ctsio->kern_data_resid = 0;
5360 		ctsio->kern_rel_offset = 0;
5361 		ctsio->kern_sg_entries = 0;
5362 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5363 		ctsio->be_move_done = ctl_config_move_done;
5364 		ctl_datamove((union ctl_io *)ctsio);
5365 
5366 		return (CTL_RETVAL_COMPLETE);
5367 	}
5368 
5369 	if (length > 0)
5370 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5371 
5372 	mtx_lock(&lun->lun_lock);
5373 
5374 	/*
5375 	 * According to SPC, it is not an error for an intiator to attempt
5376 	 * to release a reservation on a LUN that isn't reserved, or that
5377 	 * is reserved by another initiator.  The reservation can only be
5378 	 * released, though, by the initiator who made it or by one of
5379 	 * several reset type events.
5380 	 */
5381 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
5382 			lun->flags &= ~CTL_LUN_RESERVED;
5383 
5384 	mtx_unlock(&lun->lun_lock);
5385 
5386 	ctsio->scsi_status = SCSI_STATUS_OK;
5387 	ctsio->io_hdr.status = CTL_SUCCESS;
5388 
5389 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5390 		free(ctsio->kern_data_ptr, M_CTL);
5391 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5392 	}
5393 
5394 	ctl_done((union ctl_io *)ctsio);
5395 	return (CTL_RETVAL_COMPLETE);
5396 }
5397 
5398 int
5399 ctl_scsi_reserve(struct ctl_scsiio *ctsio)
5400 {
5401 	int extent, thirdparty, longid;
5402 	int resv_id, length;
5403 	uint64_t thirdparty_id;
5404 	struct ctl_softc *ctl_softc;
5405 	struct ctl_lun *lun;
5406 	uint32_t residx;
5407 
5408 	extent = 0;
5409 	thirdparty = 0;
5410 	longid = 0;
5411 	resv_id = 0;
5412 	length = 0;
5413 	thirdparty_id = 0;
5414 
5415 	CTL_DEBUG_PRINT(("ctl_reserve\n"));
5416 
5417 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5418 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5419 	ctl_softc = control_softc;
5420 
5421 	switch (ctsio->cdb[0]) {
5422 	case RESERVE_10: {
5423 		struct scsi_reserve_10 *cdb;
5424 
5425 		cdb = (struct scsi_reserve_10 *)ctsio->cdb;
5426 
5427 		if (cdb->byte2 & SR10_LONGID)
5428 			longid = 1;
5429 		else
5430 			thirdparty_id = cdb->thirdparty_id;
5431 
5432 		resv_id = cdb->resv_id;
5433 		length = scsi_2btoul(cdb->length);
5434 		break;
5435 	}
5436 	}
5437 
5438 	/*
5439 	 * XXX KDM right now, we only support LUN reservation.  We don't
5440 	 * support 3rd party reservations, or extent reservations, which
5441 	 * might actually need the parameter list.  If we've gotten this
5442 	 * far, we've got a LUN reservation.  Anything else got kicked out
5443 	 * above.  So, according to SPC, ignore the length.
5444 	 */
5445 	length = 0;
5446 
5447 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5448 	 && (length > 0)) {
5449 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5450 		ctsio->kern_data_len = length;
5451 		ctsio->kern_total_len = length;
5452 		ctsio->kern_data_resid = 0;
5453 		ctsio->kern_rel_offset = 0;
5454 		ctsio->kern_sg_entries = 0;
5455 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5456 		ctsio->be_move_done = ctl_config_move_done;
5457 		ctl_datamove((union ctl_io *)ctsio);
5458 
5459 		return (CTL_RETVAL_COMPLETE);
5460 	}
5461 
5462 	if (length > 0)
5463 		thirdparty_id = scsi_8btou64(ctsio->kern_data_ptr);
5464 
5465 	mtx_lock(&lun->lun_lock);
5466 	if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx != residx)) {
5467 		ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
5468 		ctsio->io_hdr.status = CTL_SCSI_ERROR;
5469 		goto bailout;
5470 	}
5471 
5472 	lun->flags |= CTL_LUN_RESERVED;
5473 	lun->res_idx = residx;
5474 
5475 	ctsio->scsi_status = SCSI_STATUS_OK;
5476 	ctsio->io_hdr.status = CTL_SUCCESS;
5477 
5478 bailout:
5479 	mtx_unlock(&lun->lun_lock);
5480 
5481 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5482 		free(ctsio->kern_data_ptr, M_CTL);
5483 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5484 	}
5485 
5486 	ctl_done((union ctl_io *)ctsio);
5487 	return (CTL_RETVAL_COMPLETE);
5488 }
5489 
5490 int
5491 ctl_start_stop(struct ctl_scsiio *ctsio)
5492 {
5493 	struct scsi_start_stop_unit *cdb;
5494 	struct ctl_lun *lun;
5495 	struct ctl_softc *ctl_softc;
5496 	int retval;
5497 
5498 	CTL_DEBUG_PRINT(("ctl_start_stop\n"));
5499 
5500 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5501 	ctl_softc = control_softc;
5502 	retval = 0;
5503 
5504 	cdb = (struct scsi_start_stop_unit *)ctsio->cdb;
5505 
5506 	/*
5507 	 * XXX KDM
5508 	 * We don't support the immediate bit on a stop unit.  In order to
5509 	 * do that, we would need to code up a way to know that a stop is
5510 	 * pending, and hold off any new commands until it completes, one
5511 	 * way or another.  Then we could accept or reject those commands
5512 	 * depending on its status.  We would almost need to do the reverse
5513 	 * of what we do below for an immediate start -- return the copy of
5514 	 * the ctl_io to the FETD with status to send to the host (and to
5515 	 * free the copy!) and then free the original I/O once the stop
5516 	 * actually completes.  That way, the OOA queue mechanism can work
5517 	 * to block commands that shouldn't proceed.  Another alternative
5518 	 * would be to put the copy in the queue in place of the original,
5519 	 * and return the original back to the caller.  That could be
5520 	 * slightly safer..
5521 	 */
5522 	if ((cdb->byte2 & SSS_IMMED)
5523 	 && ((cdb->how & SSS_START) == 0)) {
5524 		ctl_set_invalid_field(ctsio,
5525 				      /*sks_valid*/ 1,
5526 				      /*command*/ 1,
5527 				      /*field*/ 1,
5528 				      /*bit_valid*/ 1,
5529 				      /*bit*/ 0);
5530 		ctl_done((union ctl_io *)ctsio);
5531 		return (CTL_RETVAL_COMPLETE);
5532 	}
5533 
5534 	if ((lun->flags & CTL_LUN_PR_RESERVED)
5535 	 && ((cdb->how & SSS_START)==0)) {
5536 		uint32_t residx;
5537 
5538 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5539 		if (!lun->per_res[residx].registered
5540 		 || (lun->pr_res_idx!=residx && lun->res_type < 4)) {
5541 
5542 			ctl_set_reservation_conflict(ctsio);
5543 			ctl_done((union ctl_io *)ctsio);
5544 			return (CTL_RETVAL_COMPLETE);
5545 		}
5546 	}
5547 
5548 	/*
5549 	 * If there is no backend on this device, we can't start or stop
5550 	 * it.  In theory we shouldn't get any start/stop commands in the
5551 	 * first place at this level if the LUN doesn't have a backend.
5552 	 * That should get stopped by the command decode code.
5553 	 */
5554 	if (lun->backend == NULL) {
5555 		ctl_set_invalid_opcode(ctsio);
5556 		ctl_done((union ctl_io *)ctsio);
5557 		return (CTL_RETVAL_COMPLETE);
5558 	}
5559 
5560 	/*
5561 	 * XXX KDM Copan-specific offline behavior.
5562 	 * Figure out a reasonable way to port this?
5563 	 */
5564 #ifdef NEEDTOPORT
5565 	mtx_lock(&lun->lun_lock);
5566 
5567 	if (((cdb->byte2 & SSS_ONOFFLINE) == 0)
5568 	 && (lun->flags & CTL_LUN_OFFLINE)) {
5569 		/*
5570 		 * If the LUN is offline, and the on/offline bit isn't set,
5571 		 * reject the start or stop.  Otherwise, let it through.
5572 		 */
5573 		mtx_unlock(&lun->lun_lock);
5574 		ctl_set_lun_not_ready(ctsio);
5575 		ctl_done((union ctl_io *)ctsio);
5576 	} else {
5577 		mtx_unlock(&lun->lun_lock);
5578 #endif /* NEEDTOPORT */
5579 		/*
5580 		 * This could be a start or a stop when we're online,
5581 		 * or a stop/offline or start/online.  A start or stop when
5582 		 * we're offline is covered in the case above.
5583 		 */
5584 		/*
5585 		 * In the non-immediate case, we send the request to
5586 		 * the backend and return status to the user when
5587 		 * it is done.
5588 		 *
5589 		 * In the immediate case, we allocate a new ctl_io
5590 		 * to hold a copy of the request, and send that to
5591 		 * the backend.  We then set good status on the
5592 		 * user's request and return it immediately.
5593 		 */
5594 		if (cdb->byte2 & SSS_IMMED) {
5595 			union ctl_io *new_io;
5596 
5597 			new_io = ctl_alloc_io(ctsio->io_hdr.pool);
5598 			if (new_io == NULL) {
5599 				ctl_set_busy(ctsio);
5600 				ctl_done((union ctl_io *)ctsio);
5601 			} else {
5602 				ctl_copy_io((union ctl_io *)ctsio,
5603 					    new_io);
5604 				retval = lun->backend->config_write(new_io);
5605 				ctl_set_success(ctsio);
5606 				ctl_done((union ctl_io *)ctsio);
5607 			}
5608 		} else {
5609 			retval = lun->backend->config_write(
5610 				(union ctl_io *)ctsio);
5611 		}
5612 #ifdef NEEDTOPORT
5613 	}
5614 #endif
5615 	return (retval);
5616 }
5617 
5618 /*
5619  * We support the SYNCHRONIZE CACHE command (10 and 16 byte versions), but
5620  * we don't really do anything with the LBA and length fields if the user
5621  * passes them in.  Instead we'll just flush out the cache for the entire
5622  * LUN.
5623  */
5624 int
5625 ctl_sync_cache(struct ctl_scsiio *ctsio)
5626 {
5627 	struct ctl_lun *lun;
5628 	struct ctl_softc *ctl_softc;
5629 	uint64_t starting_lba;
5630 	uint32_t block_count;
5631 	int retval;
5632 
5633 	CTL_DEBUG_PRINT(("ctl_sync_cache\n"));
5634 
5635 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5636 	ctl_softc = control_softc;
5637 	retval = 0;
5638 
5639 	switch (ctsio->cdb[0]) {
5640 	case SYNCHRONIZE_CACHE: {
5641 		struct scsi_sync_cache *cdb;
5642 		cdb = (struct scsi_sync_cache *)ctsio->cdb;
5643 
5644 		starting_lba = scsi_4btoul(cdb->begin_lba);
5645 		block_count = scsi_2btoul(cdb->lb_count);
5646 		break;
5647 	}
5648 	case SYNCHRONIZE_CACHE_16: {
5649 		struct scsi_sync_cache_16 *cdb;
5650 		cdb = (struct scsi_sync_cache_16 *)ctsio->cdb;
5651 
5652 		starting_lba = scsi_8btou64(cdb->begin_lba);
5653 		block_count = scsi_4btoul(cdb->lb_count);
5654 		break;
5655 	}
5656 	default:
5657 		ctl_set_invalid_opcode(ctsio);
5658 		ctl_done((union ctl_io *)ctsio);
5659 		goto bailout;
5660 		break; /* NOTREACHED */
5661 	}
5662 
5663 	/*
5664 	 * We check the LBA and length, but don't do anything with them.
5665 	 * A SYNCHRONIZE CACHE will cause the entire cache for this lun to
5666 	 * get flushed.  This check will just help satisfy anyone who wants
5667 	 * to see an error for an out of range LBA.
5668 	 */
5669 	if ((starting_lba + block_count) > (lun->be_lun->maxlba + 1)) {
5670 		ctl_set_lba_out_of_range(ctsio);
5671 		ctl_done((union ctl_io *)ctsio);
5672 		goto bailout;
5673 	}
5674 
5675 	/*
5676 	 * If this LUN has no backend, we can't flush the cache anyway.
5677 	 */
5678 	if (lun->backend == NULL) {
5679 		ctl_set_invalid_opcode(ctsio);
5680 		ctl_done((union ctl_io *)ctsio);
5681 		goto bailout;
5682 	}
5683 
5684 	/*
5685 	 * Check to see whether we're configured to send the SYNCHRONIZE
5686 	 * CACHE command directly to the back end.
5687 	 */
5688 	mtx_lock(&lun->lun_lock);
5689 	if ((ctl_softc->flags & CTL_FLAG_REAL_SYNC)
5690 	 && (++(lun->sync_count) >= lun->sync_interval)) {
5691 		lun->sync_count = 0;
5692 		mtx_unlock(&lun->lun_lock);
5693 		retval = lun->backend->config_write((union ctl_io *)ctsio);
5694 	} else {
5695 		mtx_unlock(&lun->lun_lock);
5696 		ctl_set_success(ctsio);
5697 		ctl_done((union ctl_io *)ctsio);
5698 	}
5699 
5700 bailout:
5701 
5702 	return (retval);
5703 }
5704 
5705 int
5706 ctl_format(struct ctl_scsiio *ctsio)
5707 {
5708 	struct scsi_format *cdb;
5709 	struct ctl_lun *lun;
5710 	struct ctl_softc *ctl_softc;
5711 	int length, defect_list_len;
5712 
5713 	CTL_DEBUG_PRINT(("ctl_format\n"));
5714 
5715 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5716 	ctl_softc = control_softc;
5717 
5718 	cdb = (struct scsi_format *)ctsio->cdb;
5719 
5720 	length = 0;
5721 	if (cdb->byte2 & SF_FMTDATA) {
5722 		if (cdb->byte2 & SF_LONGLIST)
5723 			length = sizeof(struct scsi_format_header_long);
5724 		else
5725 			length = sizeof(struct scsi_format_header_short);
5726 	}
5727 
5728 	if (((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0)
5729 	 && (length > 0)) {
5730 		ctsio->kern_data_ptr = malloc(length, M_CTL, M_WAITOK);
5731 		ctsio->kern_data_len = length;
5732 		ctsio->kern_total_len = length;
5733 		ctsio->kern_data_resid = 0;
5734 		ctsio->kern_rel_offset = 0;
5735 		ctsio->kern_sg_entries = 0;
5736 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5737 		ctsio->be_move_done = ctl_config_move_done;
5738 		ctl_datamove((union ctl_io *)ctsio);
5739 
5740 		return (CTL_RETVAL_COMPLETE);
5741 	}
5742 
5743 	defect_list_len = 0;
5744 
5745 	if (cdb->byte2 & SF_FMTDATA) {
5746 		if (cdb->byte2 & SF_LONGLIST) {
5747 			struct scsi_format_header_long *header;
5748 
5749 			header = (struct scsi_format_header_long *)
5750 				ctsio->kern_data_ptr;
5751 
5752 			defect_list_len = scsi_4btoul(header->defect_list_len);
5753 			if (defect_list_len != 0) {
5754 				ctl_set_invalid_field(ctsio,
5755 						      /*sks_valid*/ 1,
5756 						      /*command*/ 0,
5757 						      /*field*/ 2,
5758 						      /*bit_valid*/ 0,
5759 						      /*bit*/ 0);
5760 				goto bailout;
5761 			}
5762 		} else {
5763 			struct scsi_format_header_short *header;
5764 
5765 			header = (struct scsi_format_header_short *)
5766 				ctsio->kern_data_ptr;
5767 
5768 			defect_list_len = scsi_2btoul(header->defect_list_len);
5769 			if (defect_list_len != 0) {
5770 				ctl_set_invalid_field(ctsio,
5771 						      /*sks_valid*/ 1,
5772 						      /*command*/ 0,
5773 						      /*field*/ 2,
5774 						      /*bit_valid*/ 0,
5775 						      /*bit*/ 0);
5776 				goto bailout;
5777 			}
5778 		}
5779 	}
5780 
5781 	/*
5782 	 * The format command will clear out the "Medium format corrupted"
5783 	 * status if set by the configuration code.  That status is really
5784 	 * just a way to notify the host that we have lost the media, and
5785 	 * get them to issue a command that will basically make them think
5786 	 * they're blowing away the media.
5787 	 */
5788 	mtx_lock(&lun->lun_lock);
5789 	lun->flags &= ~CTL_LUN_INOPERABLE;
5790 	mtx_unlock(&lun->lun_lock);
5791 
5792 	ctsio->scsi_status = SCSI_STATUS_OK;
5793 	ctsio->io_hdr.status = CTL_SUCCESS;
5794 bailout:
5795 
5796 	if (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) {
5797 		free(ctsio->kern_data_ptr, M_CTL);
5798 		ctsio->io_hdr.flags &= ~CTL_FLAG_ALLOCATED;
5799 	}
5800 
5801 	ctl_done((union ctl_io *)ctsio);
5802 	return (CTL_RETVAL_COMPLETE);
5803 }
5804 
5805 int
5806 ctl_read_buffer(struct ctl_scsiio *ctsio)
5807 {
5808 	struct scsi_read_buffer *cdb;
5809 	struct ctl_lun *lun;
5810 	int buffer_offset, len;
5811 	static uint8_t descr[4];
5812 	static uint8_t echo_descr[4] = { 0 };
5813 
5814 	CTL_DEBUG_PRINT(("ctl_read_buffer\n"));
5815 
5816 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5817 	cdb = (struct scsi_read_buffer *)ctsio->cdb;
5818 
5819 	if (lun->flags & CTL_LUN_PR_RESERVED) {
5820 		uint32_t residx;
5821 
5822 		/*
5823 		 * XXX KDM need a lock here.
5824 		 */
5825 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
5826 		if ((lun->res_type == SPR_TYPE_EX_AC
5827 		  && residx != lun->pr_res_idx)
5828 		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
5829 		   || lun->res_type == SPR_TYPE_EX_AC_AR)
5830 		  && !lun->per_res[residx].registered)) {
5831 			ctl_set_reservation_conflict(ctsio);
5832 			ctl_done((union ctl_io *)ctsio);
5833 			return (CTL_RETVAL_COMPLETE);
5834 	        }
5835 	}
5836 
5837 	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA &&
5838 	    (cdb->byte2 & RWB_MODE) != RWB_MODE_ECHO_DESCR &&
5839 	    (cdb->byte2 & RWB_MODE) != RWB_MODE_DESCR) {
5840 		ctl_set_invalid_field(ctsio,
5841 				      /*sks_valid*/ 1,
5842 				      /*command*/ 1,
5843 				      /*field*/ 1,
5844 				      /*bit_valid*/ 1,
5845 				      /*bit*/ 4);
5846 		ctl_done((union ctl_io *)ctsio);
5847 		return (CTL_RETVAL_COMPLETE);
5848 	}
5849 
5850 	len = scsi_3btoul(cdb->length);
5851 	buffer_offset = scsi_3btoul(cdb->offset);
5852 
5853 	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5854 		ctl_set_invalid_field(ctsio,
5855 				      /*sks_valid*/ 1,
5856 				      /*command*/ 1,
5857 				      /*field*/ 6,
5858 				      /*bit_valid*/ 0,
5859 				      /*bit*/ 0);
5860 		ctl_done((union ctl_io *)ctsio);
5861 		return (CTL_RETVAL_COMPLETE);
5862 	}
5863 
5864 	if ((cdb->byte2 & RWB_MODE) == RWB_MODE_DESCR) {
5865 		descr[0] = 0;
5866 		scsi_ulto3b(sizeof(lun->write_buffer), &descr[1]);
5867 		ctsio->kern_data_ptr = descr;
5868 		len = min(len, sizeof(descr));
5869 	} else if ((cdb->byte2 & RWB_MODE) == RWB_MODE_ECHO_DESCR) {
5870 		ctsio->kern_data_ptr = echo_descr;
5871 		len = min(len, sizeof(echo_descr));
5872 	} else
5873 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5874 	ctsio->kern_data_len = len;
5875 	ctsio->kern_total_len = len;
5876 	ctsio->kern_data_resid = 0;
5877 	ctsio->kern_rel_offset = 0;
5878 	ctsio->kern_sg_entries = 0;
5879 	ctsio->be_move_done = ctl_config_move_done;
5880 	ctl_datamove((union ctl_io *)ctsio);
5881 
5882 	return (CTL_RETVAL_COMPLETE);
5883 }
5884 
5885 int
5886 ctl_write_buffer(struct ctl_scsiio *ctsio)
5887 {
5888 	struct scsi_write_buffer *cdb;
5889 	struct ctl_lun *lun;
5890 	int buffer_offset, len;
5891 
5892 	CTL_DEBUG_PRINT(("ctl_write_buffer\n"));
5893 
5894 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5895 	cdb = (struct scsi_write_buffer *)ctsio->cdb;
5896 
5897 	if ((cdb->byte2 & RWB_MODE) != RWB_MODE_DATA) {
5898 		ctl_set_invalid_field(ctsio,
5899 				      /*sks_valid*/ 1,
5900 				      /*command*/ 1,
5901 				      /*field*/ 1,
5902 				      /*bit_valid*/ 1,
5903 				      /*bit*/ 4);
5904 		ctl_done((union ctl_io *)ctsio);
5905 		return (CTL_RETVAL_COMPLETE);
5906 	}
5907 
5908 	len = scsi_3btoul(cdb->length);
5909 	buffer_offset = scsi_3btoul(cdb->offset);
5910 
5911 	if (buffer_offset + len > sizeof(lun->write_buffer)) {
5912 		ctl_set_invalid_field(ctsio,
5913 				      /*sks_valid*/ 1,
5914 				      /*command*/ 1,
5915 				      /*field*/ 6,
5916 				      /*bit_valid*/ 0,
5917 				      /*bit*/ 0);
5918 		ctl_done((union ctl_io *)ctsio);
5919 		return (CTL_RETVAL_COMPLETE);
5920 	}
5921 
5922 	/*
5923 	 * If we've got a kernel request that hasn't been malloced yet,
5924 	 * malloc it and tell the caller the data buffer is here.
5925 	 */
5926 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
5927 		ctsio->kern_data_ptr = lun->write_buffer + buffer_offset;
5928 		ctsio->kern_data_len = len;
5929 		ctsio->kern_total_len = len;
5930 		ctsio->kern_data_resid = 0;
5931 		ctsio->kern_rel_offset = 0;
5932 		ctsio->kern_sg_entries = 0;
5933 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
5934 		ctsio->be_move_done = ctl_config_move_done;
5935 		ctl_datamove((union ctl_io *)ctsio);
5936 
5937 		return (CTL_RETVAL_COMPLETE);
5938 	}
5939 
5940 	ctl_done((union ctl_io *)ctsio);
5941 
5942 	return (CTL_RETVAL_COMPLETE);
5943 }
5944 
5945 int
5946 ctl_write_same(struct ctl_scsiio *ctsio)
5947 {
5948 	struct ctl_lun *lun;
5949 	struct ctl_lba_len_flags *lbalen;
5950 	uint64_t lba;
5951 	uint32_t num_blocks;
5952 	int len, retval;
5953 	uint8_t byte2;
5954 
5955 	retval = CTL_RETVAL_COMPLETE;
5956 
5957 	CTL_DEBUG_PRINT(("ctl_write_same\n"));
5958 
5959 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
5960 
5961 	switch (ctsio->cdb[0]) {
5962 	case WRITE_SAME_10: {
5963 		struct scsi_write_same_10 *cdb;
5964 
5965 		cdb = (struct scsi_write_same_10 *)ctsio->cdb;
5966 
5967 		lba = scsi_4btoul(cdb->addr);
5968 		num_blocks = scsi_2btoul(cdb->length);
5969 		byte2 = cdb->byte2;
5970 		break;
5971 	}
5972 	case WRITE_SAME_16: {
5973 		struct scsi_write_same_16 *cdb;
5974 
5975 		cdb = (struct scsi_write_same_16 *)ctsio->cdb;
5976 
5977 		lba = scsi_8btou64(cdb->addr);
5978 		num_blocks = scsi_4btoul(cdb->length);
5979 		byte2 = cdb->byte2;
5980 		break;
5981 	}
5982 	default:
5983 		/*
5984 		 * We got a command we don't support.  This shouldn't
5985 		 * happen, commands should be filtered out above us.
5986 		 */
5987 		ctl_set_invalid_opcode(ctsio);
5988 		ctl_done((union ctl_io *)ctsio);
5989 
5990 		return (CTL_RETVAL_COMPLETE);
5991 		break; /* NOTREACHED */
5992 	}
5993 
5994 	/* NDOB and ANCHOR flags can be used only together with UNMAP */
5995 	if ((byte2 & SWS_UNMAP) == 0 &&
5996 	    (byte2 & (SWS_NDOB | SWS_ANCHOR)) != 0) {
5997 		ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
5998 		    /*command*/ 1, /*field*/ 1, /*bit_valid*/ 1, /*bit*/ 0);
5999 		ctl_done((union ctl_io *)ctsio);
6000 		return (CTL_RETVAL_COMPLETE);
6001 	}
6002 
6003 	/*
6004 	 * The first check is to make sure we're in bounds, the second
6005 	 * check is to catch wrap-around problems.  If the lba + num blocks
6006 	 * is less than the lba, then we've wrapped around and the block
6007 	 * range is invalid anyway.
6008 	 */
6009 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6010 	 || ((lba + num_blocks) < lba)) {
6011 		ctl_set_lba_out_of_range(ctsio);
6012 		ctl_done((union ctl_io *)ctsio);
6013 		return (CTL_RETVAL_COMPLETE);
6014 	}
6015 
6016 	/* Zero number of blocks means "to the last logical block" */
6017 	if (num_blocks == 0) {
6018 		if ((lun->be_lun->maxlba + 1) - lba > UINT32_MAX) {
6019 			ctl_set_invalid_field(ctsio,
6020 					      /*sks_valid*/ 0,
6021 					      /*command*/ 1,
6022 					      /*field*/ 0,
6023 					      /*bit_valid*/ 0,
6024 					      /*bit*/ 0);
6025 			ctl_done((union ctl_io *)ctsio);
6026 			return (CTL_RETVAL_COMPLETE);
6027 		}
6028 		num_blocks = (lun->be_lun->maxlba + 1) - lba;
6029 	}
6030 
6031 	len = lun->be_lun->blocksize;
6032 
6033 	/*
6034 	 * If we've got a kernel request that hasn't been malloced yet,
6035 	 * malloc it and tell the caller the data buffer is here.
6036 	 */
6037 	if ((byte2 & SWS_NDOB) == 0 &&
6038 	    (ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6039 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6040 		ctsio->kern_data_len = len;
6041 		ctsio->kern_total_len = len;
6042 		ctsio->kern_data_resid = 0;
6043 		ctsio->kern_rel_offset = 0;
6044 		ctsio->kern_sg_entries = 0;
6045 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6046 		ctsio->be_move_done = ctl_config_move_done;
6047 		ctl_datamove((union ctl_io *)ctsio);
6048 
6049 		return (CTL_RETVAL_COMPLETE);
6050 	}
6051 
6052 	lbalen = (struct ctl_lba_len_flags *)&ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6053 	lbalen->lba = lba;
6054 	lbalen->len = num_blocks;
6055 	lbalen->flags = byte2;
6056 	retval = lun->backend->config_write((union ctl_io *)ctsio);
6057 
6058 	return (retval);
6059 }
6060 
6061 int
6062 ctl_unmap(struct ctl_scsiio *ctsio)
6063 {
6064 	struct ctl_lun *lun;
6065 	struct scsi_unmap *cdb;
6066 	struct ctl_ptr_len_flags *ptrlen;
6067 	struct scsi_unmap_header *hdr;
6068 	struct scsi_unmap_desc *buf, *end, *endnz, *range;
6069 	uint64_t lba;
6070 	uint32_t num_blocks;
6071 	int len, retval;
6072 	uint8_t byte2;
6073 
6074 	retval = CTL_RETVAL_COMPLETE;
6075 
6076 	CTL_DEBUG_PRINT(("ctl_unmap\n"));
6077 
6078 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6079 	cdb = (struct scsi_unmap *)ctsio->cdb;
6080 
6081 	len = scsi_2btoul(cdb->length);
6082 	byte2 = cdb->byte2;
6083 
6084 	/*
6085 	 * If we've got a kernel request that hasn't been malloced yet,
6086 	 * malloc it and tell the caller the data buffer is here.
6087 	 */
6088 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6089 		ctsio->kern_data_ptr = malloc(len, M_CTL, M_WAITOK);;
6090 		ctsio->kern_data_len = len;
6091 		ctsio->kern_total_len = len;
6092 		ctsio->kern_data_resid = 0;
6093 		ctsio->kern_rel_offset = 0;
6094 		ctsio->kern_sg_entries = 0;
6095 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6096 		ctsio->be_move_done = ctl_config_move_done;
6097 		ctl_datamove((union ctl_io *)ctsio);
6098 
6099 		return (CTL_RETVAL_COMPLETE);
6100 	}
6101 
6102 	len = ctsio->kern_total_len - ctsio->kern_data_resid;
6103 	hdr = (struct scsi_unmap_header *)ctsio->kern_data_ptr;
6104 	if (len < sizeof (*hdr) ||
6105 	    len < (scsi_2btoul(hdr->length) + sizeof(hdr->length)) ||
6106 	    len < (scsi_2btoul(hdr->desc_length) + sizeof (*hdr)) ||
6107 	    scsi_2btoul(hdr->desc_length) % sizeof(*buf) != 0) {
6108 		ctl_set_invalid_field(ctsio,
6109 				      /*sks_valid*/ 0,
6110 				      /*command*/ 0,
6111 				      /*field*/ 0,
6112 				      /*bit_valid*/ 0,
6113 				      /*bit*/ 0);
6114 		ctl_done((union ctl_io *)ctsio);
6115 		return (CTL_RETVAL_COMPLETE);
6116 	}
6117 	len = scsi_2btoul(hdr->desc_length);
6118 	buf = (struct scsi_unmap_desc *)(hdr + 1);
6119 	end = buf + len / sizeof(*buf);
6120 
6121 	endnz = buf;
6122 	for (range = buf; range < end; range++) {
6123 		lba = scsi_8btou64(range->lba);
6124 		num_blocks = scsi_4btoul(range->length);
6125 		if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
6126 		 || ((lba + num_blocks) < lba)) {
6127 			ctl_set_lba_out_of_range(ctsio);
6128 			ctl_done((union ctl_io *)ctsio);
6129 			return (CTL_RETVAL_COMPLETE);
6130 		}
6131 		if (num_blocks != 0)
6132 			endnz = range + 1;
6133 	}
6134 
6135 	/*
6136 	 * Block backend can not handle zero last range.
6137 	 * Filter it out and return if there is nothing left.
6138 	 */
6139 	len = (uint8_t *)endnz - (uint8_t *)buf;
6140 	if (len == 0) {
6141 		ctl_set_success(ctsio);
6142 		ctl_done((union ctl_io *)ctsio);
6143 		return (CTL_RETVAL_COMPLETE);
6144 	}
6145 
6146 	mtx_lock(&lun->lun_lock);
6147 	ptrlen = (struct ctl_ptr_len_flags *)
6148 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
6149 	ptrlen->ptr = (void *)buf;
6150 	ptrlen->len = len;
6151 	ptrlen->flags = byte2;
6152 	ctl_check_blocked(lun);
6153 	mtx_unlock(&lun->lun_lock);
6154 
6155 	retval = lun->backend->config_write((union ctl_io *)ctsio);
6156 	return (retval);
6157 }
6158 
6159 /*
6160  * Note that this function currently doesn't actually do anything inside
6161  * CTL to enforce things if the DQue bit is turned on.
6162  *
6163  * Also note that this function can't be used in the default case, because
6164  * the DQue bit isn't set in the changeable mask for the control mode page
6165  * anyway.  This is just here as an example for how to implement a page
6166  * handler, and a placeholder in case we want to allow the user to turn
6167  * tagged queueing on and off.
6168  *
6169  * The D_SENSE bit handling is functional, however, and will turn
6170  * descriptor sense on and off for a given LUN.
6171  */
6172 int
6173 ctl_control_page_handler(struct ctl_scsiio *ctsio,
6174 			 struct ctl_page_index *page_index, uint8_t *page_ptr)
6175 {
6176 	struct scsi_control_page *current_cp, *saved_cp, *user_cp;
6177 	struct ctl_lun *lun;
6178 	struct ctl_softc *softc;
6179 	int set_ua;
6180 	uint32_t initidx;
6181 
6182 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6183 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6184 	set_ua = 0;
6185 
6186 	user_cp = (struct scsi_control_page *)page_ptr;
6187 	current_cp = (struct scsi_control_page *)
6188 		(page_index->page_data + (page_index->page_len *
6189 		CTL_PAGE_CURRENT));
6190 	saved_cp = (struct scsi_control_page *)
6191 		(page_index->page_data + (page_index->page_len *
6192 		CTL_PAGE_SAVED));
6193 
6194 	softc = control_softc;
6195 
6196 	mtx_lock(&lun->lun_lock);
6197 	if (((current_cp->rlec & SCP_DSENSE) == 0)
6198 	 && ((user_cp->rlec & SCP_DSENSE) != 0)) {
6199 		/*
6200 		 * Descriptor sense is currently turned off and the user
6201 		 * wants to turn it on.
6202 		 */
6203 		current_cp->rlec |= SCP_DSENSE;
6204 		saved_cp->rlec |= SCP_DSENSE;
6205 		lun->flags |= CTL_LUN_SENSE_DESC;
6206 		set_ua = 1;
6207 	} else if (((current_cp->rlec & SCP_DSENSE) != 0)
6208 		&& ((user_cp->rlec & SCP_DSENSE) == 0)) {
6209 		/*
6210 		 * Descriptor sense is currently turned on, and the user
6211 		 * wants to turn it off.
6212 		 */
6213 		current_cp->rlec &= ~SCP_DSENSE;
6214 		saved_cp->rlec &= ~SCP_DSENSE;
6215 		lun->flags &= ~CTL_LUN_SENSE_DESC;
6216 		set_ua = 1;
6217 	}
6218 	if ((current_cp->queue_flags & SCP_QUEUE_ALG_MASK) !=
6219 	    (user_cp->queue_flags & SCP_QUEUE_ALG_MASK)) {
6220 		current_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6221 		current_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6222 		saved_cp->queue_flags &= ~SCP_QUEUE_ALG_MASK;
6223 		saved_cp->queue_flags |= user_cp->queue_flags & SCP_QUEUE_ALG_MASK;
6224 		set_ua = 1;
6225 	}
6226 	if ((current_cp->eca_and_aen & SCP_SWP) !=
6227 	    (user_cp->eca_and_aen & SCP_SWP)) {
6228 		current_cp->eca_and_aen &= ~SCP_SWP;
6229 		current_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6230 		saved_cp->eca_and_aen &= ~SCP_SWP;
6231 		saved_cp->eca_and_aen |= user_cp->eca_and_aen & SCP_SWP;
6232 		set_ua = 1;
6233 	}
6234 	if (set_ua != 0) {
6235 		int i;
6236 		/*
6237 		 * Let other initiators know that the mode
6238 		 * parameters for this LUN have changed.
6239 		 */
6240 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6241 			if (i == initidx)
6242 				continue;
6243 
6244 			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6245 		}
6246 	}
6247 	mtx_unlock(&lun->lun_lock);
6248 
6249 	return (0);
6250 }
6251 
6252 int
6253 ctl_caching_sp_handler(struct ctl_scsiio *ctsio,
6254 		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6255 {
6256 	struct scsi_caching_page *current_cp, *saved_cp, *user_cp;
6257 	struct ctl_lun *lun;
6258 	int set_ua;
6259 	uint32_t initidx;
6260 
6261 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6262 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
6263 	set_ua = 0;
6264 
6265 	user_cp = (struct scsi_caching_page *)page_ptr;
6266 	current_cp = (struct scsi_caching_page *)
6267 		(page_index->page_data + (page_index->page_len *
6268 		CTL_PAGE_CURRENT));
6269 	saved_cp = (struct scsi_caching_page *)
6270 		(page_index->page_data + (page_index->page_len *
6271 		CTL_PAGE_SAVED));
6272 
6273 	mtx_lock(&lun->lun_lock);
6274 	if ((current_cp->flags1 & (SCP_WCE | SCP_RCD)) !=
6275 	    (user_cp->flags1 & (SCP_WCE | SCP_RCD))) {
6276 		current_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6277 		current_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6278 		saved_cp->flags1 &= ~(SCP_WCE | SCP_RCD);
6279 		saved_cp->flags1 |= user_cp->flags1 & (SCP_WCE | SCP_RCD);
6280 		set_ua = 1;
6281 	}
6282 	if (set_ua != 0) {
6283 		int i;
6284 		/*
6285 		 * Let other initiators know that the mode
6286 		 * parameters for this LUN have changed.
6287 		 */
6288 		for (i = 0; i < CTL_MAX_INITIATORS; i++) {
6289 			if (i == initidx)
6290 				continue;
6291 
6292 			lun->pending_ua[i] |= CTL_UA_MODE_CHANGE;
6293 		}
6294 	}
6295 	mtx_unlock(&lun->lun_lock);
6296 
6297 	return (0);
6298 }
6299 
6300 int
6301 ctl_power_sp_handler(struct ctl_scsiio *ctsio,
6302 		     struct ctl_page_index *page_index, uint8_t *page_ptr)
6303 {
6304 	return (0);
6305 }
6306 
6307 int
6308 ctl_power_sp_sense_handler(struct ctl_scsiio *ctsio,
6309 			   struct ctl_page_index *page_index, int pc)
6310 {
6311 	struct copan_power_subpage *page;
6312 
6313 	page = (struct copan_power_subpage *)page_index->page_data +
6314 		(page_index->page_len * pc);
6315 
6316 	switch (pc) {
6317 	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6318 		/*
6319 		 * We don't update the changable bits for this page.
6320 		 */
6321 		break;
6322 	case SMS_PAGE_CTRL_CURRENT >> 6:
6323 	case SMS_PAGE_CTRL_DEFAULT >> 6:
6324 	case SMS_PAGE_CTRL_SAVED >> 6:
6325 #ifdef NEEDTOPORT
6326 		ctl_update_power_subpage(page);
6327 #endif
6328 		break;
6329 	default:
6330 #ifdef NEEDTOPORT
6331 		EPRINT(0, "Invalid PC %d!!", pc);
6332 #endif
6333 		break;
6334 	}
6335 	return (0);
6336 }
6337 
6338 
6339 int
6340 ctl_aps_sp_handler(struct ctl_scsiio *ctsio,
6341 		   struct ctl_page_index *page_index, uint8_t *page_ptr)
6342 {
6343 	struct copan_aps_subpage *user_sp;
6344 	struct copan_aps_subpage *current_sp;
6345 	union ctl_modepage_info *modepage_info;
6346 	struct ctl_softc *softc;
6347 	struct ctl_lun *lun;
6348 	int retval;
6349 
6350 	retval = CTL_RETVAL_COMPLETE;
6351 	current_sp = (struct copan_aps_subpage *)(page_index->page_data +
6352 		     (page_index->page_len * CTL_PAGE_CURRENT));
6353 	softc = control_softc;
6354 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6355 
6356 	user_sp = (struct copan_aps_subpage *)page_ptr;
6357 
6358 	modepage_info = (union ctl_modepage_info *)
6359 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6360 
6361 	modepage_info->header.page_code = page_index->page_code & SMPH_PC_MASK;
6362 	modepage_info->header.subpage = page_index->subpage;
6363 	modepage_info->aps.lock_active = user_sp->lock_active;
6364 
6365 	mtx_lock(&softc->ctl_lock);
6366 
6367 	/*
6368 	 * If there is a request to lock the LUN and another LUN is locked
6369 	 * this is an error. If the requested LUN is already locked ignore
6370 	 * the request. If no LUN is locked attempt to lock it.
6371 	 * if there is a request to unlock the LUN and the LUN is currently
6372 	 * locked attempt to unlock it. Otherwise ignore the request. i.e.
6373 	 * if another LUN is locked or no LUN is locked.
6374 	 */
6375 	if (user_sp->lock_active & APS_LOCK_ACTIVE) {
6376 		if (softc->aps_locked_lun == lun->lun) {
6377 			/*
6378 			 * This LUN is already locked, so we're done.
6379 			 */
6380 			retval = CTL_RETVAL_COMPLETE;
6381 		} else if (softc->aps_locked_lun == 0) {
6382 			/*
6383 			 * No one has the lock, pass the request to the
6384 			 * backend.
6385 			 */
6386 			retval = lun->backend->config_write(
6387 				(union ctl_io *)ctsio);
6388 		} else {
6389 			/*
6390 			 * Someone else has the lock, throw out the request.
6391 			 */
6392 			ctl_set_already_locked(ctsio);
6393 			free(ctsio->kern_data_ptr, M_CTL);
6394 			ctl_done((union ctl_io *)ctsio);
6395 
6396 			/*
6397 			 * Set the return value so that ctl_do_mode_select()
6398 			 * won't try to complete the command.  We already
6399 			 * completed it here.
6400 			 */
6401 			retval = CTL_RETVAL_ERROR;
6402 		}
6403 	} else if (softc->aps_locked_lun == lun->lun) {
6404 		/*
6405 		 * This LUN is locked, so pass the unlock request to the
6406 		 * backend.
6407 		 */
6408 		retval = lun->backend->config_write((union ctl_io *)ctsio);
6409 	}
6410 	mtx_unlock(&softc->ctl_lock);
6411 
6412 	return (retval);
6413 }
6414 
6415 int
6416 ctl_debugconf_sp_select_handler(struct ctl_scsiio *ctsio,
6417 				struct ctl_page_index *page_index,
6418 				uint8_t *page_ptr)
6419 {
6420 	uint8_t *c;
6421 	int i;
6422 
6423 	c = ((struct copan_debugconf_subpage *)page_ptr)->ctl_time_io_secs;
6424 	ctl_time_io_secs =
6425 		(c[0] << 8) |
6426 		(c[1] << 0) |
6427 		0;
6428 	CTL_DEBUG_PRINT(("set ctl_time_io_secs to %d\n", ctl_time_io_secs));
6429 	printf("set ctl_time_io_secs to %d\n", ctl_time_io_secs);
6430 	printf("page data:");
6431 	for (i=0; i<8; i++)
6432 		printf(" %.2x",page_ptr[i]);
6433 	printf("\n");
6434 	return (0);
6435 }
6436 
6437 int
6438 ctl_debugconf_sp_sense_handler(struct ctl_scsiio *ctsio,
6439 			       struct ctl_page_index *page_index,
6440 			       int pc)
6441 {
6442 	struct copan_debugconf_subpage *page;
6443 
6444 	page = (struct copan_debugconf_subpage *)page_index->page_data +
6445 		(page_index->page_len * pc);
6446 
6447 	switch (pc) {
6448 	case SMS_PAGE_CTRL_CHANGEABLE >> 6:
6449 	case SMS_PAGE_CTRL_DEFAULT >> 6:
6450 	case SMS_PAGE_CTRL_SAVED >> 6:
6451 		/*
6452 		 * We don't update the changable or default bits for this page.
6453 		 */
6454 		break;
6455 	case SMS_PAGE_CTRL_CURRENT >> 6:
6456 		page->ctl_time_io_secs[0] = ctl_time_io_secs >> 8;
6457 		page->ctl_time_io_secs[1] = ctl_time_io_secs >> 0;
6458 		break;
6459 	default:
6460 #ifdef NEEDTOPORT
6461 		EPRINT(0, "Invalid PC %d!!", pc);
6462 #endif /* NEEDTOPORT */
6463 		break;
6464 	}
6465 	return (0);
6466 }
6467 
6468 
6469 static int
6470 ctl_do_mode_select(union ctl_io *io)
6471 {
6472 	struct scsi_mode_page_header *page_header;
6473 	struct ctl_page_index *page_index;
6474 	struct ctl_scsiio *ctsio;
6475 	int control_dev, page_len;
6476 	int page_len_offset, page_len_size;
6477 	union ctl_modepage_info *modepage_info;
6478 	struct ctl_lun *lun;
6479 	int *len_left, *len_used;
6480 	int retval, i;
6481 
6482 	ctsio = &io->scsiio;
6483 	page_index = NULL;
6484 	page_len = 0;
6485 	retval = CTL_RETVAL_COMPLETE;
6486 
6487 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6488 
6489 	if (lun->be_lun->lun_type != T_DIRECT)
6490 		control_dev = 1;
6491 	else
6492 		control_dev = 0;
6493 
6494 	modepage_info = (union ctl_modepage_info *)
6495 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6496 	len_left = &modepage_info->header.len_left;
6497 	len_used = &modepage_info->header.len_used;
6498 
6499 do_next_page:
6500 
6501 	page_header = (struct scsi_mode_page_header *)
6502 		(ctsio->kern_data_ptr + *len_used);
6503 
6504 	if (*len_left == 0) {
6505 		free(ctsio->kern_data_ptr, M_CTL);
6506 		ctl_set_success(ctsio);
6507 		ctl_done((union ctl_io *)ctsio);
6508 		return (CTL_RETVAL_COMPLETE);
6509 	} else if (*len_left < sizeof(struct scsi_mode_page_header)) {
6510 
6511 		free(ctsio->kern_data_ptr, M_CTL);
6512 		ctl_set_param_len_error(ctsio);
6513 		ctl_done((union ctl_io *)ctsio);
6514 		return (CTL_RETVAL_COMPLETE);
6515 
6516 	} else if ((page_header->page_code & SMPH_SPF)
6517 		&& (*len_left < sizeof(struct scsi_mode_page_header_sp))) {
6518 
6519 		free(ctsio->kern_data_ptr, M_CTL);
6520 		ctl_set_param_len_error(ctsio);
6521 		ctl_done((union ctl_io *)ctsio);
6522 		return (CTL_RETVAL_COMPLETE);
6523 	}
6524 
6525 
6526 	/*
6527 	 * XXX KDM should we do something with the block descriptor?
6528 	 */
6529 	for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6530 
6531 		if ((control_dev != 0)
6532 		 && (lun->mode_pages.index[i].page_flags &
6533 		     CTL_PAGE_FLAG_DISK_ONLY))
6534 			continue;
6535 
6536 		if ((lun->mode_pages.index[i].page_code & SMPH_PC_MASK) !=
6537 		    (page_header->page_code & SMPH_PC_MASK))
6538 			continue;
6539 
6540 		/*
6541 		 * If neither page has a subpage code, then we've got a
6542 		 * match.
6543 		 */
6544 		if (((lun->mode_pages.index[i].page_code & SMPH_SPF) == 0)
6545 		 && ((page_header->page_code & SMPH_SPF) == 0)) {
6546 			page_index = &lun->mode_pages.index[i];
6547 			page_len = page_header->page_length;
6548 			break;
6549 		}
6550 
6551 		/*
6552 		 * If both pages have subpages, then the subpage numbers
6553 		 * have to match.
6554 		 */
6555 		if ((lun->mode_pages.index[i].page_code & SMPH_SPF)
6556 		  && (page_header->page_code & SMPH_SPF)) {
6557 			struct scsi_mode_page_header_sp *sph;
6558 
6559 			sph = (struct scsi_mode_page_header_sp *)page_header;
6560 
6561 			if (lun->mode_pages.index[i].subpage ==
6562 			    sph->subpage) {
6563 				page_index = &lun->mode_pages.index[i];
6564 				page_len = scsi_2btoul(sph->page_length);
6565 				break;
6566 			}
6567 		}
6568 	}
6569 
6570 	/*
6571 	 * If we couldn't find the page, or if we don't have a mode select
6572 	 * handler for it, send back an error to the user.
6573 	 */
6574 	if ((page_index == NULL)
6575 	 || (page_index->select_handler == NULL)) {
6576 		ctl_set_invalid_field(ctsio,
6577 				      /*sks_valid*/ 1,
6578 				      /*command*/ 0,
6579 				      /*field*/ *len_used,
6580 				      /*bit_valid*/ 0,
6581 				      /*bit*/ 0);
6582 		free(ctsio->kern_data_ptr, M_CTL);
6583 		ctl_done((union ctl_io *)ctsio);
6584 		return (CTL_RETVAL_COMPLETE);
6585 	}
6586 
6587 	if (page_index->page_code & SMPH_SPF) {
6588 		page_len_offset = 2;
6589 		page_len_size = 2;
6590 	} else {
6591 		page_len_size = 1;
6592 		page_len_offset = 1;
6593 	}
6594 
6595 	/*
6596 	 * If the length the initiator gives us isn't the one we specify in
6597 	 * the mode page header, or if they didn't specify enough data in
6598 	 * the CDB to avoid truncating this page, kick out the request.
6599 	 */
6600 	if ((page_len != (page_index->page_len - page_len_offset -
6601 			  page_len_size))
6602 	 || (*len_left < page_index->page_len)) {
6603 
6604 
6605 		ctl_set_invalid_field(ctsio,
6606 				      /*sks_valid*/ 1,
6607 				      /*command*/ 0,
6608 				      /*field*/ *len_used + page_len_offset,
6609 				      /*bit_valid*/ 0,
6610 				      /*bit*/ 0);
6611 		free(ctsio->kern_data_ptr, M_CTL);
6612 		ctl_done((union ctl_io *)ctsio);
6613 		return (CTL_RETVAL_COMPLETE);
6614 	}
6615 
6616 	/*
6617 	 * Run through the mode page, checking to make sure that the bits
6618 	 * the user changed are actually legal for him to change.
6619 	 */
6620 	for (i = 0; i < page_index->page_len; i++) {
6621 		uint8_t *user_byte, *change_mask, *current_byte;
6622 		int bad_bit;
6623 		int j;
6624 
6625 		user_byte = (uint8_t *)page_header + i;
6626 		change_mask = page_index->page_data +
6627 			      (page_index->page_len * CTL_PAGE_CHANGEABLE) + i;
6628 		current_byte = page_index->page_data +
6629 			       (page_index->page_len * CTL_PAGE_CURRENT) + i;
6630 
6631 		/*
6632 		 * Check to see whether the user set any bits in this byte
6633 		 * that he is not allowed to set.
6634 		 */
6635 		if ((*user_byte & ~(*change_mask)) ==
6636 		    (*current_byte & ~(*change_mask)))
6637 			continue;
6638 
6639 		/*
6640 		 * Go through bit by bit to determine which one is illegal.
6641 		 */
6642 		bad_bit = 0;
6643 		for (j = 7; j >= 0; j--) {
6644 			if ((((1 << i) & ~(*change_mask)) & *user_byte) !=
6645 			    (((1 << i) & ~(*change_mask)) & *current_byte)) {
6646 				bad_bit = i;
6647 				break;
6648 			}
6649 		}
6650 		ctl_set_invalid_field(ctsio,
6651 				      /*sks_valid*/ 1,
6652 				      /*command*/ 0,
6653 				      /*field*/ *len_used + i,
6654 				      /*bit_valid*/ 1,
6655 				      /*bit*/ bad_bit);
6656 		free(ctsio->kern_data_ptr, M_CTL);
6657 		ctl_done((union ctl_io *)ctsio);
6658 		return (CTL_RETVAL_COMPLETE);
6659 	}
6660 
6661 	/*
6662 	 * Decrement these before we call the page handler, since we may
6663 	 * end up getting called back one way or another before the handler
6664 	 * returns to this context.
6665 	 */
6666 	*len_left -= page_index->page_len;
6667 	*len_used += page_index->page_len;
6668 
6669 	retval = page_index->select_handler(ctsio, page_index,
6670 					    (uint8_t *)page_header);
6671 
6672 	/*
6673 	 * If the page handler returns CTL_RETVAL_QUEUED, then we need to
6674 	 * wait until this queued command completes to finish processing
6675 	 * the mode page.  If it returns anything other than
6676 	 * CTL_RETVAL_COMPLETE (e.g. CTL_RETVAL_ERROR), then it should have
6677 	 * already set the sense information, freed the data pointer, and
6678 	 * completed the io for us.
6679 	 */
6680 	if (retval != CTL_RETVAL_COMPLETE)
6681 		goto bailout_no_done;
6682 
6683 	/*
6684 	 * If the initiator sent us more than one page, parse the next one.
6685 	 */
6686 	if (*len_left > 0)
6687 		goto do_next_page;
6688 
6689 	ctl_set_success(ctsio);
6690 	free(ctsio->kern_data_ptr, M_CTL);
6691 	ctl_done((union ctl_io *)ctsio);
6692 
6693 bailout_no_done:
6694 
6695 	return (CTL_RETVAL_COMPLETE);
6696 
6697 }
6698 
6699 int
6700 ctl_mode_select(struct ctl_scsiio *ctsio)
6701 {
6702 	int param_len, pf, sp;
6703 	int header_size, bd_len;
6704 	int len_left, len_used;
6705 	struct ctl_page_index *page_index;
6706 	struct ctl_lun *lun;
6707 	int control_dev, page_len;
6708 	union ctl_modepage_info *modepage_info;
6709 	int retval;
6710 
6711 	pf = 0;
6712 	sp = 0;
6713 	page_len = 0;
6714 	len_used = 0;
6715 	len_left = 0;
6716 	retval = 0;
6717 	bd_len = 0;
6718 	page_index = NULL;
6719 
6720 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6721 
6722 	if (lun->be_lun->lun_type != T_DIRECT)
6723 		control_dev = 1;
6724 	else
6725 		control_dev = 0;
6726 
6727 	switch (ctsio->cdb[0]) {
6728 	case MODE_SELECT_6: {
6729 		struct scsi_mode_select_6 *cdb;
6730 
6731 		cdb = (struct scsi_mode_select_6 *)ctsio->cdb;
6732 
6733 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6734 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6735 
6736 		param_len = cdb->length;
6737 		header_size = sizeof(struct scsi_mode_header_6);
6738 		break;
6739 	}
6740 	case MODE_SELECT_10: {
6741 		struct scsi_mode_select_10 *cdb;
6742 
6743 		cdb = (struct scsi_mode_select_10 *)ctsio->cdb;
6744 
6745 		pf = (cdb->byte2 & SMS_PF) ? 1 : 0;
6746 		sp = (cdb->byte2 & SMS_SP) ? 1 : 0;
6747 
6748 		param_len = scsi_2btoul(cdb->length);
6749 		header_size = sizeof(struct scsi_mode_header_10);
6750 		break;
6751 	}
6752 	default:
6753 		ctl_set_invalid_opcode(ctsio);
6754 		ctl_done((union ctl_io *)ctsio);
6755 		return (CTL_RETVAL_COMPLETE);
6756 		break; /* NOTREACHED */
6757 	}
6758 
6759 	/*
6760 	 * From SPC-3:
6761 	 * "A parameter list length of zero indicates that the Data-Out Buffer
6762 	 * shall be empty. This condition shall not be considered as an error."
6763 	 */
6764 	if (param_len == 0) {
6765 		ctl_set_success(ctsio);
6766 		ctl_done((union ctl_io *)ctsio);
6767 		return (CTL_RETVAL_COMPLETE);
6768 	}
6769 
6770 	/*
6771 	 * Since we'll hit this the first time through, prior to
6772 	 * allocation, we don't need to free a data buffer here.
6773 	 */
6774 	if (param_len < header_size) {
6775 		ctl_set_param_len_error(ctsio);
6776 		ctl_done((union ctl_io *)ctsio);
6777 		return (CTL_RETVAL_COMPLETE);
6778 	}
6779 
6780 	/*
6781 	 * Allocate the data buffer and grab the user's data.  In theory,
6782 	 * we shouldn't have to sanity check the parameter list length here
6783 	 * because the maximum size is 64K.  We should be able to malloc
6784 	 * that much without too many problems.
6785 	 */
6786 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
6787 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
6788 		ctsio->kern_data_len = param_len;
6789 		ctsio->kern_total_len = param_len;
6790 		ctsio->kern_data_resid = 0;
6791 		ctsio->kern_rel_offset = 0;
6792 		ctsio->kern_sg_entries = 0;
6793 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
6794 		ctsio->be_move_done = ctl_config_move_done;
6795 		ctl_datamove((union ctl_io *)ctsio);
6796 
6797 		return (CTL_RETVAL_COMPLETE);
6798 	}
6799 
6800 	switch (ctsio->cdb[0]) {
6801 	case MODE_SELECT_6: {
6802 		struct scsi_mode_header_6 *mh6;
6803 
6804 		mh6 = (struct scsi_mode_header_6 *)ctsio->kern_data_ptr;
6805 		bd_len = mh6->blk_desc_len;
6806 		break;
6807 	}
6808 	case MODE_SELECT_10: {
6809 		struct scsi_mode_header_10 *mh10;
6810 
6811 		mh10 = (struct scsi_mode_header_10 *)ctsio->kern_data_ptr;
6812 		bd_len = scsi_2btoul(mh10->blk_desc_len);
6813 		break;
6814 	}
6815 	default:
6816 		panic("Invalid CDB type %#x", ctsio->cdb[0]);
6817 		break;
6818 	}
6819 
6820 	if (param_len < (header_size + bd_len)) {
6821 		free(ctsio->kern_data_ptr, M_CTL);
6822 		ctl_set_param_len_error(ctsio);
6823 		ctl_done((union ctl_io *)ctsio);
6824 		return (CTL_RETVAL_COMPLETE);
6825 	}
6826 
6827 	/*
6828 	 * Set the IO_CONT flag, so that if this I/O gets passed to
6829 	 * ctl_config_write_done(), it'll get passed back to
6830 	 * ctl_do_mode_select() for further processing, or completion if
6831 	 * we're all done.
6832 	 */
6833 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
6834 	ctsio->io_cont = ctl_do_mode_select;
6835 
6836 	modepage_info = (union ctl_modepage_info *)
6837 		ctsio->io_hdr.ctl_private[CTL_PRIV_MODEPAGE].bytes;
6838 
6839 	memset(modepage_info, 0, sizeof(*modepage_info));
6840 
6841 	len_left = param_len - header_size - bd_len;
6842 	len_used = header_size + bd_len;
6843 
6844 	modepage_info->header.len_left = len_left;
6845 	modepage_info->header.len_used = len_used;
6846 
6847 	return (ctl_do_mode_select((union ctl_io *)ctsio));
6848 }
6849 
6850 int
6851 ctl_mode_sense(struct ctl_scsiio *ctsio)
6852 {
6853 	struct ctl_lun *lun;
6854 	int pc, page_code, dbd, llba, subpage;
6855 	int alloc_len, page_len, header_len, total_len;
6856 	struct scsi_mode_block_descr *block_desc;
6857 	struct ctl_page_index *page_index;
6858 	int control_dev;
6859 
6860 	dbd = 0;
6861 	llba = 0;
6862 	block_desc = NULL;
6863 	page_index = NULL;
6864 
6865 	CTL_DEBUG_PRINT(("ctl_mode_sense\n"));
6866 
6867 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
6868 
6869 	if (lun->be_lun->lun_type != T_DIRECT)
6870 		control_dev = 1;
6871 	else
6872 		control_dev = 0;
6873 
6874 	if (lun->flags & CTL_LUN_PR_RESERVED) {
6875 		uint32_t residx;
6876 
6877 		/*
6878 		 * XXX KDM need a lock here.
6879 		 */
6880 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
6881 		if ((lun->res_type == SPR_TYPE_EX_AC
6882 		  && residx != lun->pr_res_idx)
6883 		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
6884 		   || lun->res_type == SPR_TYPE_EX_AC_AR)
6885 		  && !lun->per_res[residx].registered)) {
6886 			ctl_set_reservation_conflict(ctsio);
6887 			ctl_done((union ctl_io *)ctsio);
6888 			return (CTL_RETVAL_COMPLETE);
6889 		}
6890 	}
6891 
6892 	switch (ctsio->cdb[0]) {
6893 	case MODE_SENSE_6: {
6894 		struct scsi_mode_sense_6 *cdb;
6895 
6896 		cdb = (struct scsi_mode_sense_6 *)ctsio->cdb;
6897 
6898 		header_len = sizeof(struct scsi_mode_hdr_6);
6899 		if (cdb->byte2 & SMS_DBD)
6900 			dbd = 1;
6901 		else
6902 			header_len += sizeof(struct scsi_mode_block_descr);
6903 
6904 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6905 		page_code = cdb->page & SMS_PAGE_CODE;
6906 		subpage = cdb->subpage;
6907 		alloc_len = cdb->length;
6908 		break;
6909 	}
6910 	case MODE_SENSE_10: {
6911 		struct scsi_mode_sense_10 *cdb;
6912 
6913 		cdb = (struct scsi_mode_sense_10 *)ctsio->cdb;
6914 
6915 		header_len = sizeof(struct scsi_mode_hdr_10);
6916 
6917 		if (cdb->byte2 & SMS_DBD)
6918 			dbd = 1;
6919 		else
6920 			header_len += sizeof(struct scsi_mode_block_descr);
6921 		if (cdb->byte2 & SMS10_LLBAA)
6922 			llba = 1;
6923 		pc = (cdb->page & SMS_PAGE_CTRL_MASK) >> 6;
6924 		page_code = cdb->page & SMS_PAGE_CODE;
6925 		subpage = cdb->subpage;
6926 		alloc_len = scsi_2btoul(cdb->length);
6927 		break;
6928 	}
6929 	default:
6930 		ctl_set_invalid_opcode(ctsio);
6931 		ctl_done((union ctl_io *)ctsio);
6932 		return (CTL_RETVAL_COMPLETE);
6933 		break; /* NOTREACHED */
6934 	}
6935 
6936 	/*
6937 	 * We have to make a first pass through to calculate the size of
6938 	 * the pages that match the user's query.  Then we allocate enough
6939 	 * memory to hold it, and actually copy the data into the buffer.
6940 	 */
6941 	switch (page_code) {
6942 	case SMS_ALL_PAGES_PAGE: {
6943 		int i;
6944 
6945 		page_len = 0;
6946 
6947 		/*
6948 		 * At the moment, values other than 0 and 0xff here are
6949 		 * reserved according to SPC-3.
6950 		 */
6951 		if ((subpage != SMS_SUBPAGE_PAGE_0)
6952 		 && (subpage != SMS_SUBPAGE_ALL)) {
6953 			ctl_set_invalid_field(ctsio,
6954 					      /*sks_valid*/ 1,
6955 					      /*command*/ 1,
6956 					      /*field*/ 3,
6957 					      /*bit_valid*/ 0,
6958 					      /*bit*/ 0);
6959 			ctl_done((union ctl_io *)ctsio);
6960 			return (CTL_RETVAL_COMPLETE);
6961 		}
6962 
6963 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6964 			if ((control_dev != 0)
6965 			 && (lun->mode_pages.index[i].page_flags &
6966 			     CTL_PAGE_FLAG_DISK_ONLY))
6967 				continue;
6968 
6969 			/*
6970 			 * We don't use this subpage if the user didn't
6971 			 * request all subpages.
6972 			 */
6973 			if ((lun->mode_pages.index[i].subpage != 0)
6974 			 && (subpage == SMS_SUBPAGE_PAGE_0))
6975 				continue;
6976 
6977 #if 0
6978 			printf("found page %#x len %d\n",
6979 			       lun->mode_pages.index[i].page_code &
6980 			       SMPH_PC_MASK,
6981 			       lun->mode_pages.index[i].page_len);
6982 #endif
6983 			page_len += lun->mode_pages.index[i].page_len;
6984 		}
6985 		break;
6986 	}
6987 	default: {
6988 		int i;
6989 
6990 		page_len = 0;
6991 
6992 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
6993 			/* Look for the right page code */
6994 			if ((lun->mode_pages.index[i].page_code &
6995 			     SMPH_PC_MASK) != page_code)
6996 				continue;
6997 
6998 			/* Look for the right subpage or the subpage wildcard*/
6999 			if ((lun->mode_pages.index[i].subpage != subpage)
7000 			 && (subpage != SMS_SUBPAGE_ALL))
7001 				continue;
7002 
7003 			/* Make sure the page is supported for this dev type */
7004 			if ((control_dev != 0)
7005 			 && (lun->mode_pages.index[i].page_flags &
7006 			     CTL_PAGE_FLAG_DISK_ONLY))
7007 				continue;
7008 
7009 #if 0
7010 			printf("found page %#x len %d\n",
7011 			       lun->mode_pages.index[i].page_code &
7012 			       SMPH_PC_MASK,
7013 			       lun->mode_pages.index[i].page_len);
7014 #endif
7015 
7016 			page_len += lun->mode_pages.index[i].page_len;
7017 		}
7018 
7019 		if (page_len == 0) {
7020 			ctl_set_invalid_field(ctsio,
7021 					      /*sks_valid*/ 1,
7022 					      /*command*/ 1,
7023 					      /*field*/ 2,
7024 					      /*bit_valid*/ 1,
7025 					      /*bit*/ 5);
7026 			ctl_done((union ctl_io *)ctsio);
7027 			return (CTL_RETVAL_COMPLETE);
7028 		}
7029 		break;
7030 	}
7031 	}
7032 
7033 	total_len = header_len + page_len;
7034 #if 0
7035 	printf("header_len = %d, page_len = %d, total_len = %d\n",
7036 	       header_len, page_len, total_len);
7037 #endif
7038 
7039 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7040 	ctsio->kern_sg_entries = 0;
7041 	ctsio->kern_data_resid = 0;
7042 	ctsio->kern_rel_offset = 0;
7043 	if (total_len < alloc_len) {
7044 		ctsio->residual = alloc_len - total_len;
7045 		ctsio->kern_data_len = total_len;
7046 		ctsio->kern_total_len = total_len;
7047 	} else {
7048 		ctsio->residual = 0;
7049 		ctsio->kern_data_len = alloc_len;
7050 		ctsio->kern_total_len = alloc_len;
7051 	}
7052 
7053 	switch (ctsio->cdb[0]) {
7054 	case MODE_SENSE_6: {
7055 		struct scsi_mode_hdr_6 *header;
7056 
7057 		header = (struct scsi_mode_hdr_6 *)ctsio->kern_data_ptr;
7058 
7059 		header->datalen = ctl_min(total_len - 1, 254);
7060 		if (control_dev == 0) {
7061 			header->dev_specific = 0x10; /* DPOFUA */
7062 			if ((lun->flags & CTL_LUN_READONLY) ||
7063 			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
7064 			    .eca_and_aen & SCP_SWP) != 0)
7065 				    header->dev_specific |= 0x80; /* WP */
7066 		}
7067 		if (dbd)
7068 			header->block_descr_len = 0;
7069 		else
7070 			header->block_descr_len =
7071 				sizeof(struct scsi_mode_block_descr);
7072 		block_desc = (struct scsi_mode_block_descr *)&header[1];
7073 		break;
7074 	}
7075 	case MODE_SENSE_10: {
7076 		struct scsi_mode_hdr_10 *header;
7077 		int datalen;
7078 
7079 		header = (struct scsi_mode_hdr_10 *)ctsio->kern_data_ptr;
7080 
7081 		datalen = ctl_min(total_len - 2, 65533);
7082 		scsi_ulto2b(datalen, header->datalen);
7083 		if (control_dev == 0) {
7084 			header->dev_specific = 0x10; /* DPOFUA */
7085 			if ((lun->flags & CTL_LUN_READONLY) ||
7086 			    (lun->mode_pages.control_page[CTL_PAGE_CURRENT]
7087 			    .eca_and_aen & SCP_SWP) != 0)
7088 				    header->dev_specific |= 0x80; /* WP */
7089 		}
7090 		if (dbd)
7091 			scsi_ulto2b(0, header->block_descr_len);
7092 		else
7093 			scsi_ulto2b(sizeof(struct scsi_mode_block_descr),
7094 				    header->block_descr_len);
7095 		block_desc = (struct scsi_mode_block_descr *)&header[1];
7096 		break;
7097 	}
7098 	default:
7099 		panic("invalid CDB type %#x", ctsio->cdb[0]);
7100 		break; /* NOTREACHED */
7101 	}
7102 
7103 	/*
7104 	 * If we've got a disk, use its blocksize in the block
7105 	 * descriptor.  Otherwise, just set it to 0.
7106 	 */
7107 	if (dbd == 0) {
7108 		if (control_dev == 0)
7109 			scsi_ulto3b(lun->be_lun->blocksize,
7110 				    block_desc->block_len);
7111 		else
7112 			scsi_ulto3b(0, block_desc->block_len);
7113 	}
7114 
7115 	switch (page_code) {
7116 	case SMS_ALL_PAGES_PAGE: {
7117 		int i, data_used;
7118 
7119 		data_used = header_len;
7120 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7121 			struct ctl_page_index *page_index;
7122 
7123 			page_index = &lun->mode_pages.index[i];
7124 
7125 			if ((control_dev != 0)
7126 			 && (page_index->page_flags &
7127 			    CTL_PAGE_FLAG_DISK_ONLY))
7128 				continue;
7129 
7130 			/*
7131 			 * We don't use this subpage if the user didn't
7132 			 * request all subpages.  We already checked (above)
7133 			 * to make sure the user only specified a subpage
7134 			 * of 0 or 0xff in the SMS_ALL_PAGES_PAGE case.
7135 			 */
7136 			if ((page_index->subpage != 0)
7137 			 && (subpage == SMS_SUBPAGE_PAGE_0))
7138 				continue;
7139 
7140 			/*
7141 			 * Call the handler, if it exists, to update the
7142 			 * page to the latest values.
7143 			 */
7144 			if (page_index->sense_handler != NULL)
7145 				page_index->sense_handler(ctsio, page_index,pc);
7146 
7147 			memcpy(ctsio->kern_data_ptr + data_used,
7148 			       page_index->page_data +
7149 			       (page_index->page_len * pc),
7150 			       page_index->page_len);
7151 			data_used += page_index->page_len;
7152 		}
7153 		break;
7154 	}
7155 	default: {
7156 		int i, data_used;
7157 
7158 		data_used = header_len;
7159 
7160 		for (i = 0; i < CTL_NUM_MODE_PAGES; i++) {
7161 			struct ctl_page_index *page_index;
7162 
7163 			page_index = &lun->mode_pages.index[i];
7164 
7165 			/* Look for the right page code */
7166 			if ((page_index->page_code & SMPH_PC_MASK) != page_code)
7167 				continue;
7168 
7169 			/* Look for the right subpage or the subpage wildcard*/
7170 			if ((page_index->subpage != subpage)
7171 			 && (subpage != SMS_SUBPAGE_ALL))
7172 				continue;
7173 
7174 			/* Make sure the page is supported for this dev type */
7175 			if ((control_dev != 0)
7176 			 && (page_index->page_flags &
7177 			     CTL_PAGE_FLAG_DISK_ONLY))
7178 				continue;
7179 
7180 			/*
7181 			 * Call the handler, if it exists, to update the
7182 			 * page to the latest values.
7183 			 */
7184 			if (page_index->sense_handler != NULL)
7185 				page_index->sense_handler(ctsio, page_index,pc);
7186 
7187 			memcpy(ctsio->kern_data_ptr + data_used,
7188 			       page_index->page_data +
7189 			       (page_index->page_len * pc),
7190 			       page_index->page_len);
7191 			data_used += page_index->page_len;
7192 		}
7193 		break;
7194 	}
7195 	}
7196 
7197 	ctsio->scsi_status = SCSI_STATUS_OK;
7198 
7199 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7200 	ctsio->be_move_done = ctl_config_move_done;
7201 	ctl_datamove((union ctl_io *)ctsio);
7202 
7203 	return (CTL_RETVAL_COMPLETE);
7204 }
7205 
7206 int
7207 ctl_read_capacity(struct ctl_scsiio *ctsio)
7208 {
7209 	struct scsi_read_capacity *cdb;
7210 	struct scsi_read_capacity_data *data;
7211 	struct ctl_lun *lun;
7212 	uint32_t lba;
7213 
7214 	CTL_DEBUG_PRINT(("ctl_read_capacity\n"));
7215 
7216 	cdb = (struct scsi_read_capacity *)ctsio->cdb;
7217 
7218 	lba = scsi_4btoul(cdb->addr);
7219 	if (((cdb->pmi & SRC_PMI) == 0)
7220 	 && (lba != 0)) {
7221 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7222 				      /*sks_valid*/ 1,
7223 				      /*command*/ 1,
7224 				      /*field*/ 2,
7225 				      /*bit_valid*/ 0,
7226 				      /*bit*/ 0);
7227 		ctl_done((union ctl_io *)ctsio);
7228 		return (CTL_RETVAL_COMPLETE);
7229 	}
7230 
7231 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7232 
7233 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7234 	data = (struct scsi_read_capacity_data *)ctsio->kern_data_ptr;
7235 	ctsio->residual = 0;
7236 	ctsio->kern_data_len = sizeof(*data);
7237 	ctsio->kern_total_len = sizeof(*data);
7238 	ctsio->kern_data_resid = 0;
7239 	ctsio->kern_rel_offset = 0;
7240 	ctsio->kern_sg_entries = 0;
7241 
7242 	/*
7243 	 * If the maximum LBA is greater than 0xfffffffe, the user must
7244 	 * issue a SERVICE ACTION IN (16) command, with the read capacity
7245 	 * serivce action set.
7246 	 */
7247 	if (lun->be_lun->maxlba > 0xfffffffe)
7248 		scsi_ulto4b(0xffffffff, data->addr);
7249 	else
7250 		scsi_ulto4b(lun->be_lun->maxlba, data->addr);
7251 
7252 	/*
7253 	 * XXX KDM this may not be 512 bytes...
7254 	 */
7255 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7256 
7257 	ctsio->scsi_status = SCSI_STATUS_OK;
7258 
7259 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7260 	ctsio->be_move_done = ctl_config_move_done;
7261 	ctl_datamove((union ctl_io *)ctsio);
7262 
7263 	return (CTL_RETVAL_COMPLETE);
7264 }
7265 
7266 int
7267 ctl_read_capacity_16(struct ctl_scsiio *ctsio)
7268 {
7269 	struct scsi_read_capacity_16 *cdb;
7270 	struct scsi_read_capacity_data_long *data;
7271 	struct ctl_lun *lun;
7272 	uint64_t lba;
7273 	uint32_t alloc_len;
7274 
7275 	CTL_DEBUG_PRINT(("ctl_read_capacity_16\n"));
7276 
7277 	cdb = (struct scsi_read_capacity_16 *)ctsio->cdb;
7278 
7279 	alloc_len = scsi_4btoul(cdb->alloc_len);
7280 	lba = scsi_8btou64(cdb->addr);
7281 
7282 	if ((cdb->reladr & SRC16_PMI)
7283 	 && (lba != 0)) {
7284 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7285 				      /*sks_valid*/ 1,
7286 				      /*command*/ 1,
7287 				      /*field*/ 2,
7288 				      /*bit_valid*/ 0,
7289 				      /*bit*/ 0);
7290 		ctl_done((union ctl_io *)ctsio);
7291 		return (CTL_RETVAL_COMPLETE);
7292 	}
7293 
7294 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7295 
7296 	ctsio->kern_data_ptr = malloc(sizeof(*data), M_CTL, M_WAITOK | M_ZERO);
7297 	data = (struct scsi_read_capacity_data_long *)ctsio->kern_data_ptr;
7298 
7299 	if (sizeof(*data) < alloc_len) {
7300 		ctsio->residual = alloc_len - sizeof(*data);
7301 		ctsio->kern_data_len = sizeof(*data);
7302 		ctsio->kern_total_len = sizeof(*data);
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 	ctsio->kern_sg_entries = 0;
7311 
7312 	scsi_u64to8b(lun->be_lun->maxlba, data->addr);
7313 	/* XXX KDM this may not be 512 bytes... */
7314 	scsi_ulto4b(lun->be_lun->blocksize, data->length);
7315 	data->prot_lbppbe = lun->be_lun->pblockexp & SRC16_LBPPBE;
7316 	scsi_ulto2b(lun->be_lun->pblockoff & SRC16_LALBA_A, data->lalba_lbp);
7317 	if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP)
7318 		data->lalba_lbp[0] |= SRC16_LBPME | SRC16_LBPRZ;
7319 
7320 	ctsio->scsi_status = SCSI_STATUS_OK;
7321 
7322 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7323 	ctsio->be_move_done = ctl_config_move_done;
7324 	ctl_datamove((union ctl_io *)ctsio);
7325 
7326 	return (CTL_RETVAL_COMPLETE);
7327 }
7328 
7329 int
7330 ctl_report_tagret_port_groups(struct ctl_scsiio *ctsio)
7331 {
7332 	struct scsi_maintenance_in *cdb;
7333 	int retval;
7334 	int alloc_len, ext, total_len = 0, g, p, pc, pg;
7335 	int num_target_port_groups, num_target_ports, single;
7336 	struct ctl_lun *lun;
7337 	struct ctl_softc *softc;
7338 	struct ctl_port *port;
7339 	struct scsi_target_group_data *rtg_ptr;
7340 	struct scsi_target_group_data_extended *rtg_ext_ptr;
7341 	struct scsi_target_port_group_descriptor *tpg_desc;
7342 
7343 	CTL_DEBUG_PRINT(("ctl_report_tagret_port_groups\n"));
7344 
7345 	cdb = (struct scsi_maintenance_in *)ctsio->cdb;
7346 	softc = control_softc;
7347 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7348 
7349 	retval = CTL_RETVAL_COMPLETE;
7350 
7351 	switch (cdb->byte2 & STG_PDF_MASK) {
7352 	case STG_PDF_LENGTH:
7353 		ext = 0;
7354 		break;
7355 	case STG_PDF_EXTENDED:
7356 		ext = 1;
7357 		break;
7358 	default:
7359 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7360 				      /*sks_valid*/ 1,
7361 				      /*command*/ 1,
7362 				      /*field*/ 2,
7363 				      /*bit_valid*/ 1,
7364 				      /*bit*/ 5);
7365 		ctl_done((union ctl_io *)ctsio);
7366 		return(retval);
7367 	}
7368 
7369 	single = ctl_is_single;
7370 	if (single)
7371 		num_target_port_groups = 1;
7372 	else
7373 		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
7374 	num_target_ports = 0;
7375 	mtx_lock(&softc->ctl_lock);
7376 	STAILQ_FOREACH(port, &softc->port_list, links) {
7377 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7378 			continue;
7379 		if (ctl_map_lun_back(port->targ_port, lun->lun) >= CTL_MAX_LUNS)
7380 			continue;
7381 		num_target_ports++;
7382 	}
7383 	mtx_unlock(&softc->ctl_lock);
7384 
7385 	if (ext)
7386 		total_len = sizeof(struct scsi_target_group_data_extended);
7387 	else
7388 		total_len = sizeof(struct scsi_target_group_data);
7389 	total_len += sizeof(struct scsi_target_port_group_descriptor) *
7390 		num_target_port_groups +
7391 	    sizeof(struct scsi_target_port_descriptor) *
7392 		num_target_ports * num_target_port_groups;
7393 
7394 	alloc_len = scsi_4btoul(cdb->length);
7395 
7396 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7397 
7398 	ctsio->kern_sg_entries = 0;
7399 
7400 	if (total_len < alloc_len) {
7401 		ctsio->residual = alloc_len - total_len;
7402 		ctsio->kern_data_len = total_len;
7403 		ctsio->kern_total_len = total_len;
7404 	} else {
7405 		ctsio->residual = 0;
7406 		ctsio->kern_data_len = alloc_len;
7407 		ctsio->kern_total_len = alloc_len;
7408 	}
7409 	ctsio->kern_data_resid = 0;
7410 	ctsio->kern_rel_offset = 0;
7411 
7412 	if (ext) {
7413 		rtg_ext_ptr = (struct scsi_target_group_data_extended *)
7414 		    ctsio->kern_data_ptr;
7415 		scsi_ulto4b(total_len - 4, rtg_ext_ptr->length);
7416 		rtg_ext_ptr->format_type = 0x10;
7417 		rtg_ext_ptr->implicit_transition_time = 0;
7418 		tpg_desc = &rtg_ext_ptr->groups[0];
7419 	} else {
7420 		rtg_ptr = (struct scsi_target_group_data *)
7421 		    ctsio->kern_data_ptr;
7422 		scsi_ulto4b(total_len - 4, rtg_ptr->length);
7423 		tpg_desc = &rtg_ptr->groups[0];
7424 	}
7425 
7426 	pg = ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS;
7427 	mtx_lock(&softc->ctl_lock);
7428 	for (g = 0; g < num_target_port_groups; g++) {
7429 		if (g == pg)
7430 			tpg_desc->pref_state = TPG_PRIMARY |
7431 			    TPG_ASYMMETRIC_ACCESS_OPTIMIZED;
7432 		else
7433 			tpg_desc->pref_state =
7434 			    TPG_ASYMMETRIC_ACCESS_NONOPTIMIZED;
7435 		tpg_desc->support = TPG_AO_SUP;
7436 		if (!single)
7437 			tpg_desc->support |= TPG_AN_SUP;
7438 		scsi_ulto2b(g + 1, tpg_desc->target_port_group);
7439 		tpg_desc->status = TPG_IMPLICIT;
7440 		pc = 0;
7441 		STAILQ_FOREACH(port, &softc->port_list, links) {
7442 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
7443 				continue;
7444 			if (ctl_map_lun_back(port->targ_port, lun->lun) >=
7445 			    CTL_MAX_LUNS)
7446 				continue;
7447 			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
7448 			scsi_ulto2b(p, tpg_desc->descriptors[pc].
7449 			    relative_target_port_identifier);
7450 			pc++;
7451 		}
7452 		tpg_desc->target_port_count = pc;
7453 		tpg_desc = (struct scsi_target_port_group_descriptor *)
7454 		    &tpg_desc->descriptors[pc];
7455 	}
7456 	mtx_unlock(&softc->ctl_lock);
7457 
7458 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7459 	ctsio->be_move_done = ctl_config_move_done;
7460 
7461 	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
7462 			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
7463 			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
7464 			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
7465 			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
7466 
7467 	ctl_datamove((union ctl_io *)ctsio);
7468 	return(retval);
7469 }
7470 
7471 int
7472 ctl_report_supported_opcodes(struct ctl_scsiio *ctsio)
7473 {
7474 	struct ctl_lun *lun;
7475 	struct scsi_report_supported_opcodes *cdb;
7476 	const struct ctl_cmd_entry *entry, *sentry;
7477 	struct scsi_report_supported_opcodes_all *all;
7478 	struct scsi_report_supported_opcodes_descr *descr;
7479 	struct scsi_report_supported_opcodes_one *one;
7480 	int retval;
7481 	int alloc_len, total_len;
7482 	int opcode, service_action, i, j, num;
7483 
7484 	CTL_DEBUG_PRINT(("ctl_report_supported_opcodes\n"));
7485 
7486 	cdb = (struct scsi_report_supported_opcodes *)ctsio->cdb;
7487 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7488 
7489 	retval = CTL_RETVAL_COMPLETE;
7490 
7491 	opcode = cdb->requested_opcode;
7492 	service_action = scsi_2btoul(cdb->requested_service_action);
7493 	switch (cdb->options & RSO_OPTIONS_MASK) {
7494 	case RSO_OPTIONS_ALL:
7495 		num = 0;
7496 		for (i = 0; i < 256; i++) {
7497 			entry = &ctl_cmd_table[i];
7498 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7499 				for (j = 0; j < 32; j++) {
7500 					sentry = &((const struct ctl_cmd_entry *)
7501 					    entry->execute)[j];
7502 					if (ctl_cmd_applicable(
7503 					    lun->be_lun->lun_type, sentry))
7504 						num++;
7505 				}
7506 			} else {
7507 				if (ctl_cmd_applicable(lun->be_lun->lun_type,
7508 				    entry))
7509 					num++;
7510 			}
7511 		}
7512 		total_len = sizeof(struct scsi_report_supported_opcodes_all) +
7513 		    num * sizeof(struct scsi_report_supported_opcodes_descr);
7514 		break;
7515 	case RSO_OPTIONS_OC:
7516 		if (ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) {
7517 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7518 					      /*sks_valid*/ 1,
7519 					      /*command*/ 1,
7520 					      /*field*/ 2,
7521 					      /*bit_valid*/ 1,
7522 					      /*bit*/ 2);
7523 			ctl_done((union ctl_io *)ctsio);
7524 			return (CTL_RETVAL_COMPLETE);
7525 		}
7526 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7527 		break;
7528 	case RSO_OPTIONS_OC_SA:
7529 		if ((ctl_cmd_table[opcode].flags & CTL_CMD_FLAG_SA5) == 0 ||
7530 		    service_action >= 32) {
7531 			ctl_set_invalid_field(/*ctsio*/ ctsio,
7532 					      /*sks_valid*/ 1,
7533 					      /*command*/ 1,
7534 					      /*field*/ 2,
7535 					      /*bit_valid*/ 1,
7536 					      /*bit*/ 2);
7537 			ctl_done((union ctl_io *)ctsio);
7538 			return (CTL_RETVAL_COMPLETE);
7539 		}
7540 		total_len = sizeof(struct scsi_report_supported_opcodes_one) + 32;
7541 		break;
7542 	default:
7543 		ctl_set_invalid_field(/*ctsio*/ ctsio,
7544 				      /*sks_valid*/ 1,
7545 				      /*command*/ 1,
7546 				      /*field*/ 2,
7547 				      /*bit_valid*/ 1,
7548 				      /*bit*/ 2);
7549 		ctl_done((union ctl_io *)ctsio);
7550 		return (CTL_RETVAL_COMPLETE);
7551 	}
7552 
7553 	alloc_len = scsi_4btoul(cdb->length);
7554 
7555 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7556 
7557 	ctsio->kern_sg_entries = 0;
7558 
7559 	if (total_len < alloc_len) {
7560 		ctsio->residual = alloc_len - total_len;
7561 		ctsio->kern_data_len = total_len;
7562 		ctsio->kern_total_len = total_len;
7563 	} else {
7564 		ctsio->residual = 0;
7565 		ctsio->kern_data_len = alloc_len;
7566 		ctsio->kern_total_len = alloc_len;
7567 	}
7568 	ctsio->kern_data_resid = 0;
7569 	ctsio->kern_rel_offset = 0;
7570 
7571 	switch (cdb->options & RSO_OPTIONS_MASK) {
7572 	case RSO_OPTIONS_ALL:
7573 		all = (struct scsi_report_supported_opcodes_all *)
7574 		    ctsio->kern_data_ptr;
7575 		num = 0;
7576 		for (i = 0; i < 256; i++) {
7577 			entry = &ctl_cmd_table[i];
7578 			if (entry->flags & CTL_CMD_FLAG_SA5) {
7579 				for (j = 0; j < 32; j++) {
7580 					sentry = &((const struct ctl_cmd_entry *)
7581 					    entry->execute)[j];
7582 					if (!ctl_cmd_applicable(
7583 					    lun->be_lun->lun_type, sentry))
7584 						continue;
7585 					descr = &all->descr[num++];
7586 					descr->opcode = i;
7587 					scsi_ulto2b(j, descr->service_action);
7588 					descr->flags = RSO_SERVACTV;
7589 					scsi_ulto2b(sentry->length,
7590 					    descr->cdb_length);
7591 				}
7592 			} else {
7593 				if (!ctl_cmd_applicable(lun->be_lun->lun_type,
7594 				    entry))
7595 					continue;
7596 				descr = &all->descr[num++];
7597 				descr->opcode = i;
7598 				scsi_ulto2b(0, descr->service_action);
7599 				descr->flags = 0;
7600 				scsi_ulto2b(entry->length, descr->cdb_length);
7601 			}
7602 		}
7603 		scsi_ulto4b(
7604 		    num * sizeof(struct scsi_report_supported_opcodes_descr),
7605 		    all->length);
7606 		break;
7607 	case RSO_OPTIONS_OC:
7608 		one = (struct scsi_report_supported_opcodes_one *)
7609 		    ctsio->kern_data_ptr;
7610 		entry = &ctl_cmd_table[opcode];
7611 		goto fill_one;
7612 	case RSO_OPTIONS_OC_SA:
7613 		one = (struct scsi_report_supported_opcodes_one *)
7614 		    ctsio->kern_data_ptr;
7615 		entry = &ctl_cmd_table[opcode];
7616 		entry = &((const struct ctl_cmd_entry *)
7617 		    entry->execute)[service_action];
7618 fill_one:
7619 		if (ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
7620 			one->support = 3;
7621 			scsi_ulto2b(entry->length, one->cdb_length);
7622 			one->cdb_usage[0] = opcode;
7623 			memcpy(&one->cdb_usage[1], entry->usage,
7624 			    entry->length - 1);
7625 		} else
7626 			one->support = 1;
7627 		break;
7628 	}
7629 
7630 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7631 	ctsio->be_move_done = ctl_config_move_done;
7632 
7633 	ctl_datamove((union ctl_io *)ctsio);
7634 	return(retval);
7635 }
7636 
7637 int
7638 ctl_report_supported_tmf(struct ctl_scsiio *ctsio)
7639 {
7640 	struct ctl_lun *lun;
7641 	struct scsi_report_supported_tmf *cdb;
7642 	struct scsi_report_supported_tmf_data *data;
7643 	int retval;
7644 	int alloc_len, total_len;
7645 
7646 	CTL_DEBUG_PRINT(("ctl_report_supported_tmf\n"));
7647 
7648 	cdb = (struct scsi_report_supported_tmf *)ctsio->cdb;
7649 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7650 
7651 	retval = CTL_RETVAL_COMPLETE;
7652 
7653 	total_len = sizeof(struct scsi_report_supported_tmf_data);
7654 	alloc_len = scsi_4btoul(cdb->length);
7655 
7656 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7657 
7658 	ctsio->kern_sg_entries = 0;
7659 
7660 	if (total_len < alloc_len) {
7661 		ctsio->residual = alloc_len - total_len;
7662 		ctsio->kern_data_len = total_len;
7663 		ctsio->kern_total_len = total_len;
7664 	} else {
7665 		ctsio->residual = 0;
7666 		ctsio->kern_data_len = alloc_len;
7667 		ctsio->kern_total_len = alloc_len;
7668 	}
7669 	ctsio->kern_data_resid = 0;
7670 	ctsio->kern_rel_offset = 0;
7671 
7672 	data = (struct scsi_report_supported_tmf_data *)ctsio->kern_data_ptr;
7673 	data->byte1 |= RST_ATS | RST_ATSS | RST_CTSS | RST_LURS | RST_TRS;
7674 	data->byte2 |= RST_ITNRS;
7675 
7676 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7677 	ctsio->be_move_done = ctl_config_move_done;
7678 
7679 	ctl_datamove((union ctl_io *)ctsio);
7680 	return (retval);
7681 }
7682 
7683 int
7684 ctl_report_timestamp(struct ctl_scsiio *ctsio)
7685 {
7686 	struct ctl_lun *lun;
7687 	struct scsi_report_timestamp *cdb;
7688 	struct scsi_report_timestamp_data *data;
7689 	struct timeval tv;
7690 	int64_t timestamp;
7691 	int retval;
7692 	int alloc_len, total_len;
7693 
7694 	CTL_DEBUG_PRINT(("ctl_report_timestamp\n"));
7695 
7696 	cdb = (struct scsi_report_timestamp *)ctsio->cdb;
7697 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7698 
7699 	retval = CTL_RETVAL_COMPLETE;
7700 
7701 	total_len = sizeof(struct scsi_report_timestamp_data);
7702 	alloc_len = scsi_4btoul(cdb->length);
7703 
7704 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7705 
7706 	ctsio->kern_sg_entries = 0;
7707 
7708 	if (total_len < alloc_len) {
7709 		ctsio->residual = alloc_len - total_len;
7710 		ctsio->kern_data_len = total_len;
7711 		ctsio->kern_total_len = total_len;
7712 	} else {
7713 		ctsio->residual = 0;
7714 		ctsio->kern_data_len = alloc_len;
7715 		ctsio->kern_total_len = alloc_len;
7716 	}
7717 	ctsio->kern_data_resid = 0;
7718 	ctsio->kern_rel_offset = 0;
7719 
7720 	data = (struct scsi_report_timestamp_data *)ctsio->kern_data_ptr;
7721 	scsi_ulto2b(sizeof(*data) - 2, data->length);
7722 	data->origin = RTS_ORIG_OUTSIDE;
7723 	getmicrotime(&tv);
7724 	timestamp = (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
7725 	scsi_ulto4b(timestamp >> 16, data->timestamp);
7726 	scsi_ulto2b(timestamp & 0xffff, &data->timestamp[4]);
7727 
7728 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
7729 	ctsio->be_move_done = ctl_config_move_done;
7730 
7731 	ctl_datamove((union ctl_io *)ctsio);
7732 	return (retval);
7733 }
7734 
7735 int
7736 ctl_persistent_reserve_in(struct ctl_scsiio *ctsio)
7737 {
7738 	struct scsi_per_res_in *cdb;
7739 	int alloc_len, total_len = 0;
7740 	/* struct scsi_per_res_in_rsrv in_data; */
7741 	struct ctl_lun *lun;
7742 	struct ctl_softc *softc;
7743 
7744 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_in\n"));
7745 
7746 	softc = control_softc;
7747 
7748 	cdb = (struct scsi_per_res_in *)ctsio->cdb;
7749 
7750 	alloc_len = scsi_2btoul(cdb->length);
7751 
7752 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
7753 
7754 retry:
7755 	mtx_lock(&lun->lun_lock);
7756 	switch (cdb->action) {
7757 	case SPRI_RK: /* read keys */
7758 		total_len = sizeof(struct scsi_per_res_in_keys) +
7759 			lun->pr_key_count *
7760 			sizeof(struct scsi_per_res_key);
7761 		break;
7762 	case SPRI_RR: /* read reservation */
7763 		if (lun->flags & CTL_LUN_PR_RESERVED)
7764 			total_len = sizeof(struct scsi_per_res_in_rsrv);
7765 		else
7766 			total_len = sizeof(struct scsi_per_res_in_header);
7767 		break;
7768 	case SPRI_RC: /* report capabilities */
7769 		total_len = sizeof(struct scsi_per_res_cap);
7770 		break;
7771 	case SPRI_RS: /* read full status */
7772 		total_len = sizeof(struct scsi_per_res_in_header) +
7773 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7774 		    lun->pr_key_count;
7775 		break;
7776 	default:
7777 		panic("Invalid PR type %x", cdb->action);
7778 	}
7779 	mtx_unlock(&lun->lun_lock);
7780 
7781 	ctsio->kern_data_ptr = malloc(total_len, M_CTL, M_WAITOK | M_ZERO);
7782 
7783 	if (total_len < alloc_len) {
7784 		ctsio->residual = alloc_len - total_len;
7785 		ctsio->kern_data_len = total_len;
7786 		ctsio->kern_total_len = total_len;
7787 	} else {
7788 		ctsio->residual = 0;
7789 		ctsio->kern_data_len = alloc_len;
7790 		ctsio->kern_total_len = alloc_len;
7791 	}
7792 
7793 	ctsio->kern_data_resid = 0;
7794 	ctsio->kern_rel_offset = 0;
7795 	ctsio->kern_sg_entries = 0;
7796 
7797 	mtx_lock(&lun->lun_lock);
7798 	switch (cdb->action) {
7799 	case SPRI_RK: { // read keys
7800         struct scsi_per_res_in_keys *res_keys;
7801 		int i, key_count;
7802 
7803 		res_keys = (struct scsi_per_res_in_keys*)ctsio->kern_data_ptr;
7804 
7805 		/*
7806 		 * We had to drop the lock to allocate our buffer, which
7807 		 * leaves time for someone to come in with another
7808 		 * persistent reservation.  (That is unlikely, though,
7809 		 * since this should be the only persistent reservation
7810 		 * command active right now.)
7811 		 */
7812 		if (total_len != (sizeof(struct scsi_per_res_in_keys) +
7813 		    (lun->pr_key_count *
7814 		     sizeof(struct scsi_per_res_key)))){
7815 			mtx_unlock(&lun->lun_lock);
7816 			free(ctsio->kern_data_ptr, M_CTL);
7817 			printf("%s: reservation length changed, retrying\n",
7818 			       __func__);
7819 			goto retry;
7820 		}
7821 
7822 		scsi_ulto4b(lun->PRGeneration, res_keys->header.generation);
7823 
7824 		scsi_ulto4b(sizeof(struct scsi_per_res_key) *
7825 			     lun->pr_key_count, res_keys->header.length);
7826 
7827 		for (i = 0, key_count = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7828 			if (!lun->per_res[i].registered)
7829 				continue;
7830 
7831 			/*
7832 			 * We used lun->pr_key_count to calculate the
7833 			 * size to allocate.  If it turns out the number of
7834 			 * initiators with the registered flag set is
7835 			 * larger than that (i.e. they haven't been kept in
7836 			 * sync), we've got a problem.
7837 			 */
7838 			if (key_count >= lun->pr_key_count) {
7839 #ifdef NEEDTOPORT
7840 				csevent_log(CSC_CTL | CSC_SHELF_SW |
7841 					    CTL_PR_ERROR,
7842 					    csevent_LogType_Fault,
7843 					    csevent_AlertLevel_Yellow,
7844 					    csevent_FRU_ShelfController,
7845 					    csevent_FRU_Firmware,
7846 				        csevent_FRU_Unknown,
7847 					    "registered keys %d >= key "
7848 					    "count %d", key_count,
7849 					    lun->pr_key_count);
7850 #endif
7851 				key_count++;
7852 				continue;
7853 			}
7854 			memcpy(res_keys->keys[key_count].key,
7855 			       lun->per_res[i].res_key.key,
7856 			       ctl_min(sizeof(res_keys->keys[key_count].key),
7857 			       sizeof(lun->per_res[i].res_key)));
7858 			key_count++;
7859 		}
7860 		break;
7861 	}
7862 	case SPRI_RR: { // read reservation
7863 		struct scsi_per_res_in_rsrv *res;
7864 		int tmp_len, header_only;
7865 
7866 		res = (struct scsi_per_res_in_rsrv *)ctsio->kern_data_ptr;
7867 
7868 		scsi_ulto4b(lun->PRGeneration, res->header.generation);
7869 
7870 		if (lun->flags & CTL_LUN_PR_RESERVED)
7871 		{
7872 			tmp_len = sizeof(struct scsi_per_res_in_rsrv);
7873 			scsi_ulto4b(sizeof(struct scsi_per_res_in_rsrv_data),
7874 				    res->header.length);
7875 			header_only = 0;
7876 		} else {
7877 			tmp_len = sizeof(struct scsi_per_res_in_header);
7878 			scsi_ulto4b(0, res->header.length);
7879 			header_only = 1;
7880 		}
7881 
7882 		/*
7883 		 * We had to drop the lock to allocate our buffer, which
7884 		 * leaves time for someone to come in with another
7885 		 * persistent reservation.  (That is unlikely, though,
7886 		 * since this should be the only persistent reservation
7887 		 * command active right now.)
7888 		 */
7889 		if (tmp_len != total_len) {
7890 			mtx_unlock(&lun->lun_lock);
7891 			free(ctsio->kern_data_ptr, M_CTL);
7892 			printf("%s: reservation status changed, retrying\n",
7893 			       __func__);
7894 			goto retry;
7895 		}
7896 
7897 		/*
7898 		 * No reservation held, so we're done.
7899 		 */
7900 		if (header_only != 0)
7901 			break;
7902 
7903 		/*
7904 		 * If the registration is an All Registrants type, the key
7905 		 * is 0, since it doesn't really matter.
7906 		 */
7907 		if (lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
7908 			memcpy(res->data.reservation,
7909 			       &lun->per_res[lun->pr_res_idx].res_key,
7910 			       sizeof(struct scsi_per_res_key));
7911 		}
7912 		res->data.scopetype = lun->res_type;
7913 		break;
7914 	}
7915 	case SPRI_RC:     //report capabilities
7916 	{
7917 		struct scsi_per_res_cap *res_cap;
7918 		uint16_t type_mask;
7919 
7920 		res_cap = (struct scsi_per_res_cap *)ctsio->kern_data_ptr;
7921 		scsi_ulto2b(sizeof(*res_cap), res_cap->length);
7922 		res_cap->flags2 |= SPRI_TMV | SPRI_ALLOW_5;
7923 		type_mask = SPRI_TM_WR_EX_AR |
7924 			    SPRI_TM_EX_AC_RO |
7925 			    SPRI_TM_WR_EX_RO |
7926 			    SPRI_TM_EX_AC |
7927 			    SPRI_TM_WR_EX |
7928 			    SPRI_TM_EX_AC_AR;
7929 		scsi_ulto2b(type_mask, res_cap->type_mask);
7930 		break;
7931 	}
7932 	case SPRI_RS: { // read full status
7933 		struct scsi_per_res_in_full *res_status;
7934 		struct scsi_per_res_in_full_desc *res_desc;
7935 		struct ctl_port *port;
7936 		int i, len;
7937 
7938 		res_status = (struct scsi_per_res_in_full*)ctsio->kern_data_ptr;
7939 
7940 		/*
7941 		 * We had to drop the lock to allocate our buffer, which
7942 		 * leaves time for someone to come in with another
7943 		 * persistent reservation.  (That is unlikely, though,
7944 		 * since this should be the only persistent reservation
7945 		 * command active right now.)
7946 		 */
7947 		if (total_len < (sizeof(struct scsi_per_res_in_header) +
7948 		    (sizeof(struct scsi_per_res_in_full_desc) + 256) *
7949 		     lun->pr_key_count)){
7950 			mtx_unlock(&lun->lun_lock);
7951 			free(ctsio->kern_data_ptr, M_CTL);
7952 			printf("%s: reservation length changed, retrying\n",
7953 			       __func__);
7954 			goto retry;
7955 		}
7956 
7957 		scsi_ulto4b(lun->PRGeneration, res_status->header.generation);
7958 
7959 		res_desc = &res_status->desc[0];
7960 		for (i = 0; i < 2*CTL_MAX_INITIATORS; i++) {
7961 			if (!lun->per_res[i].registered)
7962 				continue;
7963 
7964 			memcpy(&res_desc->res_key, &lun->per_res[i].res_key.key,
7965 			    sizeof(res_desc->res_key));
7966 			if ((lun->flags & CTL_LUN_PR_RESERVED) &&
7967 			    (lun->pr_res_idx == i ||
7968 			     lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS)) {
7969 				res_desc->flags = SPRI_FULL_R_HOLDER;
7970 				res_desc->scopetype = lun->res_type;
7971 			}
7972 			scsi_ulto2b(i / CTL_MAX_INIT_PER_PORT,
7973 			    res_desc->rel_trgt_port_id);
7974 			len = 0;
7975 			port = softc->ctl_ports[
7976 			    ctl_port_idx(i / CTL_MAX_INIT_PER_PORT)];
7977 			if (port != NULL)
7978 				len = ctl_create_iid(port,
7979 				    i % CTL_MAX_INIT_PER_PORT,
7980 				    res_desc->transport_id);
7981 			scsi_ulto4b(len, res_desc->additional_length);
7982 			res_desc = (struct scsi_per_res_in_full_desc *)
7983 			    &res_desc->transport_id[len];
7984 		}
7985 		scsi_ulto4b((uint8_t *)res_desc - (uint8_t *)&res_status->desc[0],
7986 		    res_status->header.length);
7987 		break;
7988 	}
7989 	default:
7990 		/*
7991 		 * This is a bug, because we just checked for this above,
7992 		 * and should have returned an error.
7993 		 */
7994 		panic("Invalid PR type %x", cdb->action);
7995 		break; /* NOTREACHED */
7996 	}
7997 	mtx_unlock(&lun->lun_lock);
7998 
7999 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8000 	ctsio->be_move_done = ctl_config_move_done;
8001 
8002 	CTL_DEBUG_PRINT(("buf = %x %x %x %x %x %x %x %x\n",
8003 			 ctsio->kern_data_ptr[0], ctsio->kern_data_ptr[1],
8004 			 ctsio->kern_data_ptr[2], ctsio->kern_data_ptr[3],
8005 			 ctsio->kern_data_ptr[4], ctsio->kern_data_ptr[5],
8006 			 ctsio->kern_data_ptr[6], ctsio->kern_data_ptr[7]));
8007 
8008 	ctl_datamove((union ctl_io *)ctsio);
8009 
8010 	return (CTL_RETVAL_COMPLETE);
8011 }
8012 
8013 /*
8014  * Returns 0 if ctl_persistent_reserve_out() should continue, non-zero if
8015  * it should return.
8016  */
8017 static int
8018 ctl_pro_preempt(struct ctl_softc *softc, struct ctl_lun *lun, uint64_t res_key,
8019 		uint64_t sa_res_key, uint8_t type, uint32_t residx,
8020 		struct ctl_scsiio *ctsio, struct scsi_per_res_out *cdb,
8021 		struct scsi_per_res_out_parms* param)
8022 {
8023 	union ctl_ha_msg persis_io;
8024 	int retval, i;
8025 	int isc_retval;
8026 
8027 	retval = 0;
8028 
8029 	mtx_lock(&lun->lun_lock);
8030 	if (sa_res_key == 0) {
8031 		if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8032 			/* validate scope and type */
8033 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8034 			     SPR_LU_SCOPE) {
8035 				mtx_unlock(&lun->lun_lock);
8036 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8037 						      /*sks_valid*/ 1,
8038 						      /*command*/ 1,
8039 						      /*field*/ 2,
8040 						      /*bit_valid*/ 1,
8041 						      /*bit*/ 4);
8042 				ctl_done((union ctl_io *)ctsio);
8043 				return (1);
8044 			}
8045 
8046 		        if (type>8 || type==2 || type==4 || type==0) {
8047 				mtx_unlock(&lun->lun_lock);
8048 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8049        	           				      /*sks_valid*/ 1,
8050 						      /*command*/ 1,
8051 						      /*field*/ 2,
8052 						      /*bit_valid*/ 1,
8053 						      /*bit*/ 0);
8054 				ctl_done((union ctl_io *)ctsio);
8055 				return (1);
8056 		        }
8057 
8058 			/* temporarily unregister this nexus */
8059 			lun->per_res[residx].registered = 0;
8060 
8061 			/*
8062 			 * Unregister everybody else and build UA for
8063 			 * them
8064 			 */
8065 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8066 				if (lun->per_res[i].registered == 0)
8067 					continue;
8068 
8069 				if (!persis_offset
8070 				 && i <CTL_MAX_INITIATORS)
8071 					lun->pending_ua[i] |=
8072 						CTL_UA_REG_PREEMPT;
8073 				else if (persis_offset
8074 				      && i >= persis_offset)
8075 					lun->pending_ua[i-persis_offset] |=
8076 						CTL_UA_REG_PREEMPT;
8077 				lun->per_res[i].registered = 0;
8078 				memset(&lun->per_res[i].res_key, 0,
8079 				       sizeof(struct scsi_per_res_key));
8080 			}
8081 			lun->per_res[residx].registered = 1;
8082 			lun->pr_key_count = 1;
8083 			lun->res_type = type;
8084 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8085 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8086 				lun->pr_res_idx = residx;
8087 
8088 			/* send msg to other side */
8089 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8090 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8091 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8092 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8093 			persis_io.pr.pr_info.res_type = type;
8094 			memcpy(persis_io.pr.pr_info.sa_res_key,
8095 			       param->serv_act_res_key,
8096 			       sizeof(param->serv_act_res_key));
8097 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8098 			     &persis_io, sizeof(persis_io), 0)) >
8099 			     CTL_HA_STATUS_SUCCESS) {
8100 				printf("CTL:Persis Out error returned "
8101 				       "from ctl_ha_msg_send %d\n",
8102 				       isc_retval);
8103 			}
8104 		} else {
8105 			/* not all registrants */
8106 			mtx_unlock(&lun->lun_lock);
8107 			free(ctsio->kern_data_ptr, M_CTL);
8108 			ctl_set_invalid_field(ctsio,
8109 					      /*sks_valid*/ 1,
8110 					      /*command*/ 0,
8111 					      /*field*/ 8,
8112 					      /*bit_valid*/ 0,
8113 					      /*bit*/ 0);
8114 			ctl_done((union ctl_io *)ctsio);
8115 			return (1);
8116 		}
8117 	} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8118 		|| !(lun->flags & CTL_LUN_PR_RESERVED)) {
8119 		int found = 0;
8120 
8121 		if (res_key == sa_res_key) {
8122 			/* special case */
8123 			/*
8124 			 * The spec implies this is not good but doesn't
8125 			 * say what to do. There are two choices either
8126 			 * generate a res conflict or check condition
8127 			 * with illegal field in parameter data. Since
8128 			 * that is what is done when the sa_res_key is
8129 			 * zero I'll take that approach since this has
8130 			 * to do with the sa_res_key.
8131 			 */
8132 			mtx_unlock(&lun->lun_lock);
8133 			free(ctsio->kern_data_ptr, M_CTL);
8134 			ctl_set_invalid_field(ctsio,
8135 					      /*sks_valid*/ 1,
8136 					      /*command*/ 0,
8137 					      /*field*/ 8,
8138 					      /*bit_valid*/ 0,
8139 					      /*bit*/ 0);
8140 			ctl_done((union ctl_io *)ctsio);
8141 			return (1);
8142 		}
8143 
8144 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8145 			if (lun->per_res[i].registered
8146 			 && memcmp(param->serv_act_res_key,
8147 			    lun->per_res[i].res_key.key,
8148 			    sizeof(struct scsi_per_res_key)) != 0)
8149 				continue;
8150 
8151 			found = 1;
8152 			lun->per_res[i].registered = 0;
8153 			memset(&lun->per_res[i].res_key, 0,
8154 			       sizeof(struct scsi_per_res_key));
8155 			lun->pr_key_count--;
8156 
8157 			if (!persis_offset && i < CTL_MAX_INITIATORS)
8158 				lun->pending_ua[i] |= CTL_UA_REG_PREEMPT;
8159 			else if (persis_offset && i >= persis_offset)
8160 				lun->pending_ua[i-persis_offset] |=
8161 					CTL_UA_REG_PREEMPT;
8162 		}
8163 		if (!found) {
8164 			mtx_unlock(&lun->lun_lock);
8165 			free(ctsio->kern_data_ptr, M_CTL);
8166 			ctl_set_reservation_conflict(ctsio);
8167 			ctl_done((union ctl_io *)ctsio);
8168 			return (CTL_RETVAL_COMPLETE);
8169 		}
8170 		/* send msg to other side */
8171 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8172 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8173 		persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8174 		persis_io.pr.pr_info.residx = lun->pr_res_idx;
8175 		persis_io.pr.pr_info.res_type = type;
8176 		memcpy(persis_io.pr.pr_info.sa_res_key,
8177 		       param->serv_act_res_key,
8178 		       sizeof(param->serv_act_res_key));
8179 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8180 		     &persis_io, sizeof(persis_io), 0)) >
8181 		     CTL_HA_STATUS_SUCCESS) {
8182 			printf("CTL:Persis Out error returned from "
8183 			       "ctl_ha_msg_send %d\n", isc_retval);
8184 		}
8185 	} else {
8186 		/* Reserved but not all registrants */
8187 		/* sa_res_key is res holder */
8188 		if (memcmp(param->serv_act_res_key,
8189                    lun->per_res[lun->pr_res_idx].res_key.key,
8190                    sizeof(struct scsi_per_res_key)) == 0) {
8191 			/* validate scope and type */
8192 			if ((cdb->scope_type & SPR_SCOPE_MASK) !=
8193 			     SPR_LU_SCOPE) {
8194 				mtx_unlock(&lun->lun_lock);
8195 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8196 						      /*sks_valid*/ 1,
8197 						      /*command*/ 1,
8198 						      /*field*/ 2,
8199 						      /*bit_valid*/ 1,
8200 						      /*bit*/ 4);
8201 				ctl_done((union ctl_io *)ctsio);
8202 				return (1);
8203 			}
8204 
8205 			if (type>8 || type==2 || type==4 || type==0) {
8206 				mtx_unlock(&lun->lun_lock);
8207 				ctl_set_invalid_field(/*ctsio*/ ctsio,
8208 						      /*sks_valid*/ 1,
8209 						      /*command*/ 1,
8210 						      /*field*/ 2,
8211 						      /*bit_valid*/ 1,
8212 						      /*bit*/ 0);
8213 				ctl_done((union ctl_io *)ctsio);
8214 				return (1);
8215 			}
8216 
8217 			/*
8218 			 * Do the following:
8219 			 * if sa_res_key != res_key remove all
8220 			 * registrants w/sa_res_key and generate UA
8221 			 * for these registrants(Registrations
8222 			 * Preempted) if it wasn't an exclusive
8223 			 * reservation generate UA(Reservations
8224 			 * Preempted) for all other registered nexuses
8225 			 * if the type has changed. Establish the new
8226 			 * reservation and holder. If res_key and
8227 			 * sa_res_key are the same do the above
8228 			 * except don't unregister the res holder.
8229 			 */
8230 
8231 			/*
8232 			 * Temporarily unregister so it won't get
8233 			 * removed or UA generated
8234 			 */
8235 			lun->per_res[residx].registered = 0;
8236 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8237 				if (lun->per_res[i].registered == 0)
8238 					continue;
8239 
8240 				if (memcmp(param->serv_act_res_key,
8241 				    lun->per_res[i].res_key.key,
8242 				    sizeof(struct scsi_per_res_key)) == 0) {
8243 					lun->per_res[i].registered = 0;
8244 					memset(&lun->per_res[i].res_key,
8245 					       0,
8246 					       sizeof(struct scsi_per_res_key));
8247 					lun->pr_key_count--;
8248 
8249 					if (!persis_offset
8250 					 && i < CTL_MAX_INITIATORS)
8251 						lun->pending_ua[i] |=
8252 							CTL_UA_REG_PREEMPT;
8253 					else if (persis_offset
8254 					      && i >= persis_offset)
8255 						lun->pending_ua[i-persis_offset] |=
8256 						  CTL_UA_REG_PREEMPT;
8257 				} else if (type != lun->res_type
8258 					&& (lun->res_type == SPR_TYPE_WR_EX_RO
8259 					 || lun->res_type ==SPR_TYPE_EX_AC_RO)){
8260 						if (!persis_offset
8261 						 && i < CTL_MAX_INITIATORS)
8262 							lun->pending_ua[i] |=
8263 							CTL_UA_RES_RELEASE;
8264 						else if (persis_offset
8265 						      && i >= persis_offset)
8266 							lun->pending_ua[
8267 							i-persis_offset] |=
8268 							CTL_UA_RES_RELEASE;
8269 				}
8270 			}
8271 			lun->per_res[residx].registered = 1;
8272 			lun->res_type = type;
8273 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8274 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8275 				lun->pr_res_idx = residx;
8276 			else
8277 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8278 
8279 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8280 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8281 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8282 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8283 			persis_io.pr.pr_info.res_type = type;
8284 			memcpy(persis_io.pr.pr_info.sa_res_key,
8285 			       param->serv_act_res_key,
8286 			       sizeof(param->serv_act_res_key));
8287 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8288 			     &persis_io, sizeof(persis_io), 0)) >
8289 			     CTL_HA_STATUS_SUCCESS) {
8290 				printf("CTL:Persis Out error returned "
8291 				       "from ctl_ha_msg_send %d\n",
8292 				       isc_retval);
8293 			}
8294 		} else {
8295 			/*
8296 			 * sa_res_key is not the res holder just
8297 			 * remove registrants
8298 			 */
8299 			int found=0;
8300 
8301 			for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8302 				if (memcmp(param->serv_act_res_key,
8303 				    lun->per_res[i].res_key.key,
8304 				    sizeof(struct scsi_per_res_key)) != 0)
8305 					continue;
8306 
8307 				found = 1;
8308 				lun->per_res[i].registered = 0;
8309 				memset(&lun->per_res[i].res_key, 0,
8310 				       sizeof(struct scsi_per_res_key));
8311 				lun->pr_key_count--;
8312 
8313 				if (!persis_offset
8314 				 && i < CTL_MAX_INITIATORS)
8315 					lun->pending_ua[i] |=
8316 						CTL_UA_REG_PREEMPT;
8317 				else if (persis_offset
8318 				      && i >= persis_offset)
8319 					lun->pending_ua[i-persis_offset] |=
8320 						CTL_UA_REG_PREEMPT;
8321 			}
8322 
8323 			if (!found) {
8324 				mtx_unlock(&lun->lun_lock);
8325 				free(ctsio->kern_data_ptr, M_CTL);
8326 				ctl_set_reservation_conflict(ctsio);
8327 				ctl_done((union ctl_io *)ctsio);
8328 		        	return (1);
8329 			}
8330 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8331 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8332 			persis_io.pr.pr_info.action = CTL_PR_PREEMPT;
8333 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8334 			persis_io.pr.pr_info.res_type = type;
8335 			memcpy(persis_io.pr.pr_info.sa_res_key,
8336 			       param->serv_act_res_key,
8337 			       sizeof(param->serv_act_res_key));
8338 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8339 			     &persis_io, sizeof(persis_io), 0)) >
8340 			     CTL_HA_STATUS_SUCCESS) {
8341 				printf("CTL:Persis Out error returned "
8342 				       "from ctl_ha_msg_send %d\n",
8343 				isc_retval);
8344 			}
8345 		}
8346 	}
8347 
8348 	lun->PRGeneration++;
8349 	mtx_unlock(&lun->lun_lock);
8350 
8351 	return (retval);
8352 }
8353 
8354 static void
8355 ctl_pro_preempt_other(struct ctl_lun *lun, union ctl_ha_msg *msg)
8356 {
8357 	int i;
8358 
8359 	if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS
8360 	 || lun->pr_res_idx == CTL_PR_NO_RESERVATION
8361 	 || memcmp(&lun->per_res[lun->pr_res_idx].res_key,
8362 		   msg->pr.pr_info.sa_res_key,
8363 		   sizeof(struct scsi_per_res_key)) != 0) {
8364 		uint64_t sa_res_key;
8365 		sa_res_key = scsi_8btou64(msg->pr.pr_info.sa_res_key);
8366 
8367 		if (sa_res_key == 0) {
8368 			/* temporarily unregister this nexus */
8369 			lun->per_res[msg->pr.pr_info.residx].registered = 0;
8370 
8371 			/*
8372 			 * Unregister everybody else and build UA for
8373 			 * them
8374 			 */
8375 			for(i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8376 				if (lun->per_res[i].registered == 0)
8377 					continue;
8378 
8379 				if (!persis_offset
8380 				 && i < CTL_MAX_INITIATORS)
8381 					lun->pending_ua[i] |=
8382 						CTL_UA_REG_PREEMPT;
8383 				else if (persis_offset && i >= persis_offset)
8384 					lun->pending_ua[i - persis_offset] |=
8385 						CTL_UA_REG_PREEMPT;
8386 				lun->per_res[i].registered = 0;
8387 				memset(&lun->per_res[i].res_key, 0,
8388 				       sizeof(struct scsi_per_res_key));
8389 			}
8390 
8391 			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8392 			lun->pr_key_count = 1;
8393 			lun->res_type = msg->pr.pr_info.res_type;
8394 			if (lun->res_type != SPR_TYPE_WR_EX_AR
8395 			 && lun->res_type != SPR_TYPE_EX_AC_AR)
8396 				lun->pr_res_idx = msg->pr.pr_info.residx;
8397 		} else {
8398 		        for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8399 				if (memcmp(msg->pr.pr_info.sa_res_key,
8400 		                   lun->per_res[i].res_key.key,
8401 		                   sizeof(struct scsi_per_res_key)) != 0)
8402 					continue;
8403 
8404 				lun->per_res[i].registered = 0;
8405 				memset(&lun->per_res[i].res_key, 0,
8406 				       sizeof(struct scsi_per_res_key));
8407 				lun->pr_key_count--;
8408 
8409 				if (!persis_offset
8410 				 && i < persis_offset)
8411 					lun->pending_ua[i] |=
8412 						CTL_UA_REG_PREEMPT;
8413 				else if (persis_offset
8414 				      && i >= persis_offset)
8415 					lun->pending_ua[i - persis_offset] |=
8416 						CTL_UA_REG_PREEMPT;
8417 			}
8418 		}
8419 	} else {
8420 		/*
8421 		 * Temporarily unregister so it won't get removed
8422 		 * or UA generated
8423 		 */
8424 		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8425 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
8426 			if (lun->per_res[i].registered == 0)
8427 				continue;
8428 
8429 			if (memcmp(msg->pr.pr_info.sa_res_key,
8430 	                   lun->per_res[i].res_key.key,
8431 	                   sizeof(struct scsi_per_res_key)) == 0) {
8432 				lun->per_res[i].registered = 0;
8433 				memset(&lun->per_res[i].res_key, 0,
8434 				       sizeof(struct scsi_per_res_key));
8435 				lun->pr_key_count--;
8436 				if (!persis_offset
8437 				 && i < CTL_MAX_INITIATORS)
8438 					lun->pending_ua[i] |=
8439 						CTL_UA_REG_PREEMPT;
8440 				else if (persis_offset
8441 				      && i >= persis_offset)
8442 					lun->pending_ua[i - persis_offset] |=
8443 						CTL_UA_REG_PREEMPT;
8444 			} else if (msg->pr.pr_info.res_type != lun->res_type
8445 				&& (lun->res_type == SPR_TYPE_WR_EX_RO
8446 				 || lun->res_type == SPR_TYPE_EX_AC_RO)) {
8447 					if (!persis_offset
8448 					 && i < persis_offset)
8449 						lun->pending_ua[i] |=
8450 							CTL_UA_RES_RELEASE;
8451 					else if (persis_offset
8452 					      && i >= persis_offset)
8453 					lun->pending_ua[i - persis_offset] |=
8454 						CTL_UA_RES_RELEASE;
8455 			}
8456 		}
8457 		lun->per_res[msg->pr.pr_info.residx].registered = 1;
8458 		lun->res_type = msg->pr.pr_info.res_type;
8459 		if (lun->res_type != SPR_TYPE_WR_EX_AR
8460 		 && lun->res_type != SPR_TYPE_EX_AC_AR)
8461 			lun->pr_res_idx = msg->pr.pr_info.residx;
8462 		else
8463 			lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8464 	}
8465 	lun->PRGeneration++;
8466 
8467 }
8468 
8469 
8470 int
8471 ctl_persistent_reserve_out(struct ctl_scsiio *ctsio)
8472 {
8473 	int retval;
8474 	int isc_retval;
8475 	u_int32_t param_len;
8476 	struct scsi_per_res_out *cdb;
8477 	struct ctl_lun *lun;
8478 	struct scsi_per_res_out_parms* param;
8479 	struct ctl_softc *softc;
8480 	uint32_t residx;
8481 	uint64_t res_key, sa_res_key;
8482 	uint8_t type;
8483 	union ctl_ha_msg persis_io;
8484 	int    i;
8485 
8486 	CTL_DEBUG_PRINT(("ctl_persistent_reserve_out\n"));
8487 
8488 	retval = CTL_RETVAL_COMPLETE;
8489 
8490 	softc = control_softc;
8491 
8492 	cdb = (struct scsi_per_res_out *)ctsio->cdb;
8493 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
8494 
8495 	/*
8496 	 * We only support whole-LUN scope.  The scope & type are ignored for
8497 	 * register, register and ignore existing key and clear.
8498 	 * We sometimes ignore scope and type on preempts too!!
8499 	 * Verify reservation type here as well.
8500 	 */
8501 	type = cdb->scope_type & SPR_TYPE_MASK;
8502 	if ((cdb->action == SPRO_RESERVE)
8503 	 || (cdb->action == SPRO_RELEASE)) {
8504 		if ((cdb->scope_type & SPR_SCOPE_MASK) != SPR_LU_SCOPE) {
8505 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8506 					      /*sks_valid*/ 1,
8507 					      /*command*/ 1,
8508 					      /*field*/ 2,
8509 					      /*bit_valid*/ 1,
8510 					      /*bit*/ 4);
8511 			ctl_done((union ctl_io *)ctsio);
8512 			return (CTL_RETVAL_COMPLETE);
8513 		}
8514 
8515 		if (type>8 || type==2 || type==4 || type==0) {
8516 			ctl_set_invalid_field(/*ctsio*/ ctsio,
8517 					      /*sks_valid*/ 1,
8518 					      /*command*/ 1,
8519 					      /*field*/ 2,
8520 					      /*bit_valid*/ 1,
8521 					      /*bit*/ 0);
8522 			ctl_done((union ctl_io *)ctsio);
8523 			return (CTL_RETVAL_COMPLETE);
8524 		}
8525 	}
8526 
8527 	param_len = scsi_4btoul(cdb->length);
8528 
8529 	if ((ctsio->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0) {
8530 		ctsio->kern_data_ptr = malloc(param_len, M_CTL, M_WAITOK);
8531 		ctsio->kern_data_len = param_len;
8532 		ctsio->kern_total_len = param_len;
8533 		ctsio->kern_data_resid = 0;
8534 		ctsio->kern_rel_offset = 0;
8535 		ctsio->kern_sg_entries = 0;
8536 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
8537 		ctsio->be_move_done = ctl_config_move_done;
8538 		ctl_datamove((union ctl_io *)ctsio);
8539 
8540 		return (CTL_RETVAL_COMPLETE);
8541 	}
8542 
8543 	param = (struct scsi_per_res_out_parms *)ctsio->kern_data_ptr;
8544 
8545 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
8546 	res_key = scsi_8btou64(param->res_key.key);
8547 	sa_res_key = scsi_8btou64(param->serv_act_res_key);
8548 
8549 	/*
8550 	 * Validate the reservation key here except for SPRO_REG_IGNO
8551 	 * This must be done for all other service actions
8552 	 */
8553 	if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REG_IGNO) {
8554 		mtx_lock(&lun->lun_lock);
8555 		if (lun->per_res[residx].registered) {
8556 		    if (memcmp(param->res_key.key,
8557 			       lun->per_res[residx].res_key.key,
8558 			       ctl_min(sizeof(param->res_key),
8559 			       sizeof(lun->per_res[residx].res_key))) != 0) {
8560 				/*
8561 				 * The current key passed in doesn't match
8562 				 * the one the initiator previously
8563 				 * registered.
8564 				 */
8565 				mtx_unlock(&lun->lun_lock);
8566 				free(ctsio->kern_data_ptr, M_CTL);
8567 				ctl_set_reservation_conflict(ctsio);
8568 				ctl_done((union ctl_io *)ctsio);
8569 				return (CTL_RETVAL_COMPLETE);
8570 			}
8571 		} else if ((cdb->action & SPRO_ACTION_MASK) != SPRO_REGISTER) {
8572 			/*
8573 			 * We are not registered
8574 			 */
8575 			mtx_unlock(&lun->lun_lock);
8576 			free(ctsio->kern_data_ptr, M_CTL);
8577 			ctl_set_reservation_conflict(ctsio);
8578 			ctl_done((union ctl_io *)ctsio);
8579 			return (CTL_RETVAL_COMPLETE);
8580 		} else if (res_key != 0) {
8581 			/*
8582 			 * We are not registered and trying to register but
8583 			 * the register key isn't zero.
8584 			 */
8585 			mtx_unlock(&lun->lun_lock);
8586 			free(ctsio->kern_data_ptr, M_CTL);
8587 			ctl_set_reservation_conflict(ctsio);
8588 			ctl_done((union ctl_io *)ctsio);
8589 			return (CTL_RETVAL_COMPLETE);
8590 		}
8591 		mtx_unlock(&lun->lun_lock);
8592 	}
8593 
8594 	switch (cdb->action & SPRO_ACTION_MASK) {
8595 	case SPRO_REGISTER:
8596 	case SPRO_REG_IGNO: {
8597 
8598 #if 0
8599 		printf("Registration received\n");
8600 #endif
8601 
8602 		/*
8603 		 * We don't support any of these options, as we report in
8604 		 * the read capabilities request (see
8605 		 * ctl_persistent_reserve_in(), above).
8606 		 */
8607 		if ((param->flags & SPR_SPEC_I_PT)
8608 		 || (param->flags & SPR_ALL_TG_PT)
8609 		 || (param->flags & SPR_APTPL)) {
8610 			int bit_ptr;
8611 
8612 			if (param->flags & SPR_APTPL)
8613 				bit_ptr = 0;
8614 			else if (param->flags & SPR_ALL_TG_PT)
8615 				bit_ptr = 2;
8616 			else /* SPR_SPEC_I_PT */
8617 				bit_ptr = 3;
8618 
8619 			free(ctsio->kern_data_ptr, M_CTL);
8620 			ctl_set_invalid_field(ctsio,
8621 					      /*sks_valid*/ 1,
8622 					      /*command*/ 0,
8623 					      /*field*/ 20,
8624 					      /*bit_valid*/ 1,
8625 					      /*bit*/ bit_ptr);
8626 			ctl_done((union ctl_io *)ctsio);
8627 			return (CTL_RETVAL_COMPLETE);
8628 		}
8629 
8630 		mtx_lock(&lun->lun_lock);
8631 
8632 		/*
8633 		 * The initiator wants to clear the
8634 		 * key/unregister.
8635 		 */
8636 		if (sa_res_key == 0) {
8637 			if ((res_key == 0
8638 			  && (cdb->action & SPRO_ACTION_MASK) == SPRO_REGISTER)
8639 			 || ((cdb->action & SPRO_ACTION_MASK) == SPRO_REG_IGNO
8640 			  && !lun->per_res[residx].registered)) {
8641 				mtx_unlock(&lun->lun_lock);
8642 				goto done;
8643 			}
8644 
8645 			lun->per_res[residx].registered = 0;
8646 			memset(&lun->per_res[residx].res_key,
8647 			       0, sizeof(lun->per_res[residx].res_key));
8648 			lun->pr_key_count--;
8649 
8650 			if (residx == lun->pr_res_idx) {
8651 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8652 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8653 
8654 				if ((lun->res_type == SPR_TYPE_WR_EX_RO
8655 				  || lun->res_type == SPR_TYPE_EX_AC_RO)
8656 				 && lun->pr_key_count) {
8657 					/*
8658 					 * If the reservation is a registrants
8659 					 * only type we need to generate a UA
8660 					 * for other registered inits.  The
8661 					 * sense code should be RESERVATIONS
8662 					 * RELEASED
8663 					 */
8664 
8665 					for (i = 0; i < CTL_MAX_INITIATORS;i++){
8666 						if (lun->per_res[
8667 						    i+persis_offset].registered
8668 						    == 0)
8669 							continue;
8670 						lun->pending_ua[i] |=
8671 							CTL_UA_RES_RELEASE;
8672 					}
8673 				}
8674 				lun->res_type = 0;
8675 			} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8676 				if (lun->pr_key_count==0) {
8677 					lun->flags &= ~CTL_LUN_PR_RESERVED;
8678 					lun->res_type = 0;
8679 					lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8680 				}
8681 			}
8682 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8683 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8684 			persis_io.pr.pr_info.action = CTL_PR_UNREG_KEY;
8685 			persis_io.pr.pr_info.residx = residx;
8686 			if ((isc_retval = ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8687 			     &persis_io, sizeof(persis_io), 0 )) >
8688 			     CTL_HA_STATUS_SUCCESS) {
8689 				printf("CTL:Persis Out error returned from "
8690 				       "ctl_ha_msg_send %d\n", isc_retval);
8691 			}
8692 		} else /* sa_res_key != 0 */ {
8693 
8694 			/*
8695 			 * If we aren't registered currently then increment
8696 			 * the key count and set the registered flag.
8697 			 */
8698 			if (!lun->per_res[residx].registered) {
8699 				lun->pr_key_count++;
8700 				lun->per_res[residx].registered = 1;
8701 			}
8702 
8703 			memcpy(&lun->per_res[residx].res_key,
8704 			       param->serv_act_res_key,
8705 			       ctl_min(sizeof(param->serv_act_res_key),
8706 			       sizeof(lun->per_res[residx].res_key)));
8707 
8708 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8709 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8710 			persis_io.pr.pr_info.action = CTL_PR_REG_KEY;
8711 			persis_io.pr.pr_info.residx = residx;
8712 			memcpy(persis_io.pr.pr_info.sa_res_key,
8713 			       param->serv_act_res_key,
8714 			       sizeof(param->serv_act_res_key));
8715 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8716 			     &persis_io, sizeof(persis_io), 0)) >
8717 			     CTL_HA_STATUS_SUCCESS) {
8718 				printf("CTL:Persis Out error returned from "
8719 				       "ctl_ha_msg_send %d\n", isc_retval);
8720 			}
8721 		}
8722 		lun->PRGeneration++;
8723 		mtx_unlock(&lun->lun_lock);
8724 
8725 		break;
8726 	}
8727 	case SPRO_RESERVE:
8728 #if 0
8729                 printf("Reserve executed type %d\n", type);
8730 #endif
8731 		mtx_lock(&lun->lun_lock);
8732 		if (lun->flags & CTL_LUN_PR_RESERVED) {
8733 			/*
8734 			 * if this isn't the reservation holder and it's
8735 			 * not a "all registrants" type or if the type is
8736 			 * different then we have a conflict
8737 			 */
8738 			if ((lun->pr_res_idx != residx
8739 			  && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS)
8740 			 || lun->res_type != type) {
8741 				mtx_unlock(&lun->lun_lock);
8742 				free(ctsio->kern_data_ptr, M_CTL);
8743 				ctl_set_reservation_conflict(ctsio);
8744 				ctl_done((union ctl_io *)ctsio);
8745 				return (CTL_RETVAL_COMPLETE);
8746 			}
8747 			mtx_unlock(&lun->lun_lock);
8748 		} else /* create a reservation */ {
8749 			/*
8750 			 * If it's not an "all registrants" type record
8751 			 * reservation holder
8752 			 */
8753 			if (type != SPR_TYPE_WR_EX_AR
8754 			 && type != SPR_TYPE_EX_AC_AR)
8755 				lun->pr_res_idx = residx; /* Res holder */
8756 			else
8757 				lun->pr_res_idx = CTL_PR_ALL_REGISTRANTS;
8758 
8759 			lun->flags |= CTL_LUN_PR_RESERVED;
8760 			lun->res_type = type;
8761 
8762 			mtx_unlock(&lun->lun_lock);
8763 
8764 			/* send msg to other side */
8765 			persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8766 			persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8767 			persis_io.pr.pr_info.action = CTL_PR_RESERVE;
8768 			persis_io.pr.pr_info.residx = lun->pr_res_idx;
8769 			persis_io.pr.pr_info.res_type = type;
8770 			if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
8771 			     &persis_io, sizeof(persis_io), 0)) >
8772 			     CTL_HA_STATUS_SUCCESS) {
8773 				printf("CTL:Persis Out error returned from "
8774 				       "ctl_ha_msg_send %d\n", isc_retval);
8775 			}
8776 		}
8777 		break;
8778 
8779 	case SPRO_RELEASE:
8780 		mtx_lock(&lun->lun_lock);
8781 		if ((lun->flags & CTL_LUN_PR_RESERVED) == 0) {
8782 			/* No reservation exists return good status */
8783 			mtx_unlock(&lun->lun_lock);
8784 			goto done;
8785 		}
8786 		/*
8787 		 * Is this nexus a reservation holder?
8788 		 */
8789 		if (lun->pr_res_idx != residx
8790 		 && lun->pr_res_idx != CTL_PR_ALL_REGISTRANTS) {
8791 			/*
8792 			 * not a res holder return good status but
8793 			 * do nothing
8794 			 */
8795 			mtx_unlock(&lun->lun_lock);
8796 			goto done;
8797 		}
8798 
8799 		if (lun->res_type != type) {
8800 			mtx_unlock(&lun->lun_lock);
8801 			free(ctsio->kern_data_ptr, M_CTL);
8802 			ctl_set_illegal_pr_release(ctsio);
8803 			ctl_done((union ctl_io *)ctsio);
8804 			return (CTL_RETVAL_COMPLETE);
8805 		}
8806 
8807 		/* okay to release */
8808 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8809 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8810 		lun->res_type = 0;
8811 
8812 		/*
8813 		 * if this isn't an exclusive access
8814 		 * res generate UA for all other
8815 		 * registrants.
8816 		 */
8817 		if (type != SPR_TYPE_EX_AC
8818 		 && type != SPR_TYPE_WR_EX) {
8819 			/*
8820 			 * temporarily unregister so we don't generate UA
8821 			 */
8822 			lun->per_res[residx].registered = 0;
8823 
8824 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8825 				if (lun->per_res[i+persis_offset].registered
8826 				    == 0)
8827 					continue;
8828 				lun->pending_ua[i] |=
8829 					CTL_UA_RES_RELEASE;
8830 			}
8831 
8832 			lun->per_res[residx].registered = 1;
8833 		}
8834 		mtx_unlock(&lun->lun_lock);
8835 		/* Send msg to other side */
8836 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8837 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8838 		persis_io.pr.pr_info.action = CTL_PR_RELEASE;
8839 		if ((isc_retval=ctl_ha_msg_send( CTL_HA_CHAN_CTL, &persis_io,
8840 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8841 			printf("CTL:Persis Out error returned from "
8842 			       "ctl_ha_msg_send %d\n", isc_retval);
8843 		}
8844 		break;
8845 
8846 	case SPRO_CLEAR:
8847 		/* send msg to other side */
8848 
8849 		mtx_lock(&lun->lun_lock);
8850 		lun->flags &= ~CTL_LUN_PR_RESERVED;
8851 		lun->res_type = 0;
8852 		lun->pr_key_count = 0;
8853 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8854 
8855 
8856 		memset(&lun->per_res[residx].res_key,
8857 		       0, sizeof(lun->per_res[residx].res_key));
8858 		lun->per_res[residx].registered = 0;
8859 
8860 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++)
8861 			if (lun->per_res[i].registered) {
8862 				if (!persis_offset && i < CTL_MAX_INITIATORS)
8863 					lun->pending_ua[i] |=
8864 						CTL_UA_RES_PREEMPT;
8865 				else if (persis_offset && i >= persis_offset)
8866 					lun->pending_ua[i-persis_offset] |=
8867 					    CTL_UA_RES_PREEMPT;
8868 
8869 				memset(&lun->per_res[i].res_key,
8870 				       0, sizeof(struct scsi_per_res_key));
8871 				lun->per_res[i].registered = 0;
8872 			}
8873 		lun->PRGeneration++;
8874 		mtx_unlock(&lun->lun_lock);
8875 		persis_io.hdr.nexus = ctsio->io_hdr.nexus;
8876 		persis_io.hdr.msg_type = CTL_MSG_PERS_ACTION;
8877 		persis_io.pr.pr_info.action = CTL_PR_CLEAR;
8878 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL, &persis_io,
8879 		     sizeof(persis_io), 0)) > CTL_HA_STATUS_SUCCESS) {
8880 			printf("CTL:Persis Out error returned from "
8881 			       "ctl_ha_msg_send %d\n", isc_retval);
8882 		}
8883 		break;
8884 
8885 	case SPRO_PREEMPT: {
8886 		int nretval;
8887 
8888 		nretval = ctl_pro_preempt(softc, lun, res_key, sa_res_key, type,
8889 					  residx, ctsio, cdb, param);
8890 		if (nretval != 0)
8891 			return (CTL_RETVAL_COMPLETE);
8892 		break;
8893 	}
8894 	default:
8895 		panic("Invalid PR type %x", cdb->action);
8896 	}
8897 
8898 done:
8899 	free(ctsio->kern_data_ptr, M_CTL);
8900 	ctl_set_success(ctsio);
8901 	ctl_done((union ctl_io *)ctsio);
8902 
8903 	return (retval);
8904 }
8905 
8906 /*
8907  * This routine is for handling a message from the other SC pertaining to
8908  * persistent reserve out. All the error checking will have been done
8909  * so only perorming the action need be done here to keep the two
8910  * in sync.
8911  */
8912 static void
8913 ctl_hndl_per_res_out_on_other_sc(union ctl_ha_msg *msg)
8914 {
8915 	struct ctl_lun *lun;
8916 	struct ctl_softc *softc;
8917 	int i;
8918 	uint32_t targ_lun;
8919 
8920 	softc = control_softc;
8921 
8922 	targ_lun = msg->hdr.nexus.targ_mapped_lun;
8923 	lun = softc->ctl_luns[targ_lun];
8924 	mtx_lock(&lun->lun_lock);
8925 	switch(msg->pr.pr_info.action) {
8926 	case CTL_PR_REG_KEY:
8927 		if (!lun->per_res[msg->pr.pr_info.residx].registered) {
8928 			lun->per_res[msg->pr.pr_info.residx].registered = 1;
8929 			lun->pr_key_count++;
8930 		}
8931 		lun->PRGeneration++;
8932 		memcpy(&lun->per_res[msg->pr.pr_info.residx].res_key,
8933 		       msg->pr.pr_info.sa_res_key,
8934 		       sizeof(struct scsi_per_res_key));
8935 		break;
8936 
8937 	case CTL_PR_UNREG_KEY:
8938 		lun->per_res[msg->pr.pr_info.residx].registered = 0;
8939 		memset(&lun->per_res[msg->pr.pr_info.residx].res_key,
8940 		       0, sizeof(struct scsi_per_res_key));
8941 		lun->pr_key_count--;
8942 
8943 		/* XXX Need to see if the reservation has been released */
8944 		/* if so do we need to generate UA? */
8945 		if (msg->pr.pr_info.residx == lun->pr_res_idx) {
8946 			lun->flags &= ~CTL_LUN_PR_RESERVED;
8947 			lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8948 
8949 			if ((lun->res_type == SPR_TYPE_WR_EX_RO
8950 			  || lun->res_type == SPR_TYPE_EX_AC_RO)
8951 			 && lun->pr_key_count) {
8952 				/*
8953 				 * If the reservation is a registrants
8954 				 * only type we need to generate a UA
8955 				 * for other registered inits.  The
8956 				 * sense code should be RESERVATIONS
8957 				 * RELEASED
8958 				 */
8959 
8960 				for (i = 0; i < CTL_MAX_INITIATORS; i++) {
8961 					if (lun->per_res[i+
8962 					    persis_offset].registered == 0)
8963 						continue;
8964 
8965 					lun->pending_ua[i] |=
8966 						CTL_UA_RES_RELEASE;
8967 				}
8968 			}
8969 			lun->res_type = 0;
8970 		} else if (lun->pr_res_idx == CTL_PR_ALL_REGISTRANTS) {
8971 			if (lun->pr_key_count==0) {
8972 				lun->flags &= ~CTL_LUN_PR_RESERVED;
8973 				lun->res_type = 0;
8974 				lun->pr_res_idx = CTL_PR_NO_RESERVATION;
8975 			}
8976 		}
8977 		lun->PRGeneration++;
8978 		break;
8979 
8980 	case CTL_PR_RESERVE:
8981 		lun->flags |= CTL_LUN_PR_RESERVED;
8982 		lun->res_type = msg->pr.pr_info.res_type;
8983 		lun->pr_res_idx = msg->pr.pr_info.residx;
8984 
8985 		break;
8986 
8987 	case CTL_PR_RELEASE:
8988 		/*
8989 		 * if this isn't an exclusive access res generate UA for all
8990 		 * other registrants.
8991 		 */
8992 		if (lun->res_type != SPR_TYPE_EX_AC
8993 		 && lun->res_type != SPR_TYPE_WR_EX) {
8994 			for (i = 0; i < CTL_MAX_INITIATORS; i++)
8995 				if (lun->per_res[i+persis_offset].registered)
8996 					lun->pending_ua[i] |=
8997 						CTL_UA_RES_RELEASE;
8998 		}
8999 
9000 		lun->flags &= ~CTL_LUN_PR_RESERVED;
9001 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9002 		lun->res_type = 0;
9003 		break;
9004 
9005 	case CTL_PR_PREEMPT:
9006 		ctl_pro_preempt_other(lun, msg);
9007 		break;
9008 	case CTL_PR_CLEAR:
9009 		lun->flags &= ~CTL_LUN_PR_RESERVED;
9010 		lun->res_type = 0;
9011 		lun->pr_key_count = 0;
9012 		lun->pr_res_idx = CTL_PR_NO_RESERVATION;
9013 
9014 		for (i=0; i < 2*CTL_MAX_INITIATORS; i++) {
9015 			if (lun->per_res[i].registered == 0)
9016 				continue;
9017 			if (!persis_offset
9018 			 && i < CTL_MAX_INITIATORS)
9019 				lun->pending_ua[i] |= CTL_UA_RES_PREEMPT;
9020 			else if (persis_offset
9021 			      && i >= persis_offset)
9022 				lun->pending_ua[i-persis_offset] |=
9023 					CTL_UA_RES_PREEMPT;
9024 			memset(&lun->per_res[i].res_key, 0,
9025 			       sizeof(struct scsi_per_res_key));
9026 			lun->per_res[i].registered = 0;
9027 		}
9028 		lun->PRGeneration++;
9029 		break;
9030 	}
9031 
9032 	mtx_unlock(&lun->lun_lock);
9033 }
9034 
9035 int
9036 ctl_read_write(struct ctl_scsiio *ctsio)
9037 {
9038 	struct ctl_lun *lun;
9039 	struct ctl_lba_len_flags *lbalen;
9040 	uint64_t lba;
9041 	uint32_t num_blocks;
9042 	int flags, retval;
9043 	int isread;
9044 
9045 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9046 
9047 	CTL_DEBUG_PRINT(("ctl_read_write: command: %#x\n", ctsio->cdb[0]));
9048 
9049 	flags = 0;
9050 	retval = CTL_RETVAL_COMPLETE;
9051 
9052 	isread = ctsio->cdb[0] == READ_6  || ctsio->cdb[0] == READ_10
9053 	      || ctsio->cdb[0] == READ_12 || ctsio->cdb[0] == READ_16;
9054 	if (lun->flags & CTL_LUN_PR_RESERVED && isread) {
9055 		uint32_t residx;
9056 
9057 		/*
9058 		 * XXX KDM need a lock here.
9059 		 */
9060 		residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
9061 		if ((lun->res_type == SPR_TYPE_EX_AC
9062 		  && residx != lun->pr_res_idx)
9063 		 || ((lun->res_type == SPR_TYPE_EX_AC_RO
9064 		   || lun->res_type == SPR_TYPE_EX_AC_AR)
9065 		  && !lun->per_res[residx].registered)) {
9066 			ctl_set_reservation_conflict(ctsio);
9067 			ctl_done((union ctl_io *)ctsio);
9068 			return (CTL_RETVAL_COMPLETE);
9069 	        }
9070 	}
9071 
9072 	switch (ctsio->cdb[0]) {
9073 	case READ_6:
9074 	case WRITE_6: {
9075 		struct scsi_rw_6 *cdb;
9076 
9077 		cdb = (struct scsi_rw_6 *)ctsio->cdb;
9078 
9079 		lba = scsi_3btoul(cdb->addr);
9080 		/* only 5 bits are valid in the most significant address byte */
9081 		lba &= 0x1fffff;
9082 		num_blocks = cdb->length;
9083 		/*
9084 		 * This is correct according to SBC-2.
9085 		 */
9086 		if (num_blocks == 0)
9087 			num_blocks = 256;
9088 		break;
9089 	}
9090 	case READ_10:
9091 	case WRITE_10: {
9092 		struct scsi_rw_10 *cdb;
9093 
9094 		cdb = (struct scsi_rw_10 *)ctsio->cdb;
9095 		if (cdb->byte2 & SRW10_FUA)
9096 			flags |= CTL_LLF_FUA;
9097 		if (cdb->byte2 & SRW10_DPO)
9098 			flags |= CTL_LLF_DPO;
9099 		lba = scsi_4btoul(cdb->addr);
9100 		num_blocks = scsi_2btoul(cdb->length);
9101 		break;
9102 	}
9103 	case WRITE_VERIFY_10: {
9104 		struct scsi_write_verify_10 *cdb;
9105 
9106 		cdb = (struct scsi_write_verify_10 *)ctsio->cdb;
9107 		flags |= CTL_LLF_FUA;
9108 		if (cdb->byte2 & SWV_DPO)
9109 			flags |= CTL_LLF_DPO;
9110 		lba = scsi_4btoul(cdb->addr);
9111 		num_blocks = scsi_2btoul(cdb->length);
9112 		break;
9113 	}
9114 	case READ_12:
9115 	case WRITE_12: {
9116 		struct scsi_rw_12 *cdb;
9117 
9118 		cdb = (struct scsi_rw_12 *)ctsio->cdb;
9119 		if (cdb->byte2 & SRW12_FUA)
9120 			flags |= CTL_LLF_FUA;
9121 		if (cdb->byte2 & SRW12_DPO)
9122 			flags |= CTL_LLF_DPO;
9123 		lba = scsi_4btoul(cdb->addr);
9124 		num_blocks = scsi_4btoul(cdb->length);
9125 		break;
9126 	}
9127 	case WRITE_VERIFY_12: {
9128 		struct scsi_write_verify_12 *cdb;
9129 
9130 		cdb = (struct scsi_write_verify_12 *)ctsio->cdb;
9131 		flags |= CTL_LLF_FUA;
9132 		if (cdb->byte2 & SWV_DPO)
9133 			flags |= CTL_LLF_DPO;
9134 		lba = scsi_4btoul(cdb->addr);
9135 		num_blocks = scsi_4btoul(cdb->length);
9136 		break;
9137 	}
9138 	case READ_16:
9139 	case WRITE_16: {
9140 		struct scsi_rw_16 *cdb;
9141 
9142 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9143 		if (cdb->byte2 & SRW12_FUA)
9144 			flags |= CTL_LLF_FUA;
9145 		if (cdb->byte2 & SRW12_DPO)
9146 			flags |= CTL_LLF_DPO;
9147 		lba = scsi_8btou64(cdb->addr);
9148 		num_blocks = scsi_4btoul(cdb->length);
9149 		break;
9150 	}
9151 	case WRITE_ATOMIC_16: {
9152 		struct scsi_rw_16 *cdb;
9153 
9154 		if (lun->be_lun->atomicblock == 0) {
9155 			ctl_set_invalid_opcode(ctsio);
9156 			ctl_done((union ctl_io *)ctsio);
9157 			return (CTL_RETVAL_COMPLETE);
9158 		}
9159 
9160 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9161 		if (cdb->byte2 & SRW12_FUA)
9162 			flags |= CTL_LLF_FUA;
9163 		if (cdb->byte2 & SRW12_DPO)
9164 			flags |= CTL_LLF_DPO;
9165 		lba = scsi_8btou64(cdb->addr);
9166 		num_blocks = scsi_4btoul(cdb->length);
9167 		if (num_blocks > lun->be_lun->atomicblock) {
9168 			ctl_set_invalid_field(ctsio, /*sks_valid*/ 1,
9169 			    /*command*/ 1, /*field*/ 12, /*bit_valid*/ 0,
9170 			    /*bit*/ 0);
9171 			ctl_done((union ctl_io *)ctsio);
9172 			return (CTL_RETVAL_COMPLETE);
9173 		}
9174 		break;
9175 	}
9176 	case WRITE_VERIFY_16: {
9177 		struct scsi_write_verify_16 *cdb;
9178 
9179 		cdb = (struct scsi_write_verify_16 *)ctsio->cdb;
9180 		flags |= CTL_LLF_FUA;
9181 		if (cdb->byte2 & SWV_DPO)
9182 			flags |= CTL_LLF_DPO;
9183 		lba = scsi_8btou64(cdb->addr);
9184 		num_blocks = scsi_4btoul(cdb->length);
9185 		break;
9186 	}
9187 	default:
9188 		/*
9189 		 * We got a command we don't support.  This shouldn't
9190 		 * happen, commands should be filtered out above us.
9191 		 */
9192 		ctl_set_invalid_opcode(ctsio);
9193 		ctl_done((union ctl_io *)ctsio);
9194 
9195 		return (CTL_RETVAL_COMPLETE);
9196 		break; /* NOTREACHED */
9197 	}
9198 
9199 	/*
9200 	 * The first check is to make sure we're in bounds, the second
9201 	 * check is to catch wrap-around problems.  If the lba + num blocks
9202 	 * is less than the lba, then we've wrapped around and the block
9203 	 * range is invalid anyway.
9204 	 */
9205 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9206 	 || ((lba + num_blocks) < lba)) {
9207 		ctl_set_lba_out_of_range(ctsio);
9208 		ctl_done((union ctl_io *)ctsio);
9209 		return (CTL_RETVAL_COMPLETE);
9210 	}
9211 
9212 	/*
9213 	 * According to SBC-3, a transfer length of 0 is not an error.
9214 	 * Note that this cannot happen with WRITE(6) or READ(6), since 0
9215 	 * translates to 256 blocks for those commands.
9216 	 */
9217 	if (num_blocks == 0) {
9218 		ctl_set_success(ctsio);
9219 		ctl_done((union ctl_io *)ctsio);
9220 		return (CTL_RETVAL_COMPLETE);
9221 	}
9222 
9223 	/* Set FUA and/or DPO if caches are disabled. */
9224 	if (isread) {
9225 		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9226 		    SCP_RCD) != 0)
9227 			flags |= CTL_LLF_FUA | CTL_LLF_DPO;
9228 	} else {
9229 		if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9230 		    SCP_WCE) == 0)
9231 			flags |= CTL_LLF_FUA;
9232 	}
9233 
9234 	lbalen = (struct ctl_lba_len_flags *)
9235 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9236 	lbalen->lba = lba;
9237 	lbalen->len = num_blocks;
9238 	lbalen->flags = (isread ? CTL_LLF_READ : CTL_LLF_WRITE) | flags;
9239 
9240 	ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9241 	ctsio->kern_rel_offset = 0;
9242 
9243 	CTL_DEBUG_PRINT(("ctl_read_write: calling data_submit()\n"));
9244 
9245 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9246 
9247 	return (retval);
9248 }
9249 
9250 static int
9251 ctl_cnw_cont(union ctl_io *io)
9252 {
9253 	struct ctl_scsiio *ctsio;
9254 	struct ctl_lun *lun;
9255 	struct ctl_lba_len_flags *lbalen;
9256 	int retval;
9257 
9258 	ctsio = &io->scsiio;
9259 	ctsio->io_hdr.status = CTL_STATUS_NONE;
9260 	ctsio->io_hdr.flags &= ~CTL_FLAG_IO_CONT;
9261 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9262 	lbalen = (struct ctl_lba_len_flags *)
9263 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9264 	lbalen->flags &= ~CTL_LLF_COMPARE;
9265 	lbalen->flags |= CTL_LLF_WRITE;
9266 
9267 	CTL_DEBUG_PRINT(("ctl_cnw_cont: calling data_submit()\n"));
9268 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9269 	return (retval);
9270 }
9271 
9272 int
9273 ctl_cnw(struct ctl_scsiio *ctsio)
9274 {
9275 	struct ctl_lun *lun;
9276 	struct ctl_lba_len_flags *lbalen;
9277 	uint64_t lba;
9278 	uint32_t num_blocks;
9279 	int flags, retval;
9280 
9281 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9282 
9283 	CTL_DEBUG_PRINT(("ctl_cnw: command: %#x\n", ctsio->cdb[0]));
9284 
9285 	flags = 0;
9286 	retval = CTL_RETVAL_COMPLETE;
9287 
9288 	switch (ctsio->cdb[0]) {
9289 	case COMPARE_AND_WRITE: {
9290 		struct scsi_compare_and_write *cdb;
9291 
9292 		cdb = (struct scsi_compare_and_write *)ctsio->cdb;
9293 		if (cdb->byte2 & SRW10_FUA)
9294 			flags |= CTL_LLF_FUA;
9295 		if (cdb->byte2 & SRW10_DPO)
9296 			flags |= CTL_LLF_DPO;
9297 		lba = scsi_8btou64(cdb->addr);
9298 		num_blocks = cdb->length;
9299 		break;
9300 	}
9301 	default:
9302 		/*
9303 		 * We got a command we don't support.  This shouldn't
9304 		 * happen, commands should be filtered out above us.
9305 		 */
9306 		ctl_set_invalid_opcode(ctsio);
9307 		ctl_done((union ctl_io *)ctsio);
9308 
9309 		return (CTL_RETVAL_COMPLETE);
9310 		break; /* NOTREACHED */
9311 	}
9312 
9313 	/*
9314 	 * The first check is to make sure we're in bounds, the second
9315 	 * check is to catch wrap-around problems.  If the lba + num blocks
9316 	 * is less than the lba, then we've wrapped around and the block
9317 	 * range is invalid anyway.
9318 	 */
9319 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9320 	 || ((lba + num_blocks) < lba)) {
9321 		ctl_set_lba_out_of_range(ctsio);
9322 		ctl_done((union ctl_io *)ctsio);
9323 		return (CTL_RETVAL_COMPLETE);
9324 	}
9325 
9326 	/*
9327 	 * According to SBC-3, a transfer length of 0 is not an error.
9328 	 */
9329 	if (num_blocks == 0) {
9330 		ctl_set_success(ctsio);
9331 		ctl_done((union ctl_io *)ctsio);
9332 		return (CTL_RETVAL_COMPLETE);
9333 	}
9334 
9335 	/* Set FUA if write cache is disabled. */
9336 	if ((lun->mode_pages.caching_page[CTL_PAGE_CURRENT].flags1 &
9337 	    SCP_WCE) == 0)
9338 		flags |= CTL_LLF_FUA;
9339 
9340 	ctsio->kern_total_len = 2 * num_blocks * lun->be_lun->blocksize;
9341 	ctsio->kern_rel_offset = 0;
9342 
9343 	/*
9344 	 * Set the IO_CONT flag, so that if this I/O gets passed to
9345 	 * ctl_data_submit_done(), it'll get passed back to
9346 	 * ctl_ctl_cnw_cont() for further processing.
9347 	 */
9348 	ctsio->io_hdr.flags |= CTL_FLAG_IO_CONT;
9349 	ctsio->io_cont = ctl_cnw_cont;
9350 
9351 	lbalen = (struct ctl_lba_len_flags *)
9352 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9353 	lbalen->lba = lba;
9354 	lbalen->len = num_blocks;
9355 	lbalen->flags = CTL_LLF_COMPARE | flags;
9356 
9357 	CTL_DEBUG_PRINT(("ctl_cnw: calling data_submit()\n"));
9358 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9359 	return (retval);
9360 }
9361 
9362 int
9363 ctl_verify(struct ctl_scsiio *ctsio)
9364 {
9365 	struct ctl_lun *lun;
9366 	struct ctl_lba_len_flags *lbalen;
9367 	uint64_t lba;
9368 	uint32_t num_blocks;
9369 	int bytchk, flags;
9370 	int retval;
9371 
9372 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9373 
9374 	CTL_DEBUG_PRINT(("ctl_verify: command: %#x\n", ctsio->cdb[0]));
9375 
9376 	bytchk = 0;
9377 	flags = CTL_LLF_FUA;
9378 	retval = CTL_RETVAL_COMPLETE;
9379 
9380 	switch (ctsio->cdb[0]) {
9381 	case VERIFY_10: {
9382 		struct scsi_verify_10 *cdb;
9383 
9384 		cdb = (struct scsi_verify_10 *)ctsio->cdb;
9385 		if (cdb->byte2 & SVFY_BYTCHK)
9386 			bytchk = 1;
9387 		if (cdb->byte2 & SVFY_DPO)
9388 			flags |= CTL_LLF_DPO;
9389 		lba = scsi_4btoul(cdb->addr);
9390 		num_blocks = scsi_2btoul(cdb->length);
9391 		break;
9392 	}
9393 	case VERIFY_12: {
9394 		struct scsi_verify_12 *cdb;
9395 
9396 		cdb = (struct scsi_verify_12 *)ctsio->cdb;
9397 		if (cdb->byte2 & SVFY_BYTCHK)
9398 			bytchk = 1;
9399 		if (cdb->byte2 & SVFY_DPO)
9400 			flags |= CTL_LLF_DPO;
9401 		lba = scsi_4btoul(cdb->addr);
9402 		num_blocks = scsi_4btoul(cdb->length);
9403 		break;
9404 	}
9405 	case VERIFY_16: {
9406 		struct scsi_rw_16 *cdb;
9407 
9408 		cdb = (struct scsi_rw_16 *)ctsio->cdb;
9409 		if (cdb->byte2 & SVFY_BYTCHK)
9410 			bytchk = 1;
9411 		if (cdb->byte2 & SVFY_DPO)
9412 			flags |= CTL_LLF_DPO;
9413 		lba = scsi_8btou64(cdb->addr);
9414 		num_blocks = scsi_4btoul(cdb->length);
9415 		break;
9416 	}
9417 	default:
9418 		/*
9419 		 * We got a command we don't support.  This shouldn't
9420 		 * happen, commands should be filtered out above us.
9421 		 */
9422 		ctl_set_invalid_opcode(ctsio);
9423 		ctl_done((union ctl_io *)ctsio);
9424 		return (CTL_RETVAL_COMPLETE);
9425 	}
9426 
9427 	/*
9428 	 * The first check is to make sure we're in bounds, the second
9429 	 * check is to catch wrap-around problems.  If the lba + num blocks
9430 	 * is less than the lba, then we've wrapped around and the block
9431 	 * range is invalid anyway.
9432 	 */
9433 	if (((lba + num_blocks) > (lun->be_lun->maxlba + 1))
9434 	 || ((lba + num_blocks) < lba)) {
9435 		ctl_set_lba_out_of_range(ctsio);
9436 		ctl_done((union ctl_io *)ctsio);
9437 		return (CTL_RETVAL_COMPLETE);
9438 	}
9439 
9440 	/*
9441 	 * According to SBC-3, a transfer length of 0 is not an error.
9442 	 */
9443 	if (num_blocks == 0) {
9444 		ctl_set_success(ctsio);
9445 		ctl_done((union ctl_io *)ctsio);
9446 		return (CTL_RETVAL_COMPLETE);
9447 	}
9448 
9449 	lbalen = (struct ctl_lba_len_flags *)
9450 	    &ctsio->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
9451 	lbalen->lba = lba;
9452 	lbalen->len = num_blocks;
9453 	if (bytchk) {
9454 		lbalen->flags = CTL_LLF_COMPARE | flags;
9455 		ctsio->kern_total_len = num_blocks * lun->be_lun->blocksize;
9456 	} else {
9457 		lbalen->flags = CTL_LLF_VERIFY | flags;
9458 		ctsio->kern_total_len = 0;
9459 	}
9460 	ctsio->kern_rel_offset = 0;
9461 
9462 	CTL_DEBUG_PRINT(("ctl_verify: calling data_submit()\n"));
9463 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
9464 	return (retval);
9465 }
9466 
9467 int
9468 ctl_report_luns(struct ctl_scsiio *ctsio)
9469 {
9470 	struct scsi_report_luns *cdb;
9471 	struct scsi_report_luns_data *lun_data;
9472 	struct ctl_lun *lun, *request_lun;
9473 	int num_luns, retval;
9474 	uint32_t alloc_len, lun_datalen;
9475 	int num_filled, well_known;
9476 	uint32_t initidx, targ_lun_id, lun_id;
9477 
9478 	retval = CTL_RETVAL_COMPLETE;
9479 	well_known = 0;
9480 
9481 	cdb = (struct scsi_report_luns *)ctsio->cdb;
9482 
9483 	CTL_DEBUG_PRINT(("ctl_report_luns\n"));
9484 
9485 	mtx_lock(&control_softc->ctl_lock);
9486 	num_luns = control_softc->num_luns;
9487 	mtx_unlock(&control_softc->ctl_lock);
9488 
9489 	switch (cdb->select_report) {
9490 	case RPL_REPORT_DEFAULT:
9491 	case RPL_REPORT_ALL:
9492 		break;
9493 	case RPL_REPORT_WELLKNOWN:
9494 		well_known = 1;
9495 		num_luns = 0;
9496 		break;
9497 	default:
9498 		ctl_set_invalid_field(ctsio,
9499 				      /*sks_valid*/ 1,
9500 				      /*command*/ 1,
9501 				      /*field*/ 2,
9502 				      /*bit_valid*/ 0,
9503 				      /*bit*/ 0);
9504 		ctl_done((union ctl_io *)ctsio);
9505 		return (retval);
9506 		break; /* NOTREACHED */
9507 	}
9508 
9509 	alloc_len = scsi_4btoul(cdb->length);
9510 	/*
9511 	 * The initiator has to allocate at least 16 bytes for this request,
9512 	 * so he can at least get the header and the first LUN.  Otherwise
9513 	 * we reject the request (per SPC-3 rev 14, section 6.21).
9514 	 */
9515 	if (alloc_len < (sizeof(struct scsi_report_luns_data) +
9516 	    sizeof(struct scsi_report_luns_lundata))) {
9517 		ctl_set_invalid_field(ctsio,
9518 				      /*sks_valid*/ 1,
9519 				      /*command*/ 1,
9520 				      /*field*/ 6,
9521 				      /*bit_valid*/ 0,
9522 				      /*bit*/ 0);
9523 		ctl_done((union ctl_io *)ctsio);
9524 		return (retval);
9525 	}
9526 
9527 	request_lun = (struct ctl_lun *)
9528 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9529 
9530 	lun_datalen = sizeof(*lun_data) +
9531 		(num_luns * sizeof(struct scsi_report_luns_lundata));
9532 
9533 	ctsio->kern_data_ptr = malloc(lun_datalen, M_CTL, M_WAITOK | M_ZERO);
9534 	lun_data = (struct scsi_report_luns_data *)ctsio->kern_data_ptr;
9535 	ctsio->kern_sg_entries = 0;
9536 
9537 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9538 
9539 	mtx_lock(&control_softc->ctl_lock);
9540 	for (targ_lun_id = 0, num_filled = 0; targ_lun_id < CTL_MAX_LUNS && num_filled < num_luns; targ_lun_id++) {
9541 		lun_id = ctl_map_lun(ctsio->io_hdr.nexus.targ_port, targ_lun_id);
9542 		if (lun_id >= CTL_MAX_LUNS)
9543 			continue;
9544 		lun = control_softc->ctl_luns[lun_id];
9545 		if (lun == NULL)
9546 			continue;
9547 
9548 		if (targ_lun_id <= 0xff) {
9549 			/*
9550 			 * Peripheral addressing method, bus number 0.
9551 			 */
9552 			lun_data->luns[num_filled].lundata[0] =
9553 				RPL_LUNDATA_ATYP_PERIPH;
9554 			lun_data->luns[num_filled].lundata[1] = targ_lun_id;
9555 			num_filled++;
9556 		} else if (targ_lun_id <= 0x3fff) {
9557 			/*
9558 			 * Flat addressing method.
9559 			 */
9560 			lun_data->luns[num_filled].lundata[0] =
9561 				RPL_LUNDATA_ATYP_FLAT |
9562 				(targ_lun_id & RPL_LUNDATA_FLAT_LUN_MASK);
9563 #ifdef OLDCTLHEADERS
9564 				(SRLD_ADDR_FLAT << SRLD_ADDR_SHIFT) |
9565 				(targ_lun_id & SRLD_BUS_LUN_MASK);
9566 #endif
9567 			lun_data->luns[num_filled].lundata[1] =
9568 #ifdef OLDCTLHEADERS
9569 				targ_lun_id >> SRLD_BUS_LUN_BITS;
9570 #endif
9571 				targ_lun_id >> RPL_LUNDATA_FLAT_LUN_BITS;
9572 			num_filled++;
9573 		} else {
9574 			printf("ctl_report_luns: bogus LUN number %jd, "
9575 			       "skipping\n", (intmax_t)targ_lun_id);
9576 		}
9577 		/*
9578 		 * According to SPC-3, rev 14 section 6.21:
9579 		 *
9580 		 * "The execution of a REPORT LUNS command to any valid and
9581 		 * installed logical unit shall clear the REPORTED LUNS DATA
9582 		 * HAS CHANGED unit attention condition for all logical
9583 		 * units of that target with respect to the requesting
9584 		 * initiator. A valid and installed logical unit is one
9585 		 * having a PERIPHERAL QUALIFIER of 000b in the standard
9586 		 * INQUIRY data (see 6.4.2)."
9587 		 *
9588 		 * If request_lun is NULL, the LUN this report luns command
9589 		 * was issued to is either disabled or doesn't exist. In that
9590 		 * case, we shouldn't clear any pending lun change unit
9591 		 * attention.
9592 		 */
9593 		if (request_lun != NULL) {
9594 			mtx_lock(&lun->lun_lock);
9595 			lun->pending_ua[initidx] &= ~CTL_UA_LUN_CHANGE;
9596 			mtx_unlock(&lun->lun_lock);
9597 		}
9598 	}
9599 	mtx_unlock(&control_softc->ctl_lock);
9600 
9601 	/*
9602 	 * It's quite possible that we've returned fewer LUNs than we allocated
9603 	 * space for.  Trim it.
9604 	 */
9605 	lun_datalen = sizeof(*lun_data) +
9606 		(num_filled * sizeof(struct scsi_report_luns_lundata));
9607 
9608 	if (lun_datalen < alloc_len) {
9609 		ctsio->residual = alloc_len - lun_datalen;
9610 		ctsio->kern_data_len = lun_datalen;
9611 		ctsio->kern_total_len = lun_datalen;
9612 	} else {
9613 		ctsio->residual = 0;
9614 		ctsio->kern_data_len = alloc_len;
9615 		ctsio->kern_total_len = alloc_len;
9616 	}
9617 	ctsio->kern_data_resid = 0;
9618 	ctsio->kern_rel_offset = 0;
9619 	ctsio->kern_sg_entries = 0;
9620 
9621 	/*
9622 	 * We set this to the actual data length, regardless of how much
9623 	 * space we actually have to return results.  If the user looks at
9624 	 * this value, he'll know whether or not he allocated enough space
9625 	 * and reissue the command if necessary.  We don't support well
9626 	 * known logical units, so if the user asks for that, return none.
9627 	 */
9628 	scsi_ulto4b(lun_datalen - 8, lun_data->length);
9629 
9630 	/*
9631 	 * We can only return SCSI_STATUS_CHECK_COND when we can't satisfy
9632 	 * this request.
9633 	 */
9634 	ctsio->scsi_status = SCSI_STATUS_OK;
9635 
9636 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9637 	ctsio->be_move_done = ctl_config_move_done;
9638 	ctl_datamove((union ctl_io *)ctsio);
9639 
9640 	return (retval);
9641 }
9642 
9643 int
9644 ctl_request_sense(struct ctl_scsiio *ctsio)
9645 {
9646 	struct scsi_request_sense *cdb;
9647 	struct scsi_sense_data *sense_ptr;
9648 	struct ctl_lun *lun;
9649 	uint32_t initidx;
9650 	int have_error;
9651 	scsi_sense_data_type sense_format;
9652 
9653 	cdb = (struct scsi_request_sense *)ctsio->cdb;
9654 
9655 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9656 
9657 	CTL_DEBUG_PRINT(("ctl_request_sense\n"));
9658 
9659 	/*
9660 	 * Determine which sense format the user wants.
9661 	 */
9662 	if (cdb->byte2 & SRS_DESC)
9663 		sense_format = SSD_TYPE_DESC;
9664 	else
9665 		sense_format = SSD_TYPE_FIXED;
9666 
9667 	ctsio->kern_data_ptr = malloc(sizeof(*sense_ptr), M_CTL, M_WAITOK);
9668 	sense_ptr = (struct scsi_sense_data *)ctsio->kern_data_ptr;
9669 	ctsio->kern_sg_entries = 0;
9670 
9671 	/*
9672 	 * struct scsi_sense_data, which is currently set to 256 bytes, is
9673 	 * larger than the largest allowed value for the length field in the
9674 	 * REQUEST SENSE CDB, which is 252 bytes as of SPC-4.
9675 	 */
9676 	ctsio->residual = 0;
9677 	ctsio->kern_data_len = cdb->length;
9678 	ctsio->kern_total_len = cdb->length;
9679 
9680 	ctsio->kern_data_resid = 0;
9681 	ctsio->kern_rel_offset = 0;
9682 	ctsio->kern_sg_entries = 0;
9683 
9684 	/*
9685 	 * If we don't have a LUN, we don't have any pending sense.
9686 	 */
9687 	if (lun == NULL)
9688 		goto no_sense;
9689 
9690 	have_error = 0;
9691 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
9692 	/*
9693 	 * Check for pending sense, and then for pending unit attentions.
9694 	 * Pending sense gets returned first, then pending unit attentions.
9695 	 */
9696 	mtx_lock(&lun->lun_lock);
9697 #ifdef CTL_WITH_CA
9698 	if (ctl_is_set(lun->have_ca, initidx)) {
9699 		scsi_sense_data_type stored_format;
9700 
9701 		/*
9702 		 * Check to see which sense format was used for the stored
9703 		 * sense data.
9704 		 */
9705 		stored_format = scsi_sense_type(&lun->pending_sense[initidx]);
9706 
9707 		/*
9708 		 * If the user requested a different sense format than the
9709 		 * one we stored, then we need to convert it to the other
9710 		 * format.  If we're going from descriptor to fixed format
9711 		 * sense data, we may lose things in translation, depending
9712 		 * on what options were used.
9713 		 *
9714 		 * If the stored format is SSD_TYPE_NONE (i.e. invalid),
9715 		 * for some reason we'll just copy it out as-is.
9716 		 */
9717 		if ((stored_format == SSD_TYPE_FIXED)
9718 		 && (sense_format == SSD_TYPE_DESC))
9719 			ctl_sense_to_desc((struct scsi_sense_data_fixed *)
9720 			    &lun->pending_sense[initidx],
9721 			    (struct scsi_sense_data_desc *)sense_ptr);
9722 		else if ((stored_format == SSD_TYPE_DESC)
9723 		      && (sense_format == SSD_TYPE_FIXED))
9724 			ctl_sense_to_fixed((struct scsi_sense_data_desc *)
9725 			    &lun->pending_sense[initidx],
9726 			    (struct scsi_sense_data_fixed *)sense_ptr);
9727 		else
9728 			memcpy(sense_ptr, &lun->pending_sense[initidx],
9729 			       ctl_min(sizeof(*sense_ptr),
9730 			       sizeof(lun->pending_sense[initidx])));
9731 
9732 		ctl_clear_mask(lun->have_ca, initidx);
9733 		have_error = 1;
9734 	} else
9735 #endif
9736 	if (lun->pending_ua[initidx] != CTL_UA_NONE) {
9737 		ctl_ua_type ua_type;
9738 
9739 		ua_type = ctl_build_ua(&lun->pending_ua[initidx],
9740 				       sense_ptr, sense_format);
9741 		if (ua_type != CTL_UA_NONE)
9742 			have_error = 1;
9743 	}
9744 	mtx_unlock(&lun->lun_lock);
9745 
9746 	/*
9747 	 * We already have a pending error, return it.
9748 	 */
9749 	if (have_error != 0) {
9750 		/*
9751 		 * We report the SCSI status as OK, since the status of the
9752 		 * request sense command itself is OK.
9753 		 */
9754 		ctsio->scsi_status = SCSI_STATUS_OK;
9755 
9756 		/*
9757 		 * We report 0 for the sense length, because we aren't doing
9758 		 * autosense in this case.  We're reporting sense as
9759 		 * parameter data.
9760 		 */
9761 		ctsio->sense_len = 0;
9762 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9763 		ctsio->be_move_done = ctl_config_move_done;
9764 		ctl_datamove((union ctl_io *)ctsio);
9765 
9766 		return (CTL_RETVAL_COMPLETE);
9767 	}
9768 
9769 no_sense:
9770 
9771 	/*
9772 	 * No sense information to report, so we report that everything is
9773 	 * okay.
9774 	 */
9775 	ctl_set_sense_data(sense_ptr,
9776 			   lun,
9777 			   sense_format,
9778 			   /*current_error*/ 1,
9779 			   /*sense_key*/ SSD_KEY_NO_SENSE,
9780 			   /*asc*/ 0x00,
9781 			   /*ascq*/ 0x00,
9782 			   SSD_ELEM_NONE);
9783 
9784 	ctsio->scsi_status = SCSI_STATUS_OK;
9785 
9786 	/*
9787 	 * We report 0 for the sense length, because we aren't doing
9788 	 * autosense in this case.  We're reporting sense as parameter data.
9789 	 */
9790 	ctsio->sense_len = 0;
9791 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9792 	ctsio->be_move_done = ctl_config_move_done;
9793 	ctl_datamove((union ctl_io *)ctsio);
9794 
9795 	return (CTL_RETVAL_COMPLETE);
9796 }
9797 
9798 int
9799 ctl_tur(struct ctl_scsiio *ctsio)
9800 {
9801 	struct ctl_lun *lun;
9802 
9803 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9804 
9805 	CTL_DEBUG_PRINT(("ctl_tur\n"));
9806 
9807 	if (lun == NULL)
9808 		return (EINVAL);
9809 
9810 	ctsio->scsi_status = SCSI_STATUS_OK;
9811 	ctsio->io_hdr.status = CTL_SUCCESS;
9812 
9813 	ctl_done((union ctl_io *)ctsio);
9814 
9815 	return (CTL_RETVAL_COMPLETE);
9816 }
9817 
9818 #ifdef notyet
9819 static int
9820 ctl_cmddt_inquiry(struct ctl_scsiio *ctsio)
9821 {
9822 
9823 }
9824 #endif
9825 
9826 static int
9827 ctl_inquiry_evpd_supported(struct ctl_scsiio *ctsio, int alloc_len)
9828 {
9829 	struct scsi_vpd_supported_pages *pages;
9830 	int sup_page_size;
9831 	struct ctl_lun *lun;
9832 
9833 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9834 
9835 	sup_page_size = sizeof(struct scsi_vpd_supported_pages) *
9836 	    SCSI_EVPD_NUM_SUPPORTED_PAGES;
9837 	ctsio->kern_data_ptr = malloc(sup_page_size, M_CTL, M_WAITOK | M_ZERO);
9838 	pages = (struct scsi_vpd_supported_pages *)ctsio->kern_data_ptr;
9839 	ctsio->kern_sg_entries = 0;
9840 
9841 	if (sup_page_size < alloc_len) {
9842 		ctsio->residual = alloc_len - sup_page_size;
9843 		ctsio->kern_data_len = sup_page_size;
9844 		ctsio->kern_total_len = sup_page_size;
9845 	} else {
9846 		ctsio->residual = 0;
9847 		ctsio->kern_data_len = alloc_len;
9848 		ctsio->kern_total_len = alloc_len;
9849 	}
9850 	ctsio->kern_data_resid = 0;
9851 	ctsio->kern_rel_offset = 0;
9852 	ctsio->kern_sg_entries = 0;
9853 
9854 	/*
9855 	 * The control device is always connected.  The disk device, on the
9856 	 * other hand, may not be online all the time.  Need to change this
9857 	 * to figure out whether the disk device is actually online or not.
9858 	 */
9859 	if (lun != NULL)
9860 		pages->device = (SID_QUAL_LU_CONNECTED << 5) |
9861 				lun->be_lun->lun_type;
9862 	else
9863 		pages->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9864 
9865 	pages->length = SCSI_EVPD_NUM_SUPPORTED_PAGES;
9866 	/* Supported VPD pages */
9867 	pages->page_list[0] = SVPD_SUPPORTED_PAGES;
9868 	/* Serial Number */
9869 	pages->page_list[1] = SVPD_UNIT_SERIAL_NUMBER;
9870 	/* Device Identification */
9871 	pages->page_list[2] = SVPD_DEVICE_ID;
9872 	/* Extended INQUIRY Data */
9873 	pages->page_list[3] = SVPD_EXTENDED_INQUIRY_DATA;
9874 	/* Mode Page Policy */
9875 	pages->page_list[4] = SVPD_MODE_PAGE_POLICY;
9876 	/* SCSI Ports */
9877 	pages->page_list[5] = SVPD_SCSI_PORTS;
9878 	/* Third-party Copy */
9879 	pages->page_list[6] = SVPD_SCSI_TPC;
9880 	/* Block limits */
9881 	pages->page_list[7] = SVPD_BLOCK_LIMITS;
9882 	/* Block Device Characteristics */
9883 	pages->page_list[8] = SVPD_BDC;
9884 	/* Logical Block Provisioning */
9885 	pages->page_list[9] = SVPD_LBP;
9886 
9887 	ctsio->scsi_status = SCSI_STATUS_OK;
9888 
9889 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9890 	ctsio->be_move_done = ctl_config_move_done;
9891 	ctl_datamove((union ctl_io *)ctsio);
9892 
9893 	return (CTL_RETVAL_COMPLETE);
9894 }
9895 
9896 static int
9897 ctl_inquiry_evpd_serial(struct ctl_scsiio *ctsio, int alloc_len)
9898 {
9899 	struct scsi_vpd_unit_serial_number *sn_ptr;
9900 	struct ctl_lun *lun;
9901 
9902 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9903 
9904 	ctsio->kern_data_ptr = malloc(sizeof(*sn_ptr), M_CTL, M_WAITOK | M_ZERO);
9905 	sn_ptr = (struct scsi_vpd_unit_serial_number *)ctsio->kern_data_ptr;
9906 	ctsio->kern_sg_entries = 0;
9907 
9908 	if (sizeof(*sn_ptr) < alloc_len) {
9909 		ctsio->residual = alloc_len - sizeof(*sn_ptr);
9910 		ctsio->kern_data_len = sizeof(*sn_ptr);
9911 		ctsio->kern_total_len = sizeof(*sn_ptr);
9912 	} else {
9913 		ctsio->residual = 0;
9914 		ctsio->kern_data_len = alloc_len;
9915 		ctsio->kern_total_len = alloc_len;
9916 	}
9917 	ctsio->kern_data_resid = 0;
9918 	ctsio->kern_rel_offset = 0;
9919 	ctsio->kern_sg_entries = 0;
9920 
9921 	/*
9922 	 * The control device is always connected.  The disk device, on the
9923 	 * other hand, may not be online all the time.  Need to change this
9924 	 * to figure out whether the disk device is actually online or not.
9925 	 */
9926 	if (lun != NULL)
9927 		sn_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9928 				  lun->be_lun->lun_type;
9929 	else
9930 		sn_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9931 
9932 	sn_ptr->page_code = SVPD_UNIT_SERIAL_NUMBER;
9933 	sn_ptr->length = ctl_min(sizeof(*sn_ptr) - 4, CTL_SN_LEN);
9934 	/*
9935 	 * If we don't have a LUN, we just leave the serial number as
9936 	 * all spaces.
9937 	 */
9938 	memset(sn_ptr->serial_num, 0x20, sizeof(sn_ptr->serial_num));
9939 	if (lun != NULL) {
9940 		strncpy((char *)sn_ptr->serial_num,
9941 			(char *)lun->be_lun->serial_num, CTL_SN_LEN);
9942 	}
9943 	ctsio->scsi_status = SCSI_STATUS_OK;
9944 
9945 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9946 	ctsio->be_move_done = ctl_config_move_done;
9947 	ctl_datamove((union ctl_io *)ctsio);
9948 
9949 	return (CTL_RETVAL_COMPLETE);
9950 }
9951 
9952 
9953 static int
9954 ctl_inquiry_evpd_eid(struct ctl_scsiio *ctsio, int alloc_len)
9955 {
9956 	struct scsi_vpd_extended_inquiry_data *eid_ptr;
9957 	struct ctl_lun *lun;
9958 	int data_len;
9959 
9960 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
9961 
9962 	data_len = sizeof(struct scsi_vpd_extended_inquiry_data);
9963 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
9964 	eid_ptr = (struct scsi_vpd_extended_inquiry_data *)ctsio->kern_data_ptr;
9965 	ctsio->kern_sg_entries = 0;
9966 
9967 	if (data_len < alloc_len) {
9968 		ctsio->residual = alloc_len - data_len;
9969 		ctsio->kern_data_len = data_len;
9970 		ctsio->kern_total_len = data_len;
9971 	} else {
9972 		ctsio->residual = 0;
9973 		ctsio->kern_data_len = alloc_len;
9974 		ctsio->kern_total_len = alloc_len;
9975 	}
9976 	ctsio->kern_data_resid = 0;
9977 	ctsio->kern_rel_offset = 0;
9978 	ctsio->kern_sg_entries = 0;
9979 
9980 	/*
9981 	 * The control device is always connected.  The disk device, on the
9982 	 * other hand, may not be online all the time.
9983 	 */
9984 	if (lun != NULL)
9985 		eid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
9986 				     lun->be_lun->lun_type;
9987 	else
9988 		eid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
9989 	eid_ptr->page_code = SVPD_EXTENDED_INQUIRY_DATA;
9990 	eid_ptr->page_length = data_len - 4;
9991 	eid_ptr->flags2 = SVPD_EID_HEADSUP | SVPD_EID_ORDSUP | SVPD_EID_SIMPSUP;
9992 	eid_ptr->flags3 = SVPD_EID_V_SUP;
9993 
9994 	ctsio->scsi_status = SCSI_STATUS_OK;
9995 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
9996 	ctsio->be_move_done = ctl_config_move_done;
9997 	ctl_datamove((union ctl_io *)ctsio);
9998 
9999 	return (CTL_RETVAL_COMPLETE);
10000 }
10001 
10002 static int
10003 ctl_inquiry_evpd_mpp(struct ctl_scsiio *ctsio, int alloc_len)
10004 {
10005 	struct scsi_vpd_mode_page_policy *mpp_ptr;
10006 	struct ctl_lun *lun;
10007 	int data_len;
10008 
10009 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10010 
10011 	data_len = sizeof(struct scsi_vpd_mode_page_policy) +
10012 	    sizeof(struct scsi_vpd_mode_page_policy_descr);
10013 
10014 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10015 	mpp_ptr = (struct scsi_vpd_mode_page_policy *)ctsio->kern_data_ptr;
10016 	ctsio->kern_sg_entries = 0;
10017 
10018 	if (data_len < alloc_len) {
10019 		ctsio->residual = alloc_len - data_len;
10020 		ctsio->kern_data_len = data_len;
10021 		ctsio->kern_total_len = data_len;
10022 	} else {
10023 		ctsio->residual = 0;
10024 		ctsio->kern_data_len = alloc_len;
10025 		ctsio->kern_total_len = alloc_len;
10026 	}
10027 	ctsio->kern_data_resid = 0;
10028 	ctsio->kern_rel_offset = 0;
10029 	ctsio->kern_sg_entries = 0;
10030 
10031 	/*
10032 	 * The control device is always connected.  The disk device, on the
10033 	 * other hand, may not be online all the time.
10034 	 */
10035 	if (lun != NULL)
10036 		mpp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10037 				     lun->be_lun->lun_type;
10038 	else
10039 		mpp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10040 	mpp_ptr->page_code = SVPD_MODE_PAGE_POLICY;
10041 	scsi_ulto2b(data_len - 4, mpp_ptr->page_length);
10042 	mpp_ptr->descr[0].page_code = 0x3f;
10043 	mpp_ptr->descr[0].subpage_code = 0xff;
10044 	mpp_ptr->descr[0].policy = SVPD_MPP_SHARED;
10045 
10046 	ctsio->scsi_status = SCSI_STATUS_OK;
10047 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10048 	ctsio->be_move_done = ctl_config_move_done;
10049 	ctl_datamove((union ctl_io *)ctsio);
10050 
10051 	return (CTL_RETVAL_COMPLETE);
10052 }
10053 
10054 static int
10055 ctl_inquiry_evpd_devid(struct ctl_scsiio *ctsio, int alloc_len)
10056 {
10057 	struct scsi_vpd_device_id *devid_ptr;
10058 	struct scsi_vpd_id_descriptor *desc;
10059 	struct ctl_softc *ctl_softc;
10060 	struct ctl_lun *lun;
10061 	struct ctl_port *port;
10062 	int data_len;
10063 	uint8_t proto;
10064 
10065 	ctl_softc = control_softc;
10066 
10067 	port = ctl_softc->ctl_ports[ctl_port_idx(ctsio->io_hdr.nexus.targ_port)];
10068 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10069 
10070 	data_len = sizeof(struct scsi_vpd_device_id) +
10071 	    sizeof(struct scsi_vpd_id_descriptor) +
10072 		sizeof(struct scsi_vpd_id_rel_trgt_port_id) +
10073 	    sizeof(struct scsi_vpd_id_descriptor) +
10074 		sizeof(struct scsi_vpd_id_trgt_port_grp_id);
10075 	if (lun && lun->lun_devid)
10076 		data_len += lun->lun_devid->len;
10077 	if (port->port_devid)
10078 		data_len += port->port_devid->len;
10079 	if (port->target_devid)
10080 		data_len += port->target_devid->len;
10081 
10082 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10083 	devid_ptr = (struct scsi_vpd_device_id *)ctsio->kern_data_ptr;
10084 	ctsio->kern_sg_entries = 0;
10085 
10086 	if (data_len < alloc_len) {
10087 		ctsio->residual = alloc_len - data_len;
10088 		ctsio->kern_data_len = data_len;
10089 		ctsio->kern_total_len = data_len;
10090 	} else {
10091 		ctsio->residual = 0;
10092 		ctsio->kern_data_len = alloc_len;
10093 		ctsio->kern_total_len = alloc_len;
10094 	}
10095 	ctsio->kern_data_resid = 0;
10096 	ctsio->kern_rel_offset = 0;
10097 	ctsio->kern_sg_entries = 0;
10098 
10099 	/*
10100 	 * The control device is always connected.  The disk device, on the
10101 	 * other hand, may not be online all the time.
10102 	 */
10103 	if (lun != NULL)
10104 		devid_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10105 				     lun->be_lun->lun_type;
10106 	else
10107 		devid_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10108 	devid_ptr->page_code = SVPD_DEVICE_ID;
10109 	scsi_ulto2b(data_len - 4, devid_ptr->length);
10110 
10111 	if (port->port_type == CTL_PORT_FC)
10112 		proto = SCSI_PROTO_FC << 4;
10113 	else if (port->port_type == CTL_PORT_ISCSI)
10114 		proto = SCSI_PROTO_ISCSI << 4;
10115 	else
10116 		proto = SCSI_PROTO_SPI << 4;
10117 	desc = (struct scsi_vpd_id_descriptor *)devid_ptr->desc_list;
10118 
10119 	/*
10120 	 * We're using a LUN association here.  i.e., this device ID is a
10121 	 * per-LUN identifier.
10122 	 */
10123 	if (lun && lun->lun_devid) {
10124 		memcpy(desc, lun->lun_devid->data, lun->lun_devid->len);
10125 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10126 		    lun->lun_devid->len);
10127 	}
10128 
10129 	/*
10130 	 * This is for the WWPN which is a port association.
10131 	 */
10132 	if (port->port_devid) {
10133 		memcpy(desc, port->port_devid->data, port->port_devid->len);
10134 		desc = (struct scsi_vpd_id_descriptor *)((uint8_t *)desc +
10135 		    port->port_devid->len);
10136 	}
10137 
10138 	/*
10139 	 * This is for the Relative Target Port(type 4h) identifier
10140 	 */
10141 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10142 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10143 	    SVPD_ID_TYPE_RELTARG;
10144 	desc->length = 4;
10145 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port, &desc->identifier[2]);
10146 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10147 	    sizeof(struct scsi_vpd_id_rel_trgt_port_id));
10148 
10149 	/*
10150 	 * This is for the Target Port Group(type 5h) identifier
10151 	 */
10152 	desc->proto_codeset = proto | SVPD_ID_CODESET_BINARY;
10153 	desc->id_type = SVPD_ID_PIV | SVPD_ID_ASSOC_PORT |
10154 	    SVPD_ID_TYPE_TPORTGRP;
10155 	desc->length = 4;
10156 	scsi_ulto2b(ctsio->io_hdr.nexus.targ_port / CTL_MAX_PORTS + 1,
10157 	    &desc->identifier[2]);
10158 	desc = (struct scsi_vpd_id_descriptor *)(&desc->identifier[0] +
10159 	    sizeof(struct scsi_vpd_id_trgt_port_grp_id));
10160 
10161 	/*
10162 	 * This is for the Target identifier
10163 	 */
10164 	if (port->target_devid) {
10165 		memcpy(desc, port->target_devid->data, port->target_devid->len);
10166 	}
10167 
10168 	ctsio->scsi_status = SCSI_STATUS_OK;
10169 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10170 	ctsio->be_move_done = ctl_config_move_done;
10171 	ctl_datamove((union ctl_io *)ctsio);
10172 
10173 	return (CTL_RETVAL_COMPLETE);
10174 }
10175 
10176 static int
10177 ctl_inquiry_evpd_scsi_ports(struct ctl_scsiio *ctsio, int alloc_len)
10178 {
10179 	struct ctl_softc *softc = control_softc;
10180 	struct scsi_vpd_scsi_ports *sp;
10181 	struct scsi_vpd_port_designation *pd;
10182 	struct scsi_vpd_port_designation_cont *pdc;
10183 	struct ctl_lun *lun;
10184 	struct ctl_port *port;
10185 	int data_len, num_target_ports, iid_len, id_len, g, pg, p;
10186 	int num_target_port_groups, single;
10187 
10188 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10189 
10190 	single = ctl_is_single;
10191 	if (single)
10192 		num_target_port_groups = 1;
10193 	else
10194 		num_target_port_groups = NUM_TARGET_PORT_GROUPS;
10195 	num_target_ports = 0;
10196 	iid_len = 0;
10197 	id_len = 0;
10198 	mtx_lock(&softc->ctl_lock);
10199 	STAILQ_FOREACH(port, &softc->port_list, links) {
10200 		if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10201 			continue;
10202 		if (lun != NULL &&
10203 		    ctl_map_lun_back(port->targ_port, lun->lun) >=
10204 		    CTL_MAX_LUNS)
10205 			continue;
10206 		num_target_ports++;
10207 		if (port->init_devid)
10208 			iid_len += port->init_devid->len;
10209 		if (port->port_devid)
10210 			id_len += port->port_devid->len;
10211 	}
10212 	mtx_unlock(&softc->ctl_lock);
10213 
10214 	data_len = sizeof(struct scsi_vpd_scsi_ports) + num_target_port_groups *
10215 	    num_target_ports * (sizeof(struct scsi_vpd_port_designation) +
10216 	     sizeof(struct scsi_vpd_port_designation_cont)) + iid_len + id_len;
10217 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10218 	sp = (struct scsi_vpd_scsi_ports *)ctsio->kern_data_ptr;
10219 	ctsio->kern_sg_entries = 0;
10220 
10221 	if (data_len < alloc_len) {
10222 		ctsio->residual = alloc_len - data_len;
10223 		ctsio->kern_data_len = data_len;
10224 		ctsio->kern_total_len = data_len;
10225 	} else {
10226 		ctsio->residual = 0;
10227 		ctsio->kern_data_len = alloc_len;
10228 		ctsio->kern_total_len = alloc_len;
10229 	}
10230 	ctsio->kern_data_resid = 0;
10231 	ctsio->kern_rel_offset = 0;
10232 	ctsio->kern_sg_entries = 0;
10233 
10234 	/*
10235 	 * The control device is always connected.  The disk device, on the
10236 	 * other hand, may not be online all the time.  Need to change this
10237 	 * to figure out whether the disk device is actually online or not.
10238 	 */
10239 	if (lun != NULL)
10240 		sp->device = (SID_QUAL_LU_CONNECTED << 5) |
10241 				  lun->be_lun->lun_type;
10242 	else
10243 		sp->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10244 
10245 	sp->page_code = SVPD_SCSI_PORTS;
10246 	scsi_ulto2b(data_len - sizeof(struct scsi_vpd_scsi_ports),
10247 	    sp->page_length);
10248 	pd = &sp->design[0];
10249 
10250 	mtx_lock(&softc->ctl_lock);
10251 	if (softc->flags & CTL_FLAG_MASTER_SHELF)
10252 		pg = 0;
10253 	else
10254 		pg = 1;
10255 	for (g = 0; g < num_target_port_groups; g++) {
10256 		STAILQ_FOREACH(port, &softc->port_list, links) {
10257 			if ((port->status & CTL_PORT_STATUS_ONLINE) == 0)
10258 				continue;
10259 			if (lun != NULL &&
10260 			    ctl_map_lun_back(port->targ_port, lun->lun) >=
10261 			    CTL_MAX_LUNS)
10262 				continue;
10263 			p = port->targ_port % CTL_MAX_PORTS + g * CTL_MAX_PORTS;
10264 			scsi_ulto2b(p, pd->relative_port_id);
10265 			if (port->init_devid && g == pg) {
10266 				iid_len = port->init_devid->len;
10267 				memcpy(pd->initiator_transportid,
10268 				    port->init_devid->data, port->init_devid->len);
10269 			} else
10270 				iid_len = 0;
10271 			scsi_ulto2b(iid_len, pd->initiator_transportid_length);
10272 			pdc = (struct scsi_vpd_port_designation_cont *)
10273 			    (&pd->initiator_transportid[iid_len]);
10274 			if (port->port_devid && g == pg) {
10275 				id_len = port->port_devid->len;
10276 				memcpy(pdc->target_port_descriptors,
10277 				    port->port_devid->data, port->port_devid->len);
10278 			} else
10279 				id_len = 0;
10280 			scsi_ulto2b(id_len, pdc->target_port_descriptors_length);
10281 			pd = (struct scsi_vpd_port_designation *)
10282 			    ((uint8_t *)pdc->target_port_descriptors + id_len);
10283 		}
10284 	}
10285 	mtx_unlock(&softc->ctl_lock);
10286 
10287 	ctsio->scsi_status = SCSI_STATUS_OK;
10288 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10289 	ctsio->be_move_done = ctl_config_move_done;
10290 	ctl_datamove((union ctl_io *)ctsio);
10291 
10292 	return (CTL_RETVAL_COMPLETE);
10293 }
10294 
10295 static int
10296 ctl_inquiry_evpd_block_limits(struct ctl_scsiio *ctsio, int alloc_len)
10297 {
10298 	struct scsi_vpd_block_limits *bl_ptr;
10299 	struct ctl_lun *lun;
10300 	int bs;
10301 
10302 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10303 
10304 	ctsio->kern_data_ptr = malloc(sizeof(*bl_ptr), M_CTL, M_WAITOK | M_ZERO);
10305 	bl_ptr = (struct scsi_vpd_block_limits *)ctsio->kern_data_ptr;
10306 	ctsio->kern_sg_entries = 0;
10307 
10308 	if (sizeof(*bl_ptr) < alloc_len) {
10309 		ctsio->residual = alloc_len - sizeof(*bl_ptr);
10310 		ctsio->kern_data_len = sizeof(*bl_ptr);
10311 		ctsio->kern_total_len = sizeof(*bl_ptr);
10312 	} else {
10313 		ctsio->residual = 0;
10314 		ctsio->kern_data_len = alloc_len;
10315 		ctsio->kern_total_len = alloc_len;
10316 	}
10317 	ctsio->kern_data_resid = 0;
10318 	ctsio->kern_rel_offset = 0;
10319 	ctsio->kern_sg_entries = 0;
10320 
10321 	/*
10322 	 * The control device is always connected.  The disk device, on the
10323 	 * other hand, may not be online all the time.  Need to change this
10324 	 * to figure out whether the disk device is actually online or not.
10325 	 */
10326 	if (lun != NULL)
10327 		bl_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10328 				  lun->be_lun->lun_type;
10329 	else
10330 		bl_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10331 
10332 	bl_ptr->page_code = SVPD_BLOCK_LIMITS;
10333 	scsi_ulto2b(sizeof(*bl_ptr) - 4, bl_ptr->page_length);
10334 	bl_ptr->max_cmp_write_len = 0xff;
10335 	scsi_ulto4b(0xffffffff, bl_ptr->max_txfer_len);
10336 	if (lun != NULL) {
10337 		bs = lun->be_lun->blocksize;
10338 		scsi_ulto4b(MAXPHYS / bs, bl_ptr->opt_txfer_len);
10339 		if (lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10340 			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_lba_cnt);
10341 			scsi_ulto4b(0xffffffff, bl_ptr->max_unmap_blk_cnt);
10342 			if (lun->be_lun->pblockexp != 0) {
10343 				scsi_ulto4b((1 << lun->be_lun->pblockexp),
10344 				    bl_ptr->opt_unmap_grain);
10345 				scsi_ulto4b(0x80000000 | lun->be_lun->pblockoff,
10346 				    bl_ptr->unmap_grain_align);
10347 			}
10348 		}
10349 		scsi_ulto4b(lun->be_lun->atomicblock,
10350 		    bl_ptr->max_atomic_transfer_length);
10351 		scsi_ulto4b(0, bl_ptr->atomic_alignment);
10352 		scsi_ulto4b(0, bl_ptr->atomic_transfer_length_granularity);
10353 	}
10354 	scsi_u64to8b(UINT64_MAX, bl_ptr->max_write_same_length);
10355 
10356 	ctsio->scsi_status = SCSI_STATUS_OK;
10357 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10358 	ctsio->be_move_done = ctl_config_move_done;
10359 	ctl_datamove((union ctl_io *)ctsio);
10360 
10361 	return (CTL_RETVAL_COMPLETE);
10362 }
10363 
10364 static int
10365 ctl_inquiry_evpd_bdc(struct ctl_scsiio *ctsio, int alloc_len)
10366 {
10367 	struct scsi_vpd_block_device_characteristics *bdc_ptr;
10368 	struct ctl_lun *lun;
10369 
10370 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10371 
10372 	ctsio->kern_data_ptr = malloc(sizeof(*bdc_ptr), M_CTL, M_WAITOK | M_ZERO);
10373 	bdc_ptr = (struct scsi_vpd_block_device_characteristics *)ctsio->kern_data_ptr;
10374 	ctsio->kern_sg_entries = 0;
10375 
10376 	if (sizeof(*bdc_ptr) < alloc_len) {
10377 		ctsio->residual = alloc_len - sizeof(*bdc_ptr);
10378 		ctsio->kern_data_len = sizeof(*bdc_ptr);
10379 		ctsio->kern_total_len = sizeof(*bdc_ptr);
10380 	} else {
10381 		ctsio->residual = 0;
10382 		ctsio->kern_data_len = alloc_len;
10383 		ctsio->kern_total_len = alloc_len;
10384 	}
10385 	ctsio->kern_data_resid = 0;
10386 	ctsio->kern_rel_offset = 0;
10387 	ctsio->kern_sg_entries = 0;
10388 
10389 	/*
10390 	 * The control device is always connected.  The disk device, on the
10391 	 * other hand, may not be online all the time.  Need to change this
10392 	 * to figure out whether the disk device is actually online or not.
10393 	 */
10394 	if (lun != NULL)
10395 		bdc_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10396 				  lun->be_lun->lun_type;
10397 	else
10398 		bdc_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10399 	bdc_ptr->page_code = SVPD_BDC;
10400 	scsi_ulto2b(sizeof(*bdc_ptr) - 4, bdc_ptr->page_length);
10401 	scsi_ulto2b(SVPD_NON_ROTATING, bdc_ptr->medium_rotation_rate);
10402 	bdc_ptr->flags = SVPD_FUAB | SVPD_VBULS;
10403 
10404 	ctsio->scsi_status = SCSI_STATUS_OK;
10405 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10406 	ctsio->be_move_done = ctl_config_move_done;
10407 	ctl_datamove((union ctl_io *)ctsio);
10408 
10409 	return (CTL_RETVAL_COMPLETE);
10410 }
10411 
10412 static int
10413 ctl_inquiry_evpd_lbp(struct ctl_scsiio *ctsio, int alloc_len)
10414 {
10415 	struct scsi_vpd_logical_block_prov *lbp_ptr;
10416 	struct ctl_lun *lun;
10417 
10418 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10419 
10420 	ctsio->kern_data_ptr = malloc(sizeof(*lbp_ptr), M_CTL, M_WAITOK | M_ZERO);
10421 	lbp_ptr = (struct scsi_vpd_logical_block_prov *)ctsio->kern_data_ptr;
10422 	ctsio->kern_sg_entries = 0;
10423 
10424 	if (sizeof(*lbp_ptr) < alloc_len) {
10425 		ctsio->residual = alloc_len - sizeof(*lbp_ptr);
10426 		ctsio->kern_data_len = sizeof(*lbp_ptr);
10427 		ctsio->kern_total_len = sizeof(*lbp_ptr);
10428 	} else {
10429 		ctsio->residual = 0;
10430 		ctsio->kern_data_len = alloc_len;
10431 		ctsio->kern_total_len = alloc_len;
10432 	}
10433 	ctsio->kern_data_resid = 0;
10434 	ctsio->kern_rel_offset = 0;
10435 	ctsio->kern_sg_entries = 0;
10436 
10437 	/*
10438 	 * The control device is always connected.  The disk device, on the
10439 	 * other hand, may not be online all the time.  Need to change this
10440 	 * to figure out whether the disk device is actually online or not.
10441 	 */
10442 	if (lun != NULL)
10443 		lbp_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10444 				  lun->be_lun->lun_type;
10445 	else
10446 		lbp_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10447 
10448 	lbp_ptr->page_code = SVPD_LBP;
10449 	scsi_ulto2b(sizeof(*lbp_ptr) - 4, lbp_ptr->page_length);
10450 	if (lun != NULL && lun->be_lun->flags & CTL_LUN_FLAG_UNMAP) {
10451 		lbp_ptr->flags = SVPD_LBP_UNMAP | SVPD_LBP_WS16 |
10452 		    SVPD_LBP_WS10 | SVPD_LBP_RZ | SVPD_LBP_ANC_SUP;
10453 		lbp_ptr->prov_type = SVPD_LBP_RESOURCE;
10454 	}
10455 
10456 	ctsio->scsi_status = SCSI_STATUS_OK;
10457 	ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10458 	ctsio->be_move_done = ctl_config_move_done;
10459 	ctl_datamove((union ctl_io *)ctsio);
10460 
10461 	return (CTL_RETVAL_COMPLETE);
10462 }
10463 
10464 static int
10465 ctl_inquiry_evpd(struct ctl_scsiio *ctsio)
10466 {
10467 	struct scsi_inquiry *cdb;
10468 	struct ctl_lun *lun;
10469 	int alloc_len, retval;
10470 
10471 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10472 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10473 
10474 	retval = CTL_RETVAL_COMPLETE;
10475 
10476 	alloc_len = scsi_2btoul(cdb->length);
10477 
10478 	switch (cdb->page_code) {
10479 	case SVPD_SUPPORTED_PAGES:
10480 		retval = ctl_inquiry_evpd_supported(ctsio, alloc_len);
10481 		break;
10482 	case SVPD_UNIT_SERIAL_NUMBER:
10483 		retval = ctl_inquiry_evpd_serial(ctsio, alloc_len);
10484 		break;
10485 	case SVPD_DEVICE_ID:
10486 		retval = ctl_inquiry_evpd_devid(ctsio, alloc_len);
10487 		break;
10488 	case SVPD_EXTENDED_INQUIRY_DATA:
10489 		retval = ctl_inquiry_evpd_eid(ctsio, alloc_len);
10490 		break;
10491 	case SVPD_MODE_PAGE_POLICY:
10492 		retval = ctl_inquiry_evpd_mpp(ctsio, alloc_len);
10493 		break;
10494 	case SVPD_SCSI_PORTS:
10495 		retval = ctl_inquiry_evpd_scsi_ports(ctsio, alloc_len);
10496 		break;
10497 	case SVPD_SCSI_TPC:
10498 		retval = ctl_inquiry_evpd_tpc(ctsio, alloc_len);
10499 		break;
10500 	case SVPD_BLOCK_LIMITS:
10501 		retval = ctl_inquiry_evpd_block_limits(ctsio, alloc_len);
10502 		break;
10503 	case SVPD_BDC:
10504 		retval = ctl_inquiry_evpd_bdc(ctsio, alloc_len);
10505 		break;
10506 	case SVPD_LBP:
10507 		retval = ctl_inquiry_evpd_lbp(ctsio, alloc_len);
10508 		break;
10509 	default:
10510 		ctl_set_invalid_field(ctsio,
10511 				      /*sks_valid*/ 1,
10512 				      /*command*/ 1,
10513 				      /*field*/ 2,
10514 				      /*bit_valid*/ 0,
10515 				      /*bit*/ 0);
10516 		ctl_done((union ctl_io *)ctsio);
10517 		retval = CTL_RETVAL_COMPLETE;
10518 		break;
10519 	}
10520 
10521 	return (retval);
10522 }
10523 
10524 static int
10525 ctl_inquiry_std(struct ctl_scsiio *ctsio)
10526 {
10527 	struct scsi_inquiry_data *inq_ptr;
10528 	struct scsi_inquiry *cdb;
10529 	struct ctl_softc *ctl_softc;
10530 	struct ctl_lun *lun;
10531 	char *val;
10532 	uint32_t alloc_len, data_len;
10533 	ctl_port_type port_type;
10534 
10535 	ctl_softc = control_softc;
10536 
10537 	/*
10538 	 * Figure out whether we're talking to a Fibre Channel port or not.
10539 	 * We treat the ioctl front end, and any SCSI adapters, as packetized
10540 	 * SCSI front ends.
10541 	 */
10542 	port_type = ctl_softc->ctl_ports[
10543 	    ctl_port_idx(ctsio->io_hdr.nexus.targ_port)]->port_type;
10544 	if (port_type == CTL_PORT_IOCTL || port_type == CTL_PORT_INTERNAL)
10545 		port_type = CTL_PORT_SCSI;
10546 
10547 	lun = ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
10548 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10549 	alloc_len = scsi_2btoul(cdb->length);
10550 
10551 	/*
10552 	 * We malloc the full inquiry data size here and fill it
10553 	 * in.  If the user only asks for less, we'll give him
10554 	 * that much.
10555 	 */
10556 	data_len = offsetof(struct scsi_inquiry_data, vendor_specific1);
10557 	ctsio->kern_data_ptr = malloc(data_len, M_CTL, M_WAITOK | M_ZERO);
10558 	inq_ptr = (struct scsi_inquiry_data *)ctsio->kern_data_ptr;
10559 	ctsio->kern_sg_entries = 0;
10560 	ctsio->kern_data_resid = 0;
10561 	ctsio->kern_rel_offset = 0;
10562 
10563 	if (data_len < alloc_len) {
10564 		ctsio->residual = alloc_len - data_len;
10565 		ctsio->kern_data_len = data_len;
10566 		ctsio->kern_total_len = data_len;
10567 	} else {
10568 		ctsio->residual = 0;
10569 		ctsio->kern_data_len = alloc_len;
10570 		ctsio->kern_total_len = alloc_len;
10571 	}
10572 
10573 	/*
10574 	 * If we have a LUN configured, report it as connected.  Otherwise,
10575 	 * report that it is offline or no device is supported, depending
10576 	 * on the value of inquiry_pq_no_lun.
10577 	 *
10578 	 * According to the spec (SPC-4 r34), the peripheral qualifier
10579 	 * SID_QUAL_LU_OFFLINE (001b) is used in the following scenario:
10580 	 *
10581 	 * "A peripheral device having the specified peripheral device type
10582 	 * is not connected to this logical unit. However, the device
10583 	 * server is capable of supporting the specified peripheral device
10584 	 * type on this logical unit."
10585 	 *
10586 	 * According to the same spec, the peripheral qualifier
10587 	 * SID_QUAL_BAD_LU (011b) is used in this scenario:
10588 	 *
10589 	 * "The device server is not capable of supporting a peripheral
10590 	 * device on this logical unit. For this peripheral qualifier the
10591 	 * peripheral device type shall be set to 1Fh. All other peripheral
10592 	 * device type values are reserved for this peripheral qualifier."
10593 	 *
10594 	 * Given the text, it would seem that we probably want to report that
10595 	 * the LUN is offline here.  There is no LUN connected, but we can
10596 	 * support a LUN at the given LUN number.
10597 	 *
10598 	 * In the real world, though, it sounds like things are a little
10599 	 * different:
10600 	 *
10601 	 * - Linux, when presented with a LUN with the offline peripheral
10602 	 *   qualifier, will create an sg driver instance for it.  So when
10603 	 *   you attach it to CTL, you wind up with a ton of sg driver
10604 	 *   instances.  (One for every LUN that Linux bothered to probe.)
10605 	 *   Linux does this despite the fact that it issues a REPORT LUNs
10606 	 *   to LUN 0 to get the inventory of supported LUNs.
10607 	 *
10608 	 * - There is other anecdotal evidence (from Emulex folks) about
10609 	 *   arrays that use the offline peripheral qualifier for LUNs that
10610 	 *   are on the "passive" path in an active/passive array.
10611 	 *
10612 	 * So the solution is provide a hopefully reasonable default
10613 	 * (return bad/no LUN) and allow the user to change the behavior
10614 	 * with a tunable/sysctl variable.
10615 	 */
10616 	if (lun != NULL)
10617 		inq_ptr->device = (SID_QUAL_LU_CONNECTED << 5) |
10618 				  lun->be_lun->lun_type;
10619 	else if (ctl_softc->inquiry_pq_no_lun == 0)
10620 		inq_ptr->device = (SID_QUAL_LU_OFFLINE << 5) | T_DIRECT;
10621 	else
10622 		inq_ptr->device = (SID_QUAL_BAD_LU << 5) | T_NODEVICE;
10623 
10624 	/* RMB in byte 2 is 0 */
10625 	inq_ptr->version = SCSI_REV_SPC4;
10626 
10627 	/*
10628 	 * According to SAM-3, even if a device only supports a single
10629 	 * level of LUN addressing, it should still set the HISUP bit:
10630 	 *
10631 	 * 4.9.1 Logical unit numbers overview
10632 	 *
10633 	 * All logical unit number formats described in this standard are
10634 	 * hierarchical in structure even when only a single level in that
10635 	 * hierarchy is used. The HISUP bit shall be set to one in the
10636 	 * standard INQUIRY data (see SPC-2) when any logical unit number
10637 	 * format described in this standard is used.  Non-hierarchical
10638 	 * formats are outside the scope of this standard.
10639 	 *
10640 	 * Therefore we set the HiSup bit here.
10641 	 *
10642 	 * The reponse format is 2, per SPC-3.
10643 	 */
10644 	inq_ptr->response_format = SID_HiSup | 2;
10645 
10646 	inq_ptr->additional_length = data_len -
10647 	    (offsetof(struct scsi_inquiry_data, additional_length) + 1);
10648 	CTL_DEBUG_PRINT(("additional_length = %d\n",
10649 			 inq_ptr->additional_length));
10650 
10651 	inq_ptr->spc3_flags = SPC3_SID_3PC | SPC3_SID_TPGS_IMPLICIT;
10652 	/* 16 bit addressing */
10653 	if (port_type == CTL_PORT_SCSI)
10654 		inq_ptr->spc2_flags = SPC2_SID_ADDR16;
10655 	/* XXX set the SID_MultiP bit here if we're actually going to
10656 	   respond on multiple ports */
10657 	inq_ptr->spc2_flags |= SPC2_SID_MultiP;
10658 
10659 	/* 16 bit data bus, synchronous transfers */
10660 	if (port_type == CTL_PORT_SCSI)
10661 		inq_ptr->flags = SID_WBus16 | SID_Sync;
10662 	/*
10663 	 * XXX KDM do we want to support tagged queueing on the control
10664 	 * device at all?
10665 	 */
10666 	if ((lun == NULL)
10667 	 || (lun->be_lun->lun_type != T_PROCESSOR))
10668 		inq_ptr->flags |= SID_CmdQue;
10669 	/*
10670 	 * Per SPC-3, unused bytes in ASCII strings are filled with spaces.
10671 	 * We have 8 bytes for the vendor name, and 16 bytes for the device
10672 	 * name and 4 bytes for the revision.
10673 	 */
10674 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10675 	    "vendor")) == NULL) {
10676 		strncpy(inq_ptr->vendor, CTL_VENDOR, sizeof(inq_ptr->vendor));
10677 	} else {
10678 		memset(inq_ptr->vendor, ' ', sizeof(inq_ptr->vendor));
10679 		strncpy(inq_ptr->vendor, val,
10680 		    min(sizeof(inq_ptr->vendor), strlen(val)));
10681 	}
10682 	if (lun == NULL) {
10683 		strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10684 		    sizeof(inq_ptr->product));
10685 	} else if ((val = ctl_get_opt(&lun->be_lun->options, "product")) == NULL) {
10686 		switch (lun->be_lun->lun_type) {
10687 		case T_DIRECT:
10688 			strncpy(inq_ptr->product, CTL_DIRECT_PRODUCT,
10689 			    sizeof(inq_ptr->product));
10690 			break;
10691 		case T_PROCESSOR:
10692 			strncpy(inq_ptr->product, CTL_PROCESSOR_PRODUCT,
10693 			    sizeof(inq_ptr->product));
10694 			break;
10695 		default:
10696 			strncpy(inq_ptr->product, CTL_UNKNOWN_PRODUCT,
10697 			    sizeof(inq_ptr->product));
10698 			break;
10699 		}
10700 	} else {
10701 		memset(inq_ptr->product, ' ', sizeof(inq_ptr->product));
10702 		strncpy(inq_ptr->product, val,
10703 		    min(sizeof(inq_ptr->product), strlen(val)));
10704 	}
10705 
10706 	/*
10707 	 * XXX make this a macro somewhere so it automatically gets
10708 	 * incremented when we make changes.
10709 	 */
10710 	if (lun == NULL || (val = ctl_get_opt(&lun->be_lun->options,
10711 	    "revision")) == NULL) {
10712 		strncpy(inq_ptr->revision, "0001", sizeof(inq_ptr->revision));
10713 	} else {
10714 		memset(inq_ptr->revision, ' ', sizeof(inq_ptr->revision));
10715 		strncpy(inq_ptr->revision, val,
10716 		    min(sizeof(inq_ptr->revision), strlen(val)));
10717 	}
10718 
10719 	/*
10720 	 * For parallel SCSI, we support double transition and single
10721 	 * transition clocking.  We also support QAS (Quick Arbitration
10722 	 * and Selection) and Information Unit transfers on both the
10723 	 * control and array devices.
10724 	 */
10725 	if (port_type == CTL_PORT_SCSI)
10726 		inq_ptr->spi3data = SID_SPI_CLOCK_DT_ST | SID_SPI_QAS |
10727 				    SID_SPI_IUS;
10728 
10729 	/* SAM-5 (no version claimed) */
10730 	scsi_ulto2b(0x00A0, inq_ptr->version1);
10731 	/* SPC-4 (no version claimed) */
10732 	scsi_ulto2b(0x0460, inq_ptr->version2);
10733 	if (port_type == CTL_PORT_FC) {
10734 		/* FCP-2 ANSI INCITS.350:2003 */
10735 		scsi_ulto2b(0x0917, inq_ptr->version3);
10736 	} else if (port_type == CTL_PORT_SCSI) {
10737 		/* SPI-4 ANSI INCITS.362:200x */
10738 		scsi_ulto2b(0x0B56, inq_ptr->version3);
10739 	} else if (port_type == CTL_PORT_ISCSI) {
10740 		/* iSCSI (no version claimed) */
10741 		scsi_ulto2b(0x0960, inq_ptr->version3);
10742 	} else if (port_type == CTL_PORT_SAS) {
10743 		/* SAS (no version claimed) */
10744 		scsi_ulto2b(0x0BE0, inq_ptr->version3);
10745 	}
10746 
10747 	if (lun == NULL) {
10748 		/* SBC-4 (no version claimed) */
10749 		scsi_ulto2b(0x0600, inq_ptr->version4);
10750 	} else {
10751 		switch (lun->be_lun->lun_type) {
10752 		case T_DIRECT:
10753 			/* SBC-4 (no version claimed) */
10754 			scsi_ulto2b(0x0600, inq_ptr->version4);
10755 			break;
10756 		case T_PROCESSOR:
10757 		default:
10758 			break;
10759 		}
10760 	}
10761 
10762 	ctsio->scsi_status = SCSI_STATUS_OK;
10763 	if (ctsio->kern_data_len > 0) {
10764 		ctsio->io_hdr.flags |= CTL_FLAG_ALLOCATED;
10765 		ctsio->be_move_done = ctl_config_move_done;
10766 		ctl_datamove((union ctl_io *)ctsio);
10767 	} else {
10768 		ctsio->io_hdr.status = CTL_SUCCESS;
10769 		ctl_done((union ctl_io *)ctsio);
10770 	}
10771 
10772 	return (CTL_RETVAL_COMPLETE);
10773 }
10774 
10775 int
10776 ctl_inquiry(struct ctl_scsiio *ctsio)
10777 {
10778 	struct scsi_inquiry *cdb;
10779 	int retval;
10780 
10781 	CTL_DEBUG_PRINT(("ctl_inquiry\n"));
10782 
10783 	cdb = (struct scsi_inquiry *)ctsio->cdb;
10784 	if (cdb->byte2 & SI_EVPD)
10785 		retval = ctl_inquiry_evpd(ctsio);
10786 	else if (cdb->page_code == 0)
10787 		retval = ctl_inquiry_std(ctsio);
10788 	else {
10789 		ctl_set_invalid_field(ctsio,
10790 				      /*sks_valid*/ 1,
10791 				      /*command*/ 1,
10792 				      /*field*/ 2,
10793 				      /*bit_valid*/ 0,
10794 				      /*bit*/ 0);
10795 		ctl_done((union ctl_io *)ctsio);
10796 		return (CTL_RETVAL_COMPLETE);
10797 	}
10798 
10799 	return (retval);
10800 }
10801 
10802 /*
10803  * For known CDB types, parse the LBA and length.
10804  */
10805 static int
10806 ctl_get_lba_len(union ctl_io *io, uint64_t *lba, uint64_t *len)
10807 {
10808 	if (io->io_hdr.io_type != CTL_IO_SCSI)
10809 		return (1);
10810 
10811 	switch (io->scsiio.cdb[0]) {
10812 	case COMPARE_AND_WRITE: {
10813 		struct scsi_compare_and_write *cdb;
10814 
10815 		cdb = (struct scsi_compare_and_write *)io->scsiio.cdb;
10816 
10817 		*lba = scsi_8btou64(cdb->addr);
10818 		*len = cdb->length;
10819 		break;
10820 	}
10821 	case READ_6:
10822 	case WRITE_6: {
10823 		struct scsi_rw_6 *cdb;
10824 
10825 		cdb = (struct scsi_rw_6 *)io->scsiio.cdb;
10826 
10827 		*lba = scsi_3btoul(cdb->addr);
10828 		/* only 5 bits are valid in the most significant address byte */
10829 		*lba &= 0x1fffff;
10830 		*len = cdb->length;
10831 		break;
10832 	}
10833 	case READ_10:
10834 	case WRITE_10: {
10835 		struct scsi_rw_10 *cdb;
10836 
10837 		cdb = (struct scsi_rw_10 *)io->scsiio.cdb;
10838 
10839 		*lba = scsi_4btoul(cdb->addr);
10840 		*len = scsi_2btoul(cdb->length);
10841 		break;
10842 	}
10843 	case WRITE_VERIFY_10: {
10844 		struct scsi_write_verify_10 *cdb;
10845 
10846 		cdb = (struct scsi_write_verify_10 *)io->scsiio.cdb;
10847 
10848 		*lba = scsi_4btoul(cdb->addr);
10849 		*len = scsi_2btoul(cdb->length);
10850 		break;
10851 	}
10852 	case READ_12:
10853 	case WRITE_12: {
10854 		struct scsi_rw_12 *cdb;
10855 
10856 		cdb = (struct scsi_rw_12 *)io->scsiio.cdb;
10857 
10858 		*lba = scsi_4btoul(cdb->addr);
10859 		*len = scsi_4btoul(cdb->length);
10860 		break;
10861 	}
10862 	case WRITE_VERIFY_12: {
10863 		struct scsi_write_verify_12 *cdb;
10864 
10865 		cdb = (struct scsi_write_verify_12 *)io->scsiio.cdb;
10866 
10867 		*lba = scsi_4btoul(cdb->addr);
10868 		*len = scsi_4btoul(cdb->length);
10869 		break;
10870 	}
10871 	case READ_16:
10872 	case WRITE_16:
10873 	case WRITE_ATOMIC_16: {
10874 		struct scsi_rw_16 *cdb;
10875 
10876 		cdb = (struct scsi_rw_16 *)io->scsiio.cdb;
10877 
10878 		*lba = scsi_8btou64(cdb->addr);
10879 		*len = scsi_4btoul(cdb->length);
10880 		break;
10881 	}
10882 	case WRITE_VERIFY_16: {
10883 		struct scsi_write_verify_16 *cdb;
10884 
10885 		cdb = (struct scsi_write_verify_16 *)io->scsiio.cdb;
10886 
10887 		*lba = scsi_8btou64(cdb->addr);
10888 		*len = scsi_4btoul(cdb->length);
10889 		break;
10890 	}
10891 	case WRITE_SAME_10: {
10892 		struct scsi_write_same_10 *cdb;
10893 
10894 		cdb = (struct scsi_write_same_10 *)io->scsiio.cdb;
10895 
10896 		*lba = scsi_4btoul(cdb->addr);
10897 		*len = scsi_2btoul(cdb->length);
10898 		break;
10899 	}
10900 	case WRITE_SAME_16: {
10901 		struct scsi_write_same_16 *cdb;
10902 
10903 		cdb = (struct scsi_write_same_16 *)io->scsiio.cdb;
10904 
10905 		*lba = scsi_8btou64(cdb->addr);
10906 		*len = scsi_4btoul(cdb->length);
10907 		break;
10908 	}
10909 	case VERIFY_10: {
10910 		struct scsi_verify_10 *cdb;
10911 
10912 		cdb = (struct scsi_verify_10 *)io->scsiio.cdb;
10913 
10914 		*lba = scsi_4btoul(cdb->addr);
10915 		*len = scsi_2btoul(cdb->length);
10916 		break;
10917 	}
10918 	case VERIFY_12: {
10919 		struct scsi_verify_12 *cdb;
10920 
10921 		cdb = (struct scsi_verify_12 *)io->scsiio.cdb;
10922 
10923 		*lba = scsi_4btoul(cdb->addr);
10924 		*len = scsi_4btoul(cdb->length);
10925 		break;
10926 	}
10927 	case VERIFY_16: {
10928 		struct scsi_verify_16 *cdb;
10929 
10930 		cdb = (struct scsi_verify_16 *)io->scsiio.cdb;
10931 
10932 		*lba = scsi_8btou64(cdb->addr);
10933 		*len = scsi_4btoul(cdb->length);
10934 		break;
10935 	}
10936 	case UNMAP: {
10937 		*lba = 0;
10938 		*len = UINT64_MAX;
10939 		break;
10940 	}
10941 	default:
10942 		return (1);
10943 		break; /* NOTREACHED */
10944 	}
10945 
10946 	return (0);
10947 }
10948 
10949 static ctl_action
10950 ctl_extent_check_lba(uint64_t lba1, uint64_t len1, uint64_t lba2, uint64_t len2)
10951 {
10952 	uint64_t endlba1, endlba2;
10953 
10954 	endlba1 = lba1 + len1 - 1;
10955 	endlba2 = lba2 + len2 - 1;
10956 
10957 	if ((endlba1 < lba2)
10958 	 || (endlba2 < lba1))
10959 		return (CTL_ACTION_PASS);
10960 	else
10961 		return (CTL_ACTION_BLOCK);
10962 }
10963 
10964 static int
10965 ctl_extent_check_unmap(union ctl_io *io, uint64_t lba2, uint64_t len2)
10966 {
10967 	struct ctl_ptr_len_flags *ptrlen;
10968 	struct scsi_unmap_desc *buf, *end, *range;
10969 	uint64_t lba;
10970 	uint32_t len;
10971 
10972 	/* If not UNMAP -- go other way. */
10973 	if (io->io_hdr.io_type != CTL_IO_SCSI ||
10974 	    io->scsiio.cdb[0] != UNMAP)
10975 		return (CTL_ACTION_ERROR);
10976 
10977 	/* If UNMAP without data -- block and wait for data. */
10978 	ptrlen = (struct ctl_ptr_len_flags *)
10979 	    &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN];
10980 	if ((io->io_hdr.flags & CTL_FLAG_ALLOCATED) == 0 ||
10981 	    ptrlen->ptr == NULL)
10982 		return (CTL_ACTION_BLOCK);
10983 
10984 	/* UNMAP with data -- check for collision. */
10985 	buf = (struct scsi_unmap_desc *)ptrlen->ptr;
10986 	end = buf + ptrlen->len / sizeof(*buf);
10987 	for (range = buf; range < end; range++) {
10988 		lba = scsi_8btou64(range->lba);
10989 		len = scsi_4btoul(range->length);
10990 		if ((lba < lba2 + len2) && (lba + len > lba2))
10991 			return (CTL_ACTION_BLOCK);
10992 	}
10993 	return (CTL_ACTION_PASS);
10994 }
10995 
10996 static ctl_action
10997 ctl_extent_check(union ctl_io *io1, union ctl_io *io2)
10998 {
10999 	uint64_t lba1, lba2;
11000 	uint64_t len1, len2;
11001 	int retval;
11002 
11003 	if (ctl_get_lba_len(io1, &lba1, &len1) != 0)
11004 		return (CTL_ACTION_ERROR);
11005 
11006 	retval = ctl_extent_check_unmap(io2, lba1, len1);
11007 	if (retval != CTL_ACTION_ERROR)
11008 		return (retval);
11009 
11010 	if (ctl_get_lba_len(io2, &lba2, &len2) != 0)
11011 		return (CTL_ACTION_ERROR);
11012 
11013 	return (ctl_extent_check_lba(lba1, len1, lba2, len2));
11014 }
11015 
11016 static ctl_action
11017 ctl_check_for_blockage(struct ctl_lun *lun, union ctl_io *pending_io,
11018     union ctl_io *ooa_io)
11019 {
11020 	const struct ctl_cmd_entry *pending_entry, *ooa_entry;
11021 	ctl_serialize_action *serialize_row;
11022 
11023 	/*
11024 	 * The initiator attempted multiple untagged commands at the same
11025 	 * time.  Can't do that.
11026 	 */
11027 	if ((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11028 	 && (ooa_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11029 	 && ((pending_io->io_hdr.nexus.targ_port ==
11030 	      ooa_io->io_hdr.nexus.targ_port)
11031 	  && (pending_io->io_hdr.nexus.initid.id ==
11032 	      ooa_io->io_hdr.nexus.initid.id))
11033 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11034 		return (CTL_ACTION_OVERLAP);
11035 
11036 	/*
11037 	 * The initiator attempted to send multiple tagged commands with
11038 	 * the same ID.  (It's fine if different initiators have the same
11039 	 * tag ID.)
11040 	 *
11041 	 * Even if all of those conditions are true, we don't kill the I/O
11042 	 * if the command ahead of us has been aborted.  We won't end up
11043 	 * sending it to the FETD, and it's perfectly legal to resend a
11044 	 * command with the same tag number as long as the previous
11045 	 * instance of this tag number has been aborted somehow.
11046 	 */
11047 	if ((pending_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11048 	 && (ooa_io->scsiio.tag_type != CTL_TAG_UNTAGGED)
11049 	 && (pending_io->scsiio.tag_num == ooa_io->scsiio.tag_num)
11050 	 && ((pending_io->io_hdr.nexus.targ_port ==
11051 	      ooa_io->io_hdr.nexus.targ_port)
11052 	  && (pending_io->io_hdr.nexus.initid.id ==
11053 	      ooa_io->io_hdr.nexus.initid.id))
11054 	 && ((ooa_io->io_hdr.flags & CTL_FLAG_ABORT) == 0))
11055 		return (CTL_ACTION_OVERLAP_TAG);
11056 
11057 	/*
11058 	 * If we get a head of queue tag, SAM-3 says that we should
11059 	 * immediately execute it.
11060 	 *
11061 	 * What happens if this command would normally block for some other
11062 	 * reason?  e.g. a request sense with a head of queue tag
11063 	 * immediately after a write.  Normally that would block, but this
11064 	 * will result in its getting executed immediately...
11065 	 *
11066 	 * We currently return "pass" instead of "skip", so we'll end up
11067 	 * going through the rest of the queue to check for overlapped tags.
11068 	 *
11069 	 * XXX KDM check for other types of blockage first??
11070 	 */
11071 	if (pending_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11072 		return (CTL_ACTION_PASS);
11073 
11074 	/*
11075 	 * Ordered tags have to block until all items ahead of them
11076 	 * have completed.  If we get called with an ordered tag, we always
11077 	 * block, if something else is ahead of us in the queue.
11078 	 */
11079 	if (pending_io->scsiio.tag_type == CTL_TAG_ORDERED)
11080 		return (CTL_ACTION_BLOCK);
11081 
11082 	/*
11083 	 * Simple tags get blocked until all head of queue and ordered tags
11084 	 * ahead of them have completed.  I'm lumping untagged commands in
11085 	 * with simple tags here.  XXX KDM is that the right thing to do?
11086 	 */
11087 	if (((pending_io->scsiio.tag_type == CTL_TAG_UNTAGGED)
11088 	  || (pending_io->scsiio.tag_type == CTL_TAG_SIMPLE))
11089 	 && ((ooa_io->scsiio.tag_type == CTL_TAG_HEAD_OF_QUEUE)
11090 	  || (ooa_io->scsiio.tag_type == CTL_TAG_ORDERED)))
11091 		return (CTL_ACTION_BLOCK);
11092 
11093 	pending_entry = ctl_get_cmd_entry(&pending_io->scsiio, NULL);
11094 	ooa_entry = ctl_get_cmd_entry(&ooa_io->scsiio, NULL);
11095 
11096 	serialize_row = ctl_serialize_table[ooa_entry->seridx];
11097 
11098 	switch (serialize_row[pending_entry->seridx]) {
11099 	case CTL_SER_BLOCK:
11100 		return (CTL_ACTION_BLOCK);
11101 	case CTL_SER_EXTENT:
11102 		return (ctl_extent_check(pending_io, ooa_io));
11103 	case CTL_SER_EXTENTOPT:
11104 		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11105 		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11106 			return (ctl_extent_check(pending_io, ooa_io));
11107 		/* FALLTHROUGH */
11108 	case CTL_SER_PASS:
11109 		return (CTL_ACTION_PASS);
11110 	case CTL_SER_BLOCKOPT:
11111 		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT].queue_flags
11112 		    & SCP_QUEUE_ALG_MASK) != SCP_QUEUE_ALG_UNRESTRICTED)
11113 			return (CTL_ACTION_BLOCK);
11114 		return (CTL_ACTION_PASS);
11115 	case CTL_SER_SKIP:
11116 		return (CTL_ACTION_SKIP);
11117 	default:
11118 		panic("invalid serialization value %d",
11119 		      serialize_row[pending_entry->seridx]);
11120 	}
11121 
11122 	return (CTL_ACTION_ERROR);
11123 }
11124 
11125 /*
11126  * Check for blockage or overlaps against the OOA (Order Of Arrival) queue.
11127  * Assumptions:
11128  * - pending_io is generally either incoming, or on the blocked queue
11129  * - starting I/O is the I/O we want to start the check with.
11130  */
11131 static ctl_action
11132 ctl_check_ooa(struct ctl_lun *lun, union ctl_io *pending_io,
11133 	      union ctl_io *starting_io)
11134 {
11135 	union ctl_io *ooa_io;
11136 	ctl_action action;
11137 
11138 	mtx_assert(&lun->lun_lock, MA_OWNED);
11139 
11140 	/*
11141 	 * Run back along the OOA queue, starting with the current
11142 	 * blocked I/O and going through every I/O before it on the
11143 	 * queue.  If starting_io is NULL, we'll just end up returning
11144 	 * CTL_ACTION_PASS.
11145 	 */
11146 	for (ooa_io = starting_io; ooa_io != NULL;
11147 	     ooa_io = (union ctl_io *)TAILQ_PREV(&ooa_io->io_hdr, ctl_ooaq,
11148 	     ooa_links)){
11149 
11150 		/*
11151 		 * This routine just checks to see whether
11152 		 * cur_blocked is blocked by ooa_io, which is ahead
11153 		 * of it in the queue.  It doesn't queue/dequeue
11154 		 * cur_blocked.
11155 		 */
11156 		action = ctl_check_for_blockage(lun, pending_io, ooa_io);
11157 		switch (action) {
11158 		case CTL_ACTION_BLOCK:
11159 		case CTL_ACTION_OVERLAP:
11160 		case CTL_ACTION_OVERLAP_TAG:
11161 		case CTL_ACTION_SKIP:
11162 		case CTL_ACTION_ERROR:
11163 			return (action);
11164 			break; /* NOTREACHED */
11165 		case CTL_ACTION_PASS:
11166 			break;
11167 		default:
11168 			panic("invalid action %d", action);
11169 			break;  /* NOTREACHED */
11170 		}
11171 	}
11172 
11173 	return (CTL_ACTION_PASS);
11174 }
11175 
11176 /*
11177  * Assumptions:
11178  * - An I/O has just completed, and has been removed from the per-LUN OOA
11179  *   queue, so some items on the blocked queue may now be unblocked.
11180  */
11181 static int
11182 ctl_check_blocked(struct ctl_lun *lun)
11183 {
11184 	union ctl_io *cur_blocked, *next_blocked;
11185 
11186 	mtx_assert(&lun->lun_lock, MA_OWNED);
11187 
11188 	/*
11189 	 * Run forward from the head of the blocked queue, checking each
11190 	 * entry against the I/Os prior to it on the OOA queue to see if
11191 	 * there is still any blockage.
11192 	 *
11193 	 * We cannot use the TAILQ_FOREACH() macro, because it can't deal
11194 	 * with our removing a variable on it while it is traversing the
11195 	 * list.
11196 	 */
11197 	for (cur_blocked = (union ctl_io *)TAILQ_FIRST(&lun->blocked_queue);
11198 	     cur_blocked != NULL; cur_blocked = next_blocked) {
11199 		union ctl_io *prev_ooa;
11200 		ctl_action action;
11201 
11202 		next_blocked = (union ctl_io *)TAILQ_NEXT(&cur_blocked->io_hdr,
11203 							  blocked_links);
11204 
11205 		prev_ooa = (union ctl_io *)TAILQ_PREV(&cur_blocked->io_hdr,
11206 						      ctl_ooaq, ooa_links);
11207 
11208 		/*
11209 		 * If cur_blocked happens to be the first item in the OOA
11210 		 * queue now, prev_ooa will be NULL, and the action
11211 		 * returned will just be CTL_ACTION_PASS.
11212 		 */
11213 		action = ctl_check_ooa(lun, cur_blocked, prev_ooa);
11214 
11215 		switch (action) {
11216 		case CTL_ACTION_BLOCK:
11217 			/* Nothing to do here, still blocked */
11218 			break;
11219 		case CTL_ACTION_OVERLAP:
11220 		case CTL_ACTION_OVERLAP_TAG:
11221 			/*
11222 			 * This shouldn't happen!  In theory we've already
11223 			 * checked this command for overlap...
11224 			 */
11225 			break;
11226 		case CTL_ACTION_PASS:
11227 		case CTL_ACTION_SKIP: {
11228 			struct ctl_softc *softc;
11229 			const struct ctl_cmd_entry *entry;
11230 			uint32_t initidx;
11231 			int isc_retval;
11232 
11233 			/*
11234 			 * The skip case shouldn't happen, this transaction
11235 			 * should have never made it onto the blocked queue.
11236 			 */
11237 			/*
11238 			 * This I/O is no longer blocked, we can remove it
11239 			 * from the blocked queue.  Since this is a TAILQ
11240 			 * (doubly linked list), we can do O(1) removals
11241 			 * from any place on the list.
11242 			 */
11243 			TAILQ_REMOVE(&lun->blocked_queue, &cur_blocked->io_hdr,
11244 				     blocked_links);
11245 			cur_blocked->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11246 
11247 			if (cur_blocked->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC){
11248 				/*
11249 				 * Need to send IO back to original side to
11250 				 * run
11251 				 */
11252 				union ctl_ha_msg msg_info;
11253 
11254 				msg_info.hdr.original_sc =
11255 					cur_blocked->io_hdr.original_sc;
11256 				msg_info.hdr.serializing_sc = cur_blocked;
11257 				msg_info.hdr.msg_type = CTL_MSG_R2R;
11258 				if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11259 				     &msg_info, sizeof(msg_info), 0)) >
11260 				     CTL_HA_STATUS_SUCCESS) {
11261 					printf("CTL:Check Blocked error from "
11262 					       "ctl_ha_msg_send %d\n",
11263 					       isc_retval);
11264 				}
11265 				break;
11266 			}
11267 			entry = ctl_get_cmd_entry(&cur_blocked->scsiio, NULL);
11268 			softc = control_softc;
11269 
11270 			initidx = ctl_get_initindex(&cur_blocked->io_hdr.nexus);
11271 
11272 			/*
11273 			 * Check this I/O for LUN state changes that may
11274 			 * have happened while this command was blocked.
11275 			 * The LUN state may have been changed by a command
11276 			 * ahead of us in the queue, so we need to re-check
11277 			 * for any states that can be caused by SCSI
11278 			 * commands.
11279 			 */
11280 			if (ctl_scsiio_lun_check(softc, lun, entry,
11281 						 &cur_blocked->scsiio) == 0) {
11282 				cur_blocked->io_hdr.flags |=
11283 				                      CTL_FLAG_IS_WAS_ON_RTR;
11284 				ctl_enqueue_rtr(cur_blocked);
11285 			} else
11286 				ctl_done(cur_blocked);
11287 			break;
11288 		}
11289 		default:
11290 			/*
11291 			 * This probably shouldn't happen -- we shouldn't
11292 			 * get CTL_ACTION_ERROR, or anything else.
11293 			 */
11294 			break;
11295 		}
11296 	}
11297 
11298 	return (CTL_RETVAL_COMPLETE);
11299 }
11300 
11301 /*
11302  * This routine (with one exception) checks LUN flags that can be set by
11303  * commands ahead of us in the OOA queue.  These flags have to be checked
11304  * when a command initially comes in, and when we pull a command off the
11305  * blocked queue and are preparing to execute it.  The reason we have to
11306  * check these flags for commands on the blocked queue is that the LUN
11307  * state may have been changed by a command ahead of us while we're on the
11308  * blocked queue.
11309  *
11310  * Ordering is somewhat important with these checks, so please pay
11311  * careful attention to the placement of any new checks.
11312  */
11313 static int
11314 ctl_scsiio_lun_check(struct ctl_softc *ctl_softc, struct ctl_lun *lun,
11315     const struct ctl_cmd_entry *entry, struct ctl_scsiio *ctsio)
11316 {
11317 	int retval;
11318 	uint32_t residx;
11319 
11320 	retval = 0;
11321 
11322 	mtx_assert(&lun->lun_lock, MA_OWNED);
11323 
11324 	/*
11325 	 * If this shelf is a secondary shelf controller, we have to reject
11326 	 * any media access commands.
11327 	 */
11328 #if 0
11329 	/* No longer needed for HA */
11330 	if (((ctl_softc->flags & CTL_FLAG_MASTER_SHELF) == 0)
11331 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_SECONDARY) == 0)) {
11332 		ctl_set_lun_standby(ctsio);
11333 		retval = 1;
11334 		goto bailout;
11335 	}
11336 #endif
11337 
11338 	if (entry->pattern & CTL_LUN_PAT_WRITE) {
11339 		if (lun->flags & CTL_LUN_READONLY) {
11340 			ctl_set_sense(ctsio, /*current_error*/ 1,
11341 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11342 			    /*asc*/ 0x27, /*ascq*/ 0x01, SSD_ELEM_NONE);
11343 			retval = 1;
11344 			goto bailout;
11345 		}
11346 		if ((lun->mode_pages.control_page[CTL_PAGE_CURRENT]
11347 		    .eca_and_aen & SCP_SWP) != 0) {
11348 			ctl_set_sense(ctsio, /*current_error*/ 1,
11349 			    /*sense_key*/ SSD_KEY_DATA_PROTECT,
11350 			    /*asc*/ 0x27, /*ascq*/ 0x02, SSD_ELEM_NONE);
11351 			retval = 1;
11352 			goto bailout;
11353 		}
11354 	}
11355 
11356 	/*
11357 	 * Check for a reservation conflict.  If this command isn't allowed
11358 	 * even on reserved LUNs, and if this initiator isn't the one who
11359 	 * reserved us, reject the command with a reservation conflict.
11360 	 */
11361 	residx = ctl_get_resindex(&ctsio->io_hdr.nexus);
11362 	if ((lun->flags & CTL_LUN_RESERVED)
11363 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_RESV) == 0)) {
11364 		if (lun->res_idx != residx) {
11365 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11366 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11367 			retval = 1;
11368 			goto bailout;
11369 		}
11370 	}
11371 
11372 	if ((lun->flags & CTL_LUN_PR_RESERVED)
11373 	 && ((entry->flags & CTL_CMD_FLAG_ALLOW_ON_PR_RESV) == 0)) {
11374 		/*
11375 		 * if we aren't registered or it's a res holder type
11376 		 * reservation and this isn't the res holder then set a
11377 		 * conflict.
11378 		 * NOTE: Commands which might be allowed on write exclusive
11379 		 * type reservations are checked in the particular command
11380 		 * for a conflict. Read and SSU are the only ones.
11381 		 */
11382 		if (!lun->per_res[residx].registered
11383 		 || (residx != lun->pr_res_idx && lun->res_type < 4)) {
11384 			ctsio->scsi_status = SCSI_STATUS_RESERV_CONFLICT;
11385 			ctsio->io_hdr.status = CTL_SCSI_ERROR;
11386 			retval = 1;
11387 			goto bailout;
11388 		}
11389 
11390 	}
11391 
11392 	if ((lun->flags & CTL_LUN_OFFLINE)
11393 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_OFFLINE) == 0)) {
11394 		ctl_set_lun_not_ready(ctsio);
11395 		retval = 1;
11396 		goto bailout;
11397 	}
11398 
11399 	/*
11400 	 * If the LUN is stopped, see if this particular command is allowed
11401 	 * for a stopped lun.  Otherwise, reject it with 0x04,0x02.
11402 	 */
11403 	if ((lun->flags & CTL_LUN_STOPPED)
11404 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_STOPPED) == 0)) {
11405 		/* "Logical unit not ready, initializing cmd. required" */
11406 		ctl_set_lun_stopped(ctsio);
11407 		retval = 1;
11408 		goto bailout;
11409 	}
11410 
11411 	if ((lun->flags & CTL_LUN_INOPERABLE)
11412 	 && ((entry->flags & CTL_CMD_FLAG_OK_ON_INOPERABLE) == 0)) {
11413 		/* "Medium format corrupted" */
11414 		ctl_set_medium_format_corrupted(ctsio);
11415 		retval = 1;
11416 		goto bailout;
11417 	}
11418 
11419 bailout:
11420 	return (retval);
11421 
11422 }
11423 
11424 static void
11425 ctl_failover_io(union ctl_io *io, int have_lock)
11426 {
11427 	ctl_set_busy(&io->scsiio);
11428 	ctl_done(io);
11429 }
11430 
11431 static void
11432 ctl_failover(void)
11433 {
11434 	struct ctl_lun *lun;
11435 	struct ctl_softc *ctl_softc;
11436 	union ctl_io *next_io, *pending_io;
11437 	union ctl_io *io;
11438 	int lun_idx;
11439 	int i;
11440 
11441 	ctl_softc = control_softc;
11442 
11443 	mtx_lock(&ctl_softc->ctl_lock);
11444 	/*
11445 	 * Remove any cmds from the other SC from the rtr queue.  These
11446 	 * will obviously only be for LUNs for which we're the primary.
11447 	 * We can't send status or get/send data for these commands.
11448 	 * Since they haven't been executed yet, we can just remove them.
11449 	 * We'll either abort them or delete them below, depending on
11450 	 * which HA mode we're in.
11451 	 */
11452 #ifdef notyet
11453 	mtx_lock(&ctl_softc->queue_lock);
11454 	for (io = (union ctl_io *)STAILQ_FIRST(&ctl_softc->rtr_queue);
11455 	     io != NULL; io = next_io) {
11456 		next_io = (union ctl_io *)STAILQ_NEXT(&io->io_hdr, links);
11457 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11458 			STAILQ_REMOVE(&ctl_softc->rtr_queue, &io->io_hdr,
11459 				      ctl_io_hdr, links);
11460 	}
11461 	mtx_unlock(&ctl_softc->queue_lock);
11462 #endif
11463 
11464 	for (lun_idx=0; lun_idx < ctl_softc->num_luns; lun_idx++) {
11465 		lun = ctl_softc->ctl_luns[lun_idx];
11466 		if (lun==NULL)
11467 			continue;
11468 
11469 		/*
11470 		 * Processor LUNs are primary on both sides.
11471 		 * XXX will this always be true?
11472 		 */
11473 		if (lun->be_lun->lun_type == T_PROCESSOR)
11474 			continue;
11475 
11476 		if ((lun->flags & CTL_LUN_PRIMARY_SC)
11477 		 && (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11478 			printf("FAILOVER: primary lun %d\n", lun_idx);
11479 		        /*
11480 			 * Remove all commands from the other SC. First from the
11481 			 * blocked queue then from the ooa queue. Once we have
11482 			 * removed them. Call ctl_check_blocked to see if there
11483 			 * is anything that can run.
11484 			 */
11485 			for (io = (union ctl_io *)TAILQ_FIRST(
11486 			     &lun->blocked_queue); io != NULL; io = next_io) {
11487 
11488 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11489 				    &io->io_hdr, blocked_links);
11490 
11491 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11492 					TAILQ_REMOVE(&lun->blocked_queue,
11493 						     &io->io_hdr,blocked_links);
11494 					io->io_hdr.flags &= ~CTL_FLAG_BLOCKED;
11495 					TAILQ_REMOVE(&lun->ooa_queue,
11496 						     &io->io_hdr, ooa_links);
11497 
11498 					ctl_free_io(io);
11499 				}
11500 			}
11501 
11502 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11503 	     		     io != NULL; io = next_io) {
11504 
11505 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11506 				    &io->io_hdr, ooa_links);
11507 
11508 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) {
11509 
11510 					TAILQ_REMOVE(&lun->ooa_queue,
11511 						&io->io_hdr,
11512 					     	ooa_links);
11513 
11514 					ctl_free_io(io);
11515 				}
11516 			}
11517 			ctl_check_blocked(lun);
11518 		} else if ((lun->flags & CTL_LUN_PRIMARY_SC)
11519 			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11520 
11521 			printf("FAILOVER: primary lun %d\n", lun_idx);
11522 			/*
11523 			 * Abort all commands from the other SC.  We can't
11524 			 * send status back for them now.  These should get
11525 			 * cleaned up when they are completed or come out
11526 			 * for a datamove operation.
11527 			 */
11528 			for (io = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue);
11529 	     		     io != NULL; io = next_io) {
11530 		        	next_io = (union ctl_io *)TAILQ_NEXT(
11531 					&io->io_hdr, ooa_links);
11532 
11533 				if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
11534 					io->io_hdr.flags |= CTL_FLAG_ABORT;
11535 			}
11536 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11537 			&& (ctl_softc->ha_mode == CTL_HA_MODE_XFER)) {
11538 
11539 			printf("FAILOVER: secondary lun %d\n", lun_idx);
11540 
11541 			lun->flags |= CTL_LUN_PRIMARY_SC;
11542 
11543 			/*
11544 			 * We send all I/O that was sent to this controller
11545 			 * and redirected to the other side back with
11546 			 * busy status, and have the initiator retry it.
11547 			 * Figuring out how much data has been transferred,
11548 			 * etc. and picking up where we left off would be
11549 			 * very tricky.
11550 			 *
11551 			 * XXX KDM need to remove I/O from the blocked
11552 			 * queue as well!
11553 			 */
11554 			for (pending_io = (union ctl_io *)TAILQ_FIRST(
11555 			     &lun->ooa_queue); pending_io != NULL;
11556 			     pending_io = next_io) {
11557 
11558 				next_io =  (union ctl_io *)TAILQ_NEXT(
11559 					&pending_io->io_hdr, ooa_links);
11560 
11561 				pending_io->io_hdr.flags &=
11562 					~CTL_FLAG_SENT_2OTHER_SC;
11563 
11564 				if (pending_io->io_hdr.flags &
11565 				    CTL_FLAG_IO_ACTIVE) {
11566 					pending_io->io_hdr.flags |=
11567 						CTL_FLAG_FAILOVER;
11568 				} else {
11569 					ctl_set_busy(&pending_io->scsiio);
11570 					ctl_done(pending_io);
11571 				}
11572 			}
11573 
11574 			/*
11575 			 * Build Unit Attention
11576 			 */
11577 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11578 				lun->pending_ua[i] |=
11579 				                     CTL_UA_ASYM_ACC_CHANGE;
11580 			}
11581 		} else if (((lun->flags & CTL_LUN_PRIMARY_SC) == 0)
11582 			&& (ctl_softc->ha_mode == CTL_HA_MODE_SER_ONLY)) {
11583 			printf("FAILOVER: secondary lun %d\n", lun_idx);
11584 			/*
11585 			 * if the first io on the OOA is not on the RtR queue
11586 			 * add it.
11587 			 */
11588 			lun->flags |= CTL_LUN_PRIMARY_SC;
11589 
11590 			pending_io = (union ctl_io *)TAILQ_FIRST(
11591 			    &lun->ooa_queue);
11592 			if (pending_io==NULL) {
11593 				printf("Nothing on OOA queue\n");
11594 				continue;
11595 			}
11596 
11597 			pending_io->io_hdr.flags &= ~CTL_FLAG_SENT_2OTHER_SC;
11598 			if ((pending_io->io_hdr.flags &
11599 			     CTL_FLAG_IS_WAS_ON_RTR) == 0) {
11600 				pending_io->io_hdr.flags |=
11601 				    CTL_FLAG_IS_WAS_ON_RTR;
11602 				ctl_enqueue_rtr(pending_io);
11603 			}
11604 #if 0
11605 			else
11606 			{
11607 				printf("Tag 0x%04x is running\n",
11608 				      pending_io->scsiio.tag_num);
11609 			}
11610 #endif
11611 
11612 			next_io = (union ctl_io *)TAILQ_NEXT(
11613 			    &pending_io->io_hdr, ooa_links);
11614 			for (pending_io=next_io; pending_io != NULL;
11615 			     pending_io = next_io) {
11616 				pending_io->io_hdr.flags &=
11617 				    ~CTL_FLAG_SENT_2OTHER_SC;
11618 				next_io = (union ctl_io *)TAILQ_NEXT(
11619 					&pending_io->io_hdr, ooa_links);
11620 				if (pending_io->io_hdr.flags &
11621 				    CTL_FLAG_IS_WAS_ON_RTR) {
11622 #if 0
11623 				        printf("Tag 0x%04x is running\n",
11624 				      		pending_io->scsiio.tag_num);
11625 #endif
11626 					continue;
11627 				}
11628 
11629 				switch (ctl_check_ooa(lun, pending_io,
11630 			            (union ctl_io *)TAILQ_PREV(
11631 				    &pending_io->io_hdr, ctl_ooaq,
11632 				    ooa_links))) {
11633 
11634 				case CTL_ACTION_BLOCK:
11635 					TAILQ_INSERT_TAIL(&lun->blocked_queue,
11636 							  &pending_io->io_hdr,
11637 							  blocked_links);
11638 					pending_io->io_hdr.flags |=
11639 					    CTL_FLAG_BLOCKED;
11640 					break;
11641 				case CTL_ACTION_PASS:
11642 				case CTL_ACTION_SKIP:
11643 					pending_io->io_hdr.flags |=
11644 					    CTL_FLAG_IS_WAS_ON_RTR;
11645 					ctl_enqueue_rtr(pending_io);
11646 					break;
11647 				case CTL_ACTION_OVERLAP:
11648 					ctl_set_overlapped_cmd(
11649 					    (struct ctl_scsiio *)pending_io);
11650 					ctl_done(pending_io);
11651 					break;
11652 				case CTL_ACTION_OVERLAP_TAG:
11653 					ctl_set_overlapped_tag(
11654 					    (struct ctl_scsiio *)pending_io,
11655 					    pending_io->scsiio.tag_num & 0xff);
11656 					ctl_done(pending_io);
11657 					break;
11658 				case CTL_ACTION_ERROR:
11659 				default:
11660 					ctl_set_internal_failure(
11661 						(struct ctl_scsiio *)pending_io,
11662 						0,  // sks_valid
11663 						0); //retry count
11664 					ctl_done(pending_io);
11665 					break;
11666 				}
11667 			}
11668 
11669 			/*
11670 			 * Build Unit Attention
11671 			 */
11672 			for (i = 0; i < CTL_MAX_INITIATORS; i++) {
11673 				lun->pending_ua[i] |=
11674 				                     CTL_UA_ASYM_ACC_CHANGE;
11675 			}
11676 		} else {
11677 			panic("Unhandled HA mode failover, LUN flags = %#x, "
11678 			      "ha_mode = #%x", lun->flags, ctl_softc->ha_mode);
11679 		}
11680 	}
11681 	ctl_pause_rtr = 0;
11682 	mtx_unlock(&ctl_softc->ctl_lock);
11683 }
11684 
11685 static int
11686 ctl_scsiio_precheck(struct ctl_softc *ctl_softc, struct ctl_scsiio *ctsio)
11687 {
11688 	struct ctl_lun *lun;
11689 	const struct ctl_cmd_entry *entry;
11690 	uint32_t initidx, targ_lun;
11691 	int retval;
11692 
11693 	retval = 0;
11694 
11695 	lun = NULL;
11696 
11697 	targ_lun = ctsio->io_hdr.nexus.targ_mapped_lun;
11698 	if ((targ_lun < CTL_MAX_LUNS)
11699 	 && (ctl_softc->ctl_luns[targ_lun] != NULL)) {
11700 		lun = ctl_softc->ctl_luns[targ_lun];
11701 		/*
11702 		 * If the LUN is invalid, pretend that it doesn't exist.
11703 		 * It will go away as soon as all pending I/O has been
11704 		 * completed.
11705 		 */
11706 		if (lun->flags & CTL_LUN_DISABLED) {
11707 			lun = NULL;
11708 		} else {
11709 			ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = lun;
11710 			ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr =
11711 				lun->be_lun;
11712 			if (lun->be_lun->lun_type == T_PROCESSOR) {
11713 				ctsio->io_hdr.flags |= CTL_FLAG_CONTROL_DEV;
11714 			}
11715 
11716 			/*
11717 			 * Every I/O goes into the OOA queue for a
11718 			 * particular LUN, and stays there until completion.
11719 			 */
11720 			mtx_lock(&lun->lun_lock);
11721 			TAILQ_INSERT_TAIL(&lun->ooa_queue, &ctsio->io_hdr,
11722 			    ooa_links);
11723 		}
11724 	} else {
11725 		ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr = NULL;
11726 		ctsio->io_hdr.ctl_private[CTL_PRIV_BACKEND_LUN].ptr = NULL;
11727 	}
11728 
11729 	/* Get command entry and return error if it is unsuppotyed. */
11730 	entry = ctl_validate_command(ctsio);
11731 	if (entry == NULL) {
11732 		if (lun)
11733 			mtx_unlock(&lun->lun_lock);
11734 		return (retval);
11735 	}
11736 
11737 	ctsio->io_hdr.flags &= ~CTL_FLAG_DATA_MASK;
11738 	ctsio->io_hdr.flags |= entry->flags & CTL_FLAG_DATA_MASK;
11739 
11740 	/*
11741 	 * Check to see whether we can send this command to LUNs that don't
11742 	 * exist.  This should pretty much only be the case for inquiry
11743 	 * and request sense.  Further checks, below, really require having
11744 	 * a LUN, so we can't really check the command anymore.  Just put
11745 	 * it on the rtr queue.
11746 	 */
11747 	if (lun == NULL) {
11748 		if (entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) {
11749 			ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11750 			ctl_enqueue_rtr((union ctl_io *)ctsio);
11751 			return (retval);
11752 		}
11753 
11754 		ctl_set_unsupported_lun(ctsio);
11755 		ctl_done((union ctl_io *)ctsio);
11756 		CTL_DEBUG_PRINT(("ctl_scsiio_precheck: bailing out due to invalid LUN\n"));
11757 		return (retval);
11758 	} else {
11759 		/*
11760 		 * Make sure we support this particular command on this LUN.
11761 		 * e.g., we don't support writes to the control LUN.
11762 		 */
11763 		if (!ctl_cmd_applicable(lun->be_lun->lun_type, entry)) {
11764 			mtx_unlock(&lun->lun_lock);
11765 			ctl_set_invalid_opcode(ctsio);
11766 			ctl_done((union ctl_io *)ctsio);
11767 			return (retval);
11768 		}
11769 	}
11770 
11771 	initidx = ctl_get_initindex(&ctsio->io_hdr.nexus);
11772 
11773 #ifdef CTL_WITH_CA
11774 	/*
11775 	 * If we've got a request sense, it'll clear the contingent
11776 	 * allegiance condition.  Otherwise, if we have a CA condition for
11777 	 * this initiator, clear it, because it sent down a command other
11778 	 * than request sense.
11779 	 */
11780 	if ((ctsio->cdb[0] != REQUEST_SENSE)
11781 	 && (ctl_is_set(lun->have_ca, initidx)))
11782 		ctl_clear_mask(lun->have_ca, initidx);
11783 #endif
11784 
11785 	/*
11786 	 * If the command has this flag set, it handles its own unit
11787 	 * attention reporting, we shouldn't do anything.  Otherwise we
11788 	 * check for any pending unit attentions, and send them back to the
11789 	 * initiator.  We only do this when a command initially comes in,
11790 	 * not when we pull it off the blocked queue.
11791 	 *
11792 	 * According to SAM-3, section 5.3.2, the order that things get
11793 	 * presented back to the host is basically unit attentions caused
11794 	 * by some sort of reset event, busy status, reservation conflicts
11795 	 * or task set full, and finally any other status.
11796 	 *
11797 	 * One issue here is that some of the unit attentions we report
11798 	 * don't fall into the "reset" category (e.g. "reported luns data
11799 	 * has changed").  So reporting it here, before the reservation
11800 	 * check, may be technically wrong.  I guess the only thing to do
11801 	 * would be to check for and report the reset events here, and then
11802 	 * check for the other unit attention types after we check for a
11803 	 * reservation conflict.
11804 	 *
11805 	 * XXX KDM need to fix this
11806 	 */
11807 	if ((entry->flags & CTL_CMD_FLAG_NO_SENSE) == 0) {
11808 		ctl_ua_type ua_type;
11809 
11810 		if (lun->pending_ua[initidx] != CTL_UA_NONE) {
11811 			scsi_sense_data_type sense_format;
11812 
11813 			if (lun != NULL)
11814 				sense_format = (lun->flags &
11815 				    CTL_LUN_SENSE_DESC) ? SSD_TYPE_DESC :
11816 				    SSD_TYPE_FIXED;
11817 			else
11818 				sense_format = SSD_TYPE_FIXED;
11819 
11820 			ua_type = ctl_build_ua(&lun->pending_ua[initidx],
11821 			    &ctsio->sense_data, sense_format);
11822 			if (ua_type != CTL_UA_NONE) {
11823 				ctsio->scsi_status = SCSI_STATUS_CHECK_COND;
11824 				ctsio->io_hdr.status = CTL_SCSI_ERROR |
11825 						       CTL_AUTOSENSE;
11826 				ctsio->sense_len = SSD_FULL_SIZE;
11827 				mtx_unlock(&lun->lun_lock);
11828 				ctl_done((union ctl_io *)ctsio);
11829 				return (retval);
11830 			}
11831 		}
11832 	}
11833 
11834 
11835 	if (ctl_scsiio_lun_check(ctl_softc, lun, entry, ctsio) != 0) {
11836 		mtx_unlock(&lun->lun_lock);
11837 		ctl_done((union ctl_io *)ctsio);
11838 		return (retval);
11839 	}
11840 
11841 	/*
11842 	 * XXX CHD this is where we want to send IO to other side if
11843 	 * this LUN is secondary on this SC. We will need to make a copy
11844 	 * of the IO and flag the IO on this side as SENT_2OTHER and the flag
11845 	 * the copy we send as FROM_OTHER.
11846 	 * We also need to stuff the address of the original IO so we can
11847 	 * find it easily. Something similar will need be done on the other
11848 	 * side so when we are done we can find the copy.
11849 	 */
11850 	if ((lun->flags & CTL_LUN_PRIMARY_SC) == 0) {
11851 		union ctl_ha_msg msg_info;
11852 		int isc_retval;
11853 
11854 		ctsio->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
11855 
11856 		msg_info.hdr.msg_type = CTL_MSG_SERIALIZE;
11857 		msg_info.hdr.original_sc = (union ctl_io *)ctsio;
11858 #if 0
11859 		printf("1. ctsio %p\n", ctsio);
11860 #endif
11861 		msg_info.hdr.serializing_sc = NULL;
11862 		msg_info.hdr.nexus = ctsio->io_hdr.nexus;
11863 		msg_info.scsi.tag_num = ctsio->tag_num;
11864 		msg_info.scsi.tag_type = ctsio->tag_type;
11865 		memcpy(msg_info.scsi.cdb, ctsio->cdb, CTL_MAX_CDBLEN);
11866 
11867 		ctsio->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
11868 
11869 		if ((isc_retval=ctl_ha_msg_send(CTL_HA_CHAN_CTL,
11870 		    (void *)&msg_info, sizeof(msg_info), 0)) >
11871 		    CTL_HA_STATUS_SUCCESS) {
11872 			printf("CTL:precheck, ctl_ha_msg_send returned %d\n",
11873 			       isc_retval);
11874 			printf("CTL:opcode is %x\n", ctsio->cdb[0]);
11875 		} else {
11876 #if 0
11877 			printf("CTL:Precheck sent msg, opcode is %x\n",opcode);
11878 #endif
11879 		}
11880 
11881 		/*
11882 		 * XXX KDM this I/O is off the incoming queue, but hasn't
11883 		 * been inserted on any other queue.  We may need to come
11884 		 * up with a holding queue while we wait for serialization
11885 		 * so that we have an idea of what we're waiting for from
11886 		 * the other side.
11887 		 */
11888 		mtx_unlock(&lun->lun_lock);
11889 		return (retval);
11890 	}
11891 
11892 	switch (ctl_check_ooa(lun, (union ctl_io *)ctsio,
11893 			      (union ctl_io *)TAILQ_PREV(&ctsio->io_hdr,
11894 			      ctl_ooaq, ooa_links))) {
11895 	case CTL_ACTION_BLOCK:
11896 		ctsio->io_hdr.flags |= CTL_FLAG_BLOCKED;
11897 		TAILQ_INSERT_TAIL(&lun->blocked_queue, &ctsio->io_hdr,
11898 				  blocked_links);
11899 		mtx_unlock(&lun->lun_lock);
11900 		return (retval);
11901 	case CTL_ACTION_PASS:
11902 	case CTL_ACTION_SKIP:
11903 		ctsio->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
11904 		mtx_unlock(&lun->lun_lock);
11905 		ctl_enqueue_rtr((union ctl_io *)ctsio);
11906 		break;
11907 	case CTL_ACTION_OVERLAP:
11908 		mtx_unlock(&lun->lun_lock);
11909 		ctl_set_overlapped_cmd(ctsio);
11910 		ctl_done((union ctl_io *)ctsio);
11911 		break;
11912 	case CTL_ACTION_OVERLAP_TAG:
11913 		mtx_unlock(&lun->lun_lock);
11914 		ctl_set_overlapped_tag(ctsio, ctsio->tag_num & 0xff);
11915 		ctl_done((union ctl_io *)ctsio);
11916 		break;
11917 	case CTL_ACTION_ERROR:
11918 	default:
11919 		mtx_unlock(&lun->lun_lock);
11920 		ctl_set_internal_failure(ctsio,
11921 					 /*sks_valid*/ 0,
11922 					 /*retry_count*/ 0);
11923 		ctl_done((union ctl_io *)ctsio);
11924 		break;
11925 	}
11926 	return (retval);
11927 }
11928 
11929 const struct ctl_cmd_entry *
11930 ctl_get_cmd_entry(struct ctl_scsiio *ctsio, int *sa)
11931 {
11932 	const struct ctl_cmd_entry *entry;
11933 	int service_action;
11934 
11935 	entry = &ctl_cmd_table[ctsio->cdb[0]];
11936 	if (sa)
11937 		*sa = ((entry->flags & CTL_CMD_FLAG_SA5) != 0);
11938 	if (entry->flags & CTL_CMD_FLAG_SA5) {
11939 		service_action = ctsio->cdb[1] & SERVICE_ACTION_MASK;
11940 		entry = &((const struct ctl_cmd_entry *)
11941 		    entry->execute)[service_action];
11942 	}
11943 	return (entry);
11944 }
11945 
11946 const struct ctl_cmd_entry *
11947 ctl_validate_command(struct ctl_scsiio *ctsio)
11948 {
11949 	const struct ctl_cmd_entry *entry;
11950 	int i, sa;
11951 	uint8_t diff;
11952 
11953 	entry = ctl_get_cmd_entry(ctsio, &sa);
11954 	if (entry->execute == NULL) {
11955 		if (sa)
11956 			ctl_set_invalid_field(ctsio,
11957 					      /*sks_valid*/ 1,
11958 					      /*command*/ 1,
11959 					      /*field*/ 1,
11960 					      /*bit_valid*/ 1,
11961 					      /*bit*/ 4);
11962 		else
11963 			ctl_set_invalid_opcode(ctsio);
11964 		ctl_done((union ctl_io *)ctsio);
11965 		return (NULL);
11966 	}
11967 	KASSERT(entry->length > 0,
11968 	    ("Not defined length for command 0x%02x/0x%02x",
11969 	     ctsio->cdb[0], ctsio->cdb[1]));
11970 	for (i = 1; i < entry->length; i++) {
11971 		diff = ctsio->cdb[i] & ~entry->usage[i - 1];
11972 		if (diff == 0)
11973 			continue;
11974 		ctl_set_invalid_field(ctsio,
11975 				      /*sks_valid*/ 1,
11976 				      /*command*/ 1,
11977 				      /*field*/ i,
11978 				      /*bit_valid*/ 1,
11979 				      /*bit*/ fls(diff) - 1);
11980 		ctl_done((union ctl_io *)ctsio);
11981 		return (NULL);
11982 	}
11983 	return (entry);
11984 }
11985 
11986 static int
11987 ctl_cmd_applicable(uint8_t lun_type, const struct ctl_cmd_entry *entry)
11988 {
11989 
11990 	switch (lun_type) {
11991 	case T_PROCESSOR:
11992 		if (((entry->flags & CTL_CMD_FLAG_OK_ON_PROC) == 0) &&
11993 		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11994 			return (0);
11995 		break;
11996 	case T_DIRECT:
11997 		if (((entry->flags & CTL_CMD_FLAG_OK_ON_SLUN) == 0) &&
11998 		    ((entry->flags & CTL_CMD_FLAG_OK_ON_ALL_LUNS) == 0))
11999 			return (0);
12000 		break;
12001 	default:
12002 		return (0);
12003 	}
12004 	return (1);
12005 }
12006 
12007 static int
12008 ctl_scsiio(struct ctl_scsiio *ctsio)
12009 {
12010 	int retval;
12011 	const struct ctl_cmd_entry *entry;
12012 
12013 	retval = CTL_RETVAL_COMPLETE;
12014 
12015 	CTL_DEBUG_PRINT(("ctl_scsiio cdb[0]=%02X\n", ctsio->cdb[0]));
12016 
12017 	entry = ctl_get_cmd_entry(ctsio, NULL);
12018 
12019 	/*
12020 	 * If this I/O has been aborted, just send it straight to
12021 	 * ctl_done() without executing it.
12022 	 */
12023 	if (ctsio->io_hdr.flags & CTL_FLAG_ABORT) {
12024 		ctl_done((union ctl_io *)ctsio);
12025 		goto bailout;
12026 	}
12027 
12028 	/*
12029 	 * All the checks should have been handled by ctl_scsiio_precheck().
12030 	 * We should be clear now to just execute the I/O.
12031 	 */
12032 	retval = entry->execute(ctsio);
12033 
12034 bailout:
12035 	return (retval);
12036 }
12037 
12038 /*
12039  * Since we only implement one target right now, a bus reset simply resets
12040  * our single target.
12041  */
12042 static int
12043 ctl_bus_reset(struct ctl_softc *ctl_softc, union ctl_io *io)
12044 {
12045 	return(ctl_target_reset(ctl_softc, io, CTL_UA_BUS_RESET));
12046 }
12047 
12048 static int
12049 ctl_target_reset(struct ctl_softc *ctl_softc, union ctl_io *io,
12050 		 ctl_ua_type ua_type)
12051 {
12052 	struct ctl_lun *lun;
12053 	int retval;
12054 
12055 	if (!(io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12056 		union ctl_ha_msg msg_info;
12057 
12058 		io->io_hdr.flags |= CTL_FLAG_SENT_2OTHER_SC;
12059 		msg_info.hdr.nexus = io->io_hdr.nexus;
12060 		if (ua_type==CTL_UA_TARG_RESET)
12061 			msg_info.task.task_action = CTL_TASK_TARGET_RESET;
12062 		else
12063 			msg_info.task.task_action = CTL_TASK_BUS_RESET;
12064 		msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12065 		msg_info.hdr.original_sc = NULL;
12066 		msg_info.hdr.serializing_sc = NULL;
12067 		if (CTL_HA_STATUS_SUCCESS != ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12068 		    (void *)&msg_info, sizeof(msg_info), 0)) {
12069 		}
12070 	}
12071 	retval = 0;
12072 
12073 	mtx_lock(&ctl_softc->ctl_lock);
12074 	STAILQ_FOREACH(lun, &ctl_softc->lun_list, links)
12075 		retval += ctl_lun_reset(lun, io, ua_type);
12076 	mtx_unlock(&ctl_softc->ctl_lock);
12077 
12078 	return (retval);
12079 }
12080 
12081 /*
12082  * The LUN should always be set.  The I/O is optional, and is used to
12083  * distinguish between I/Os sent by this initiator, and by other
12084  * initiators.  We set unit attention for initiators other than this one.
12085  * SAM-3 is vague on this point.  It does say that a unit attention should
12086  * be established for other initiators when a LUN is reset (see section
12087  * 5.7.3), but it doesn't specifically say that the unit attention should
12088  * be established for this particular initiator when a LUN is reset.  Here
12089  * is the relevant text, from SAM-3 rev 8:
12090  *
12091  * 5.7.2 When a SCSI initiator port aborts its own tasks
12092  *
12093  * When a SCSI initiator port causes its own task(s) to be aborted, no
12094  * notification that the task(s) have been aborted shall be returned to
12095  * the SCSI initiator port other than the completion response for the
12096  * command or task management function action that caused the task(s) to
12097  * be aborted and notification(s) associated with related effects of the
12098  * action (e.g., a reset unit attention condition).
12099  *
12100  * XXX KDM for now, we're setting unit attention for all initiators.
12101  */
12102 static int
12103 ctl_lun_reset(struct ctl_lun *lun, union ctl_io *io, ctl_ua_type ua_type)
12104 {
12105 	union ctl_io *xio;
12106 #if 0
12107 	uint32_t initindex;
12108 #endif
12109 	int i;
12110 
12111 	mtx_lock(&lun->lun_lock);
12112 	/*
12113 	 * Run through the OOA queue and abort each I/O.
12114 	 */
12115 #if 0
12116 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12117 #endif
12118 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12119 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12120 		xio->io_hdr.flags |= CTL_FLAG_ABORT | CTL_FLAG_ABORT_STATUS;
12121 	}
12122 
12123 	/*
12124 	 * This version sets unit attention for every
12125 	 */
12126 #if 0
12127 	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12128 	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12129 		if (initindex == i)
12130 			continue;
12131 		lun->pending_ua[i] |= ua_type;
12132 	}
12133 #endif
12134 
12135 	/*
12136 	 * A reset (any kind, really) clears reservations established with
12137 	 * RESERVE/RELEASE.  It does not clear reservations established
12138 	 * with PERSISTENT RESERVE OUT, but we don't support that at the
12139 	 * moment anyway.  See SPC-2, section 5.6.  SPC-3 doesn't address
12140 	 * reservations made with the RESERVE/RELEASE commands, because
12141 	 * those commands are obsolete in SPC-3.
12142 	 */
12143 	lun->flags &= ~CTL_LUN_RESERVED;
12144 
12145 	for (i = 0; i < CTL_MAX_INITIATORS; i++) {
12146 #ifdef CTL_WITH_CA
12147 		ctl_clear_mask(lun->have_ca, i);
12148 #endif
12149 		lun->pending_ua[i] |= ua_type;
12150 	}
12151 	mtx_unlock(&lun->lun_lock);
12152 
12153 	return (0);
12154 }
12155 
12156 static void
12157 ctl_abort_tasks_lun(struct ctl_lun *lun, uint32_t targ_port, uint32_t init_id,
12158     int other_sc)
12159 {
12160 	union ctl_io *xio;
12161 
12162 	mtx_assert(&lun->lun_lock, MA_OWNED);
12163 
12164 	/*
12165 	 * Run through the OOA queue and attempt to find the given I/O.
12166 	 * The target port, initiator ID, tag type and tag number have to
12167 	 * match the values that we got from the initiator.  If we have an
12168 	 * untagged command to abort, simply abort the first untagged command
12169 	 * we come to.  We only allow one untagged command at a time of course.
12170 	 */
12171 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12172 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12173 
12174 		if ((targ_port == UINT32_MAX ||
12175 		     targ_port == xio->io_hdr.nexus.targ_port) &&
12176 		    (init_id == UINT32_MAX ||
12177 		     init_id == xio->io_hdr.nexus.initid.id)) {
12178 			if (targ_port != xio->io_hdr.nexus.targ_port ||
12179 			    init_id != xio->io_hdr.nexus.initid.id)
12180 				xio->io_hdr.flags |= CTL_FLAG_ABORT_STATUS;
12181 			xio->io_hdr.flags |= CTL_FLAG_ABORT;
12182 			if (!other_sc && !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12183 				union ctl_ha_msg msg_info;
12184 
12185 				msg_info.hdr.nexus = xio->io_hdr.nexus;
12186 				msg_info.task.task_action = CTL_TASK_ABORT_TASK;
12187 				msg_info.task.tag_num = xio->scsiio.tag_num;
12188 				msg_info.task.tag_type = xio->scsiio.tag_type;
12189 				msg_info.hdr.msg_type = CTL_MSG_MANAGE_TASKS;
12190 				msg_info.hdr.original_sc = NULL;
12191 				msg_info.hdr.serializing_sc = NULL;
12192 				ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12193 				    (void *)&msg_info, sizeof(msg_info), 0);
12194 			}
12195 		}
12196 	}
12197 }
12198 
12199 static int
12200 ctl_abort_task_set(union ctl_io *io)
12201 {
12202 	struct ctl_softc *softc = control_softc;
12203 	struct ctl_lun *lun;
12204 	uint32_t targ_lun;
12205 
12206 	/*
12207 	 * Look up the LUN.
12208 	 */
12209 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12210 	mtx_lock(&softc->ctl_lock);
12211 	if ((targ_lun < CTL_MAX_LUNS) && (softc->ctl_luns[targ_lun] != NULL))
12212 		lun = softc->ctl_luns[targ_lun];
12213 	else {
12214 		mtx_unlock(&softc->ctl_lock);
12215 		return (1);
12216 	}
12217 
12218 	mtx_lock(&lun->lun_lock);
12219 	mtx_unlock(&softc->ctl_lock);
12220 	if (io->taskio.task_action == CTL_TASK_ABORT_TASK_SET) {
12221 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12222 		    io->io_hdr.nexus.initid.id,
12223 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12224 	} else { /* CTL_TASK_CLEAR_TASK_SET */
12225 		ctl_abort_tasks_lun(lun, UINT32_MAX, UINT32_MAX,
12226 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12227 	}
12228 	mtx_unlock(&lun->lun_lock);
12229 	return (0);
12230 }
12231 
12232 static int
12233 ctl_i_t_nexus_reset(union ctl_io *io)
12234 {
12235 	struct ctl_softc *softc = control_softc;
12236 	struct ctl_lun *lun;
12237 	uint32_t initindex, residx;
12238 
12239 	initindex = ctl_get_initindex(&io->io_hdr.nexus);
12240 	residx = ctl_get_resindex(&io->io_hdr.nexus);
12241 	mtx_lock(&softc->ctl_lock);
12242 	STAILQ_FOREACH(lun, &softc->lun_list, links) {
12243 		mtx_lock(&lun->lun_lock);
12244 		ctl_abort_tasks_lun(lun, io->io_hdr.nexus.targ_port,
12245 		    io->io_hdr.nexus.initid.id,
12246 		    (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC) != 0);
12247 #ifdef CTL_WITH_CA
12248 		ctl_clear_mask(lun->have_ca, initindex);
12249 #endif
12250 		if ((lun->flags & CTL_LUN_RESERVED) && (lun->res_idx == residx))
12251 			lun->flags &= ~CTL_LUN_RESERVED;
12252 		lun->pending_ua[initindex] |= CTL_UA_I_T_NEXUS_LOSS;
12253 		mtx_unlock(&lun->lun_lock);
12254 	}
12255 	mtx_unlock(&softc->ctl_lock);
12256 	return (0);
12257 }
12258 
12259 static int
12260 ctl_abort_task(union ctl_io *io)
12261 {
12262 	union ctl_io *xio;
12263 	struct ctl_lun *lun;
12264 	struct ctl_softc *ctl_softc;
12265 #if 0
12266 	struct sbuf sb;
12267 	char printbuf[128];
12268 #endif
12269 	int found;
12270 	uint32_t targ_lun;
12271 
12272 	ctl_softc = control_softc;
12273 	found = 0;
12274 
12275 	/*
12276 	 * Look up the LUN.
12277 	 */
12278 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12279 	mtx_lock(&ctl_softc->ctl_lock);
12280 	if ((targ_lun < CTL_MAX_LUNS)
12281 	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12282 		lun = ctl_softc->ctl_luns[targ_lun];
12283 	else {
12284 		mtx_unlock(&ctl_softc->ctl_lock);
12285 		return (1);
12286 	}
12287 
12288 #if 0
12289 	printf("ctl_abort_task: called for lun %lld, tag %d type %d\n",
12290 	       lun->lun, io->taskio.tag_num, io->taskio.tag_type);
12291 #endif
12292 
12293 	mtx_lock(&lun->lun_lock);
12294 	mtx_unlock(&ctl_softc->ctl_lock);
12295 	/*
12296 	 * Run through the OOA queue and attempt to find the given I/O.
12297 	 * The target port, initiator ID, tag type and tag number have to
12298 	 * match the values that we got from the initiator.  If we have an
12299 	 * untagged command to abort, simply abort the first untagged command
12300 	 * we come to.  We only allow one untagged command at a time of course.
12301 	 */
12302 #if 0
12303 	TAILQ_FOREACH((struct ctl_io_hdr *)xio, &lun->ooa_queue, ooa_links) {
12304 #endif
12305 	for (xio = (union ctl_io *)TAILQ_FIRST(&lun->ooa_queue); xio != NULL;
12306 	     xio = (union ctl_io *)TAILQ_NEXT(&xio->io_hdr, ooa_links)) {
12307 #if 0
12308 		sbuf_new(&sb, printbuf, sizeof(printbuf), SBUF_FIXEDLEN);
12309 
12310 		sbuf_printf(&sb, "LUN %lld tag %d type %d%s%s%s%s: ",
12311 			    lun->lun, xio->scsiio.tag_num,
12312 			    xio->scsiio.tag_type,
12313 			    (xio->io_hdr.blocked_links.tqe_prev
12314 			    == NULL) ? "" : " BLOCKED",
12315 			    (xio->io_hdr.flags &
12316 			    CTL_FLAG_DMA_INPROG) ? " DMA" : "",
12317 			    (xio->io_hdr.flags &
12318 			    CTL_FLAG_ABORT) ? " ABORT" : "",
12319 			    (xio->io_hdr.flags &
12320 			    CTL_FLAG_IS_WAS_ON_RTR ? " RTR" : ""));
12321 		ctl_scsi_command_string(&xio->scsiio, NULL, &sb);
12322 		sbuf_finish(&sb);
12323 		printf("%s\n", sbuf_data(&sb));
12324 #endif
12325 
12326 		if ((xio->io_hdr.nexus.targ_port == io->io_hdr.nexus.targ_port)
12327 		 && (xio->io_hdr.nexus.initid.id ==
12328 		     io->io_hdr.nexus.initid.id)) {
12329 			/*
12330 			 * If the abort says that the task is untagged, the
12331 			 * task in the queue must be untagged.  Otherwise,
12332 			 * we just check to see whether the tag numbers
12333 			 * match.  This is because the QLogic firmware
12334 			 * doesn't pass back the tag type in an abort
12335 			 * request.
12336 			 */
12337 #if 0
12338 			if (((xio->scsiio.tag_type == CTL_TAG_UNTAGGED)
12339 			  && (io->taskio.tag_type == CTL_TAG_UNTAGGED))
12340 			 || (xio->scsiio.tag_num == io->taskio.tag_num)) {
12341 #endif
12342 			/*
12343 			 * XXX KDM we've got problems with FC, because it
12344 			 * doesn't send down a tag type with aborts.  So we
12345 			 * can only really go by the tag number...
12346 			 * This may cause problems with parallel SCSI.
12347 			 * Need to figure that out!!
12348 			 */
12349 			if (xio->scsiio.tag_num == io->taskio.tag_num) {
12350 				xio->io_hdr.flags |= CTL_FLAG_ABORT;
12351 				found = 1;
12352 				if ((io->io_hdr.flags &
12353 				     CTL_FLAG_FROM_OTHER_SC) == 0 &&
12354 				    !(lun->flags & CTL_LUN_PRIMARY_SC)) {
12355 					union ctl_ha_msg msg_info;
12356 
12357 					io->io_hdr.flags |=
12358 					                CTL_FLAG_SENT_2OTHER_SC;
12359 					msg_info.hdr.nexus = io->io_hdr.nexus;
12360 					msg_info.task.task_action =
12361 						CTL_TASK_ABORT_TASK;
12362 					msg_info.task.tag_num =
12363 						io->taskio.tag_num;
12364 					msg_info.task.tag_type =
12365 						io->taskio.tag_type;
12366 					msg_info.hdr.msg_type =
12367 						CTL_MSG_MANAGE_TASKS;
12368 					msg_info.hdr.original_sc = NULL;
12369 					msg_info.hdr.serializing_sc = NULL;
12370 #if 0
12371 					printf("Sent Abort to other side\n");
12372 #endif
12373 					if (CTL_HA_STATUS_SUCCESS !=
12374 					        ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12375 		    				(void *)&msg_info,
12376 						sizeof(msg_info), 0)) {
12377 					}
12378 				}
12379 #if 0
12380 				printf("ctl_abort_task: found I/O to abort\n");
12381 #endif
12382 				break;
12383 			}
12384 		}
12385 	}
12386 	mtx_unlock(&lun->lun_lock);
12387 
12388 	if (found == 0) {
12389 		/*
12390 		 * This isn't really an error.  It's entirely possible for
12391 		 * the abort and command completion to cross on the wire.
12392 		 * This is more of an informative/diagnostic error.
12393 		 */
12394 #if 0
12395 		printf("ctl_abort_task: ABORT sent for nonexistent I/O: "
12396 		       "%d:%d:%d:%d tag %d type %d\n",
12397 		       io->io_hdr.nexus.initid.id,
12398 		       io->io_hdr.nexus.targ_port,
12399 		       io->io_hdr.nexus.targ_target.id,
12400 		       io->io_hdr.nexus.targ_lun, io->taskio.tag_num,
12401 		       io->taskio.tag_type);
12402 #endif
12403 	}
12404 	return (0);
12405 }
12406 
12407 static void
12408 ctl_run_task(union ctl_io *io)
12409 {
12410 	struct ctl_softc *ctl_softc = control_softc;
12411 	int retval = 1;
12412 	const char *task_desc;
12413 
12414 	CTL_DEBUG_PRINT(("ctl_run_task\n"));
12415 
12416 	KASSERT(io->io_hdr.io_type == CTL_IO_TASK,
12417 	    ("ctl_run_task: Unextected io_type %d\n",
12418 	     io->io_hdr.io_type));
12419 
12420 	task_desc = ctl_scsi_task_string(&io->taskio);
12421 	if (task_desc != NULL) {
12422 #ifdef NEEDTOPORT
12423 		csevent_log(CSC_CTL | CSC_SHELF_SW |
12424 			    CTL_TASK_REPORT,
12425 			    csevent_LogType_Trace,
12426 			    csevent_Severity_Information,
12427 			    csevent_AlertLevel_Green,
12428 			    csevent_FRU_Firmware,
12429 			    csevent_FRU_Unknown,
12430 			    "CTL: received task: %s",task_desc);
12431 #endif
12432 	} else {
12433 #ifdef NEEDTOPORT
12434 		csevent_log(CSC_CTL | CSC_SHELF_SW |
12435 			    CTL_TASK_REPORT,
12436 			    csevent_LogType_Trace,
12437 			    csevent_Severity_Information,
12438 			    csevent_AlertLevel_Green,
12439 			    csevent_FRU_Firmware,
12440 			    csevent_FRU_Unknown,
12441 			    "CTL: received unknown task "
12442 			    "type: %d (%#x)",
12443 			    io->taskio.task_action,
12444 			    io->taskio.task_action);
12445 #endif
12446 	}
12447 	switch (io->taskio.task_action) {
12448 	case CTL_TASK_ABORT_TASK:
12449 		retval = ctl_abort_task(io);
12450 		break;
12451 	case CTL_TASK_ABORT_TASK_SET:
12452 	case CTL_TASK_CLEAR_TASK_SET:
12453 		retval = ctl_abort_task_set(io);
12454 		break;
12455 	case CTL_TASK_CLEAR_ACA:
12456 		break;
12457 	case CTL_TASK_I_T_NEXUS_RESET:
12458 		retval = ctl_i_t_nexus_reset(io);
12459 		break;
12460 	case CTL_TASK_LUN_RESET: {
12461 		struct ctl_lun *lun;
12462 		uint32_t targ_lun;
12463 
12464 		targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12465 		mtx_lock(&ctl_softc->ctl_lock);
12466 		if ((targ_lun < CTL_MAX_LUNS)
12467 		 && (ctl_softc->ctl_luns[targ_lun] != NULL))
12468 			lun = ctl_softc->ctl_luns[targ_lun];
12469 		else {
12470 			mtx_unlock(&ctl_softc->ctl_lock);
12471 			retval = 1;
12472 			break;
12473 		}
12474 
12475 		if (!(io->io_hdr.flags &
12476 		    CTL_FLAG_FROM_OTHER_SC)) {
12477 			union ctl_ha_msg msg_info;
12478 
12479 			io->io_hdr.flags |=
12480 				CTL_FLAG_SENT_2OTHER_SC;
12481 			msg_info.hdr.msg_type =
12482 				CTL_MSG_MANAGE_TASKS;
12483 			msg_info.hdr.nexus = io->io_hdr.nexus;
12484 			msg_info.task.task_action =
12485 				CTL_TASK_LUN_RESET;
12486 			msg_info.hdr.original_sc = NULL;
12487 			msg_info.hdr.serializing_sc = NULL;
12488 			if (CTL_HA_STATUS_SUCCESS !=
12489 			    ctl_ha_msg_send(CTL_HA_CHAN_CTL,
12490 			    (void *)&msg_info,
12491 			    sizeof(msg_info), 0)) {
12492 			}
12493 		}
12494 
12495 		retval = ctl_lun_reset(lun, io,
12496 				       CTL_UA_LUN_RESET);
12497 		mtx_unlock(&ctl_softc->ctl_lock);
12498 		break;
12499 	}
12500 	case CTL_TASK_TARGET_RESET:
12501 		retval = ctl_target_reset(ctl_softc, io, CTL_UA_TARG_RESET);
12502 		break;
12503 	case CTL_TASK_BUS_RESET:
12504 		retval = ctl_bus_reset(ctl_softc, io);
12505 		break;
12506 	case CTL_TASK_PORT_LOGIN:
12507 		break;
12508 	case CTL_TASK_PORT_LOGOUT:
12509 		break;
12510 	default:
12511 		printf("ctl_run_task: got unknown task management event %d\n",
12512 		       io->taskio.task_action);
12513 		break;
12514 	}
12515 	if (retval == 0)
12516 		io->io_hdr.status = CTL_SUCCESS;
12517 	else
12518 		io->io_hdr.status = CTL_ERROR;
12519 	ctl_done(io);
12520 }
12521 
12522 /*
12523  * For HA operation.  Handle commands that come in from the other
12524  * controller.
12525  */
12526 static void
12527 ctl_handle_isc(union ctl_io *io)
12528 {
12529 	int free_io;
12530 	struct ctl_lun *lun;
12531 	struct ctl_softc *ctl_softc;
12532 	uint32_t targ_lun;
12533 
12534 	ctl_softc = control_softc;
12535 
12536 	targ_lun = io->io_hdr.nexus.targ_mapped_lun;
12537 	lun = ctl_softc->ctl_luns[targ_lun];
12538 
12539 	switch (io->io_hdr.msg_type) {
12540 	case CTL_MSG_SERIALIZE:
12541 		free_io = ctl_serialize_other_sc_cmd(&io->scsiio);
12542 		break;
12543 	case CTL_MSG_R2R: {
12544 		const struct ctl_cmd_entry *entry;
12545 
12546 		/*
12547 		 * This is only used in SER_ONLY mode.
12548 		 */
12549 		free_io = 0;
12550 		entry = ctl_get_cmd_entry(&io->scsiio, NULL);
12551 		mtx_lock(&lun->lun_lock);
12552 		if (ctl_scsiio_lun_check(ctl_softc, lun,
12553 		    entry, (struct ctl_scsiio *)io) != 0) {
12554 			mtx_unlock(&lun->lun_lock);
12555 			ctl_done(io);
12556 			break;
12557 		}
12558 		io->io_hdr.flags |= CTL_FLAG_IS_WAS_ON_RTR;
12559 		mtx_unlock(&lun->lun_lock);
12560 		ctl_enqueue_rtr(io);
12561 		break;
12562 	}
12563 	case CTL_MSG_FINISH_IO:
12564 		if (ctl_softc->ha_mode == CTL_HA_MODE_XFER) {
12565 			free_io = 0;
12566 			ctl_done(io);
12567 		} else {
12568 			free_io = 1;
12569 			mtx_lock(&lun->lun_lock);
12570 			TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr,
12571 				     ooa_links);
12572 			ctl_check_blocked(lun);
12573 			mtx_unlock(&lun->lun_lock);
12574 		}
12575 		break;
12576 	case CTL_MSG_PERS_ACTION:
12577 		ctl_hndl_per_res_out_on_other_sc(
12578 			(union ctl_ha_msg *)&io->presio.pr_msg);
12579 		free_io = 1;
12580 		break;
12581 	case CTL_MSG_BAD_JUJU:
12582 		free_io = 0;
12583 		ctl_done(io);
12584 		break;
12585 	case CTL_MSG_DATAMOVE:
12586 		/* Only used in XFER mode */
12587 		free_io = 0;
12588 		ctl_datamove_remote(io);
12589 		break;
12590 	case CTL_MSG_DATAMOVE_DONE:
12591 		/* Only used in XFER mode */
12592 		free_io = 0;
12593 		io->scsiio.be_move_done(io);
12594 		break;
12595 	default:
12596 		free_io = 1;
12597 		printf("%s: Invalid message type %d\n",
12598 		       __func__, io->io_hdr.msg_type);
12599 		break;
12600 	}
12601 	if (free_io)
12602 		ctl_free_io(io);
12603 
12604 }
12605 
12606 
12607 /*
12608  * Returns the match type in the case of a match, or CTL_LUN_PAT_NONE if
12609  * there is no match.
12610  */
12611 static ctl_lun_error_pattern
12612 ctl_cmd_pattern_match(struct ctl_scsiio *ctsio, struct ctl_error_desc *desc)
12613 {
12614 	const struct ctl_cmd_entry *entry;
12615 	ctl_lun_error_pattern filtered_pattern, pattern;
12616 
12617 	pattern = desc->error_pattern;
12618 
12619 	/*
12620 	 * XXX KDM we need more data passed into this function to match a
12621 	 * custom pattern, and we actually need to implement custom pattern
12622 	 * matching.
12623 	 */
12624 	if (pattern & CTL_LUN_PAT_CMD)
12625 		return (CTL_LUN_PAT_CMD);
12626 
12627 	if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_ANY)
12628 		return (CTL_LUN_PAT_ANY);
12629 
12630 	entry = ctl_get_cmd_entry(ctsio, NULL);
12631 
12632 	filtered_pattern = entry->pattern & pattern;
12633 
12634 	/*
12635 	 * If the user requested specific flags in the pattern (e.g.
12636 	 * CTL_LUN_PAT_RANGE), make sure the command supports all of those
12637 	 * flags.
12638 	 *
12639 	 * If the user did not specify any flags, it doesn't matter whether
12640 	 * or not the command supports the flags.
12641 	 */
12642 	if ((filtered_pattern & ~CTL_LUN_PAT_MASK) !=
12643 	     (pattern & ~CTL_LUN_PAT_MASK))
12644 		return (CTL_LUN_PAT_NONE);
12645 
12646 	/*
12647 	 * If the user asked for a range check, see if the requested LBA
12648 	 * range overlaps with this command's LBA range.
12649 	 */
12650 	if (filtered_pattern & CTL_LUN_PAT_RANGE) {
12651 		uint64_t lba1;
12652 		uint64_t len1;
12653 		ctl_action action;
12654 		int retval;
12655 
12656 		retval = ctl_get_lba_len((union ctl_io *)ctsio, &lba1, &len1);
12657 		if (retval != 0)
12658 			return (CTL_LUN_PAT_NONE);
12659 
12660 		action = ctl_extent_check_lba(lba1, len1, desc->lba_range.lba,
12661 					      desc->lba_range.len);
12662 		/*
12663 		 * A "pass" means that the LBA ranges don't overlap, so
12664 		 * this doesn't match the user's range criteria.
12665 		 */
12666 		if (action == CTL_ACTION_PASS)
12667 			return (CTL_LUN_PAT_NONE);
12668 	}
12669 
12670 	return (filtered_pattern);
12671 }
12672 
12673 static void
12674 ctl_inject_error(struct ctl_lun *lun, union ctl_io *io)
12675 {
12676 	struct ctl_error_desc *desc, *desc2;
12677 
12678 	mtx_assert(&lun->lun_lock, MA_OWNED);
12679 
12680 	STAILQ_FOREACH_SAFE(desc, &lun->error_list, links, desc2) {
12681 		ctl_lun_error_pattern pattern;
12682 		/*
12683 		 * Check to see whether this particular command matches
12684 		 * the pattern in the descriptor.
12685 		 */
12686 		pattern = ctl_cmd_pattern_match(&io->scsiio, desc);
12687 		if ((pattern & CTL_LUN_PAT_MASK) == CTL_LUN_PAT_NONE)
12688 			continue;
12689 
12690 		switch (desc->lun_error & CTL_LUN_INJ_TYPE) {
12691 		case CTL_LUN_INJ_ABORTED:
12692 			ctl_set_aborted(&io->scsiio);
12693 			break;
12694 		case CTL_LUN_INJ_MEDIUM_ERR:
12695 			ctl_set_medium_error(&io->scsiio);
12696 			break;
12697 		case CTL_LUN_INJ_UA:
12698 			/* 29h/00h  POWER ON, RESET, OR BUS DEVICE RESET
12699 			 * OCCURRED */
12700 			ctl_set_ua(&io->scsiio, 0x29, 0x00);
12701 			break;
12702 		case CTL_LUN_INJ_CUSTOM:
12703 			/*
12704 			 * We're assuming the user knows what he is doing.
12705 			 * Just copy the sense information without doing
12706 			 * checks.
12707 			 */
12708 			bcopy(&desc->custom_sense, &io->scsiio.sense_data,
12709 			      ctl_min(sizeof(desc->custom_sense),
12710 				      sizeof(io->scsiio.sense_data)));
12711 			io->scsiio.scsi_status = SCSI_STATUS_CHECK_COND;
12712 			io->scsiio.sense_len = SSD_FULL_SIZE;
12713 			io->io_hdr.status = CTL_SCSI_ERROR | CTL_AUTOSENSE;
12714 			break;
12715 		case CTL_LUN_INJ_NONE:
12716 		default:
12717 			/*
12718 			 * If this is an error injection type we don't know
12719 			 * about, clear the continuous flag (if it is set)
12720 			 * so it will get deleted below.
12721 			 */
12722 			desc->lun_error &= ~CTL_LUN_INJ_CONTINUOUS;
12723 			break;
12724 		}
12725 		/*
12726 		 * By default, each error injection action is a one-shot
12727 		 */
12728 		if (desc->lun_error & CTL_LUN_INJ_CONTINUOUS)
12729 			continue;
12730 
12731 		STAILQ_REMOVE(&lun->error_list, desc, ctl_error_desc, links);
12732 
12733 		free(desc, M_CTL);
12734 	}
12735 }
12736 
12737 #ifdef CTL_IO_DELAY
12738 static void
12739 ctl_datamove_timer_wakeup(void *arg)
12740 {
12741 	union ctl_io *io;
12742 
12743 	io = (union ctl_io *)arg;
12744 
12745 	ctl_datamove(io);
12746 }
12747 #endif /* CTL_IO_DELAY */
12748 
12749 void
12750 ctl_datamove(union ctl_io *io)
12751 {
12752 	void (*fe_datamove)(union ctl_io *io);
12753 
12754 	mtx_assert(&control_softc->ctl_lock, MA_NOTOWNED);
12755 
12756 	CTL_DEBUG_PRINT(("ctl_datamove\n"));
12757 
12758 #ifdef CTL_TIME_IO
12759 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
12760 		char str[256];
12761 		char path_str[64];
12762 		struct sbuf sb;
12763 
12764 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
12765 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
12766 
12767 		sbuf_cat(&sb, path_str);
12768 		switch (io->io_hdr.io_type) {
12769 		case CTL_IO_SCSI:
12770 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
12771 			sbuf_printf(&sb, "\n");
12772 			sbuf_cat(&sb, path_str);
12773 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
12774 				    io->scsiio.tag_num, io->scsiio.tag_type);
12775 			break;
12776 		case CTL_IO_TASK:
12777 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
12778 				    "Tag Type: %d\n", io->taskio.task_action,
12779 				    io->taskio.tag_num, io->taskio.tag_type);
12780 			break;
12781 		default:
12782 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12783 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
12784 			break;
12785 		}
12786 		sbuf_cat(&sb, path_str);
12787 		sbuf_printf(&sb, "ctl_datamove: %jd seconds\n",
12788 			    (intmax_t)time_uptime - io->io_hdr.start_time);
12789 		sbuf_finish(&sb);
12790 		printf("%s", sbuf_data(&sb));
12791 	}
12792 #endif /* CTL_TIME_IO */
12793 
12794 #ifdef CTL_IO_DELAY
12795 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
12796 		struct ctl_lun *lun;
12797 
12798 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12799 
12800 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
12801 	} else {
12802 		struct ctl_lun *lun;
12803 
12804 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
12805 		if ((lun != NULL)
12806 		 && (lun->delay_info.datamove_delay > 0)) {
12807 			struct callout *callout;
12808 
12809 			callout = (struct callout *)&io->io_hdr.timer_bytes;
12810 			callout_init(callout, /*mpsafe*/ 1);
12811 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
12812 			callout_reset(callout,
12813 				      lun->delay_info.datamove_delay * hz,
12814 				      ctl_datamove_timer_wakeup, io);
12815 			if (lun->delay_info.datamove_type ==
12816 			    CTL_DELAY_TYPE_ONESHOT)
12817 				lun->delay_info.datamove_delay = 0;
12818 			return;
12819 		}
12820 	}
12821 #endif
12822 
12823 	/*
12824 	 * This command has been aborted.  Set the port status, so we fail
12825 	 * the data move.
12826 	 */
12827 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
12828 		printf("ctl_datamove: tag 0x%04x on (%ju:%d:%ju:%d) aborted\n",
12829 		       io->scsiio.tag_num,(uintmax_t)io->io_hdr.nexus.initid.id,
12830 		       io->io_hdr.nexus.targ_port,
12831 		       (uintmax_t)io->io_hdr.nexus.targ_target.id,
12832 		       io->io_hdr.nexus.targ_lun);
12833 		io->io_hdr.port_status = 31337;
12834 		/*
12835 		 * Note that the backend, in this case, will get the
12836 		 * callback in its context.  In other cases it may get
12837 		 * called in the frontend's interrupt thread context.
12838 		 */
12839 		io->scsiio.be_move_done(io);
12840 		return;
12841 	}
12842 
12843 	/*
12844 	 * If we're in XFER mode and this I/O is from the other shelf
12845 	 * controller, we need to send the DMA to the other side to
12846 	 * actually transfer the data to/from the host.  In serialize only
12847 	 * mode the transfer happens below CTL and ctl_datamove() is only
12848 	 * called on the machine that originally received the I/O.
12849 	 */
12850 	if ((control_softc->ha_mode == CTL_HA_MODE_XFER)
12851 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
12852 		union ctl_ha_msg msg;
12853 		uint32_t sg_entries_sent;
12854 		int do_sg_copy;
12855 		int i;
12856 
12857 		memset(&msg, 0, sizeof(msg));
12858 		msg.hdr.msg_type = CTL_MSG_DATAMOVE;
12859 		msg.hdr.original_sc = io->io_hdr.original_sc;
12860 		msg.hdr.serializing_sc = io;
12861 		msg.hdr.nexus = io->io_hdr.nexus;
12862 		msg.dt.flags = io->io_hdr.flags;
12863 		/*
12864 		 * We convert everything into a S/G list here.  We can't
12865 		 * pass by reference, only by value between controllers.
12866 		 * So we can't pass a pointer to the S/G list, only as many
12867 		 * S/G entries as we can fit in here.  If it's possible for
12868 		 * us to get more than CTL_HA_MAX_SG_ENTRIES S/G entries,
12869 		 * then we need to break this up into multiple transfers.
12870 		 */
12871 		if (io->scsiio.kern_sg_entries == 0) {
12872 			msg.dt.kern_sg_entries = 1;
12873 			/*
12874 			 * If this is in cached memory, flush the cache
12875 			 * before we send the DMA request to the other
12876 			 * controller.  We want to do this in either the
12877 			 * read or the write case.  The read case is
12878 			 * straightforward.  In the write case, we want to
12879 			 * make sure nothing is in the local cache that
12880 			 * could overwrite the DMAed data.
12881 			 */
12882 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12883 				/*
12884 				 * XXX KDM use bus_dmamap_sync() here.
12885 				 */
12886 			}
12887 
12888 			/*
12889 			 * Convert to a physical address if this is a
12890 			 * virtual address.
12891 			 */
12892 			if (io->io_hdr.flags & CTL_FLAG_BUS_ADDR) {
12893 				msg.dt.sg_list[0].addr =
12894 					io->scsiio.kern_data_ptr;
12895 			} else {
12896 				/*
12897 				 * XXX KDM use busdma here!
12898 				 */
12899 #if 0
12900 				msg.dt.sg_list[0].addr = (void *)
12901 					vtophys(io->scsiio.kern_data_ptr);
12902 #endif
12903 			}
12904 
12905 			msg.dt.sg_list[0].len = io->scsiio.kern_data_len;
12906 			do_sg_copy = 0;
12907 		} else {
12908 			struct ctl_sg_entry *sgl;
12909 
12910 			do_sg_copy = 1;
12911 			msg.dt.kern_sg_entries = io->scsiio.kern_sg_entries;
12912 			sgl = (struct ctl_sg_entry *)io->scsiio.kern_data_ptr;
12913 			if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
12914 				/*
12915 				 * XXX KDM use bus_dmamap_sync() here.
12916 				 */
12917 			}
12918 		}
12919 
12920 		msg.dt.kern_data_len = io->scsiio.kern_data_len;
12921 		msg.dt.kern_total_len = io->scsiio.kern_total_len;
12922 		msg.dt.kern_data_resid = io->scsiio.kern_data_resid;
12923 		msg.dt.kern_rel_offset = io->scsiio.kern_rel_offset;
12924 		msg.dt.sg_sequence = 0;
12925 
12926 		/*
12927 		 * Loop until we've sent all of the S/G entries.  On the
12928 		 * other end, we'll recompose these S/G entries into one
12929 		 * contiguous list before passing it to the
12930 		 */
12931 		for (sg_entries_sent = 0; sg_entries_sent <
12932 		     msg.dt.kern_sg_entries; msg.dt.sg_sequence++) {
12933 			msg.dt.cur_sg_entries = ctl_min((sizeof(msg.dt.sg_list)/
12934 				sizeof(msg.dt.sg_list[0])),
12935 				msg.dt.kern_sg_entries - sg_entries_sent);
12936 
12937 			if (do_sg_copy != 0) {
12938 				struct ctl_sg_entry *sgl;
12939 				int j;
12940 
12941 				sgl = (struct ctl_sg_entry *)
12942 					io->scsiio.kern_data_ptr;
12943 				/*
12944 				 * If this is in cached memory, flush the cache
12945 				 * before we send the DMA request to the other
12946 				 * controller.  We want to do this in either
12947 				 * the * read or the write case.  The read
12948 				 * case is straightforward.  In the write
12949 				 * case, we want to make sure nothing is
12950 				 * in the local cache that could overwrite
12951 				 * the DMAed data.
12952 				 */
12953 
12954 				for (i = sg_entries_sent, j = 0;
12955 				     i < msg.dt.cur_sg_entries; i++, j++) {
12956 					if ((io->io_hdr.flags &
12957 					     CTL_FLAG_NO_DATASYNC) == 0) {
12958 						/*
12959 						 * XXX KDM use bus_dmamap_sync()
12960 						 */
12961 					}
12962 					if ((io->io_hdr.flags &
12963 					     CTL_FLAG_BUS_ADDR) == 0) {
12964 						/*
12965 						 * XXX KDM use busdma.
12966 						 */
12967 #if 0
12968 						msg.dt.sg_list[j].addr =(void *)
12969 						       vtophys(sgl[i].addr);
12970 #endif
12971 					} else {
12972 						msg.dt.sg_list[j].addr =
12973 							sgl[i].addr;
12974 					}
12975 					msg.dt.sg_list[j].len = sgl[i].len;
12976 				}
12977 			}
12978 
12979 			sg_entries_sent += msg.dt.cur_sg_entries;
12980 			if (sg_entries_sent >= msg.dt.kern_sg_entries)
12981 				msg.dt.sg_last = 1;
12982 			else
12983 				msg.dt.sg_last = 0;
12984 
12985 			/*
12986 			 * XXX KDM drop and reacquire the lock here?
12987 			 */
12988 			if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
12989 			    sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
12990 				/*
12991 				 * XXX do something here.
12992 				 */
12993 			}
12994 
12995 			msg.dt.sent_sg_entries = sg_entries_sent;
12996 		}
12997 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
12998 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER)
12999 			ctl_failover_io(io, /*have_lock*/ 0);
13000 
13001 	} else {
13002 
13003 		/*
13004 		 * Lookup the fe_datamove() function for this particular
13005 		 * front end.
13006 		 */
13007 		fe_datamove =
13008 		    control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13009 
13010 		fe_datamove(io);
13011 	}
13012 }
13013 
13014 static void
13015 ctl_send_datamove_done(union ctl_io *io, int have_lock)
13016 {
13017 	union ctl_ha_msg msg;
13018 	int isc_status;
13019 
13020 	memset(&msg, 0, sizeof(msg));
13021 
13022 	msg.hdr.msg_type = CTL_MSG_DATAMOVE_DONE;
13023 	msg.hdr.original_sc = io;
13024 	msg.hdr.serializing_sc = io->io_hdr.serializing_sc;
13025 	msg.hdr.nexus = io->io_hdr.nexus;
13026 	msg.hdr.status = io->io_hdr.status;
13027 	msg.scsi.tag_num = io->scsiio.tag_num;
13028 	msg.scsi.tag_type = io->scsiio.tag_type;
13029 	msg.scsi.scsi_status = io->scsiio.scsi_status;
13030 	memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13031 	       sizeof(io->scsiio.sense_data));
13032 	msg.scsi.sense_len = io->scsiio.sense_len;
13033 	msg.scsi.sense_residual = io->scsiio.sense_residual;
13034 	msg.scsi.fetd_status = io->io_hdr.port_status;
13035 	msg.scsi.residual = io->scsiio.residual;
13036 	io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13037 
13038 	if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13039 		ctl_failover_io(io, /*have_lock*/ have_lock);
13040 		return;
13041 	}
13042 
13043 	isc_status = ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0);
13044 	if (isc_status > CTL_HA_STATUS_SUCCESS) {
13045 		/* XXX do something if this fails */
13046 	}
13047 
13048 }
13049 
13050 /*
13051  * The DMA to the remote side is done, now we need to tell the other side
13052  * we're done so it can continue with its data movement.
13053  */
13054 static void
13055 ctl_datamove_remote_write_cb(struct ctl_ha_dt_req *rq)
13056 {
13057 	union ctl_io *io;
13058 
13059 	io = rq->context;
13060 
13061 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13062 		printf("%s: ISC DMA write failed with error %d", __func__,
13063 		       rq->ret);
13064 		ctl_set_internal_failure(&io->scsiio,
13065 					 /*sks_valid*/ 1,
13066 					 /*retry_count*/ rq->ret);
13067 	}
13068 
13069 	ctl_dt_req_free(rq);
13070 
13071 	/*
13072 	 * In this case, we had to malloc the memory locally.  Free it.
13073 	 */
13074 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13075 		int i;
13076 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13077 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13078 	}
13079 	/*
13080 	 * The data is in local and remote memory, so now we need to send
13081 	 * status (good or back) back to the other side.
13082 	 */
13083 	ctl_send_datamove_done(io, /*have_lock*/ 0);
13084 }
13085 
13086 /*
13087  * We've moved the data from the host/controller into local memory.  Now we
13088  * need to push it over to the remote controller's memory.
13089  */
13090 static int
13091 ctl_datamove_remote_dm_write_cb(union ctl_io *io)
13092 {
13093 	int retval;
13094 
13095 	retval = 0;
13096 
13097 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_WRITE,
13098 					  ctl_datamove_remote_write_cb);
13099 
13100 	return (retval);
13101 }
13102 
13103 static void
13104 ctl_datamove_remote_write(union ctl_io *io)
13105 {
13106 	int retval;
13107 	void (*fe_datamove)(union ctl_io *io);
13108 
13109 	/*
13110 	 * - Get the data from the host/HBA into local memory.
13111 	 * - DMA memory from the local controller to the remote controller.
13112 	 * - Send status back to the remote controller.
13113 	 */
13114 
13115 	retval = ctl_datamove_remote_sgl_setup(io);
13116 	if (retval != 0)
13117 		return;
13118 
13119 	/* Switch the pointer over so the FETD knows what to do */
13120 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13121 
13122 	/*
13123 	 * Use a custom move done callback, since we need to send completion
13124 	 * back to the other controller, not to the backend on this side.
13125 	 */
13126 	io->scsiio.be_move_done = ctl_datamove_remote_dm_write_cb;
13127 
13128 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13129 
13130 	fe_datamove(io);
13131 
13132 	return;
13133 
13134 }
13135 
13136 static int
13137 ctl_datamove_remote_dm_read_cb(union ctl_io *io)
13138 {
13139 #if 0
13140 	char str[256];
13141 	char path_str[64];
13142 	struct sbuf sb;
13143 #endif
13144 
13145 	/*
13146 	 * In this case, we had to malloc the memory locally.  Free it.
13147 	 */
13148 	if ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0) {
13149 		int i;
13150 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13151 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13152 	}
13153 
13154 #if 0
13155 	scsi_path_string(io, path_str, sizeof(path_str));
13156 	sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13157 	sbuf_cat(&sb, path_str);
13158 	scsi_command_string(&io->scsiio, NULL, &sb);
13159 	sbuf_printf(&sb, "\n");
13160 	sbuf_cat(&sb, path_str);
13161 	sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13162 		    io->scsiio.tag_num, io->scsiio.tag_type);
13163 	sbuf_cat(&sb, path_str);
13164 	sbuf_printf(&sb, "%s: flags %#x, status %#x\n", __func__,
13165 		    io->io_hdr.flags, io->io_hdr.status);
13166 	sbuf_finish(&sb);
13167 	printk("%s", sbuf_data(&sb));
13168 #endif
13169 
13170 
13171 	/*
13172 	 * The read is done, now we need to send status (good or bad) back
13173 	 * to the other side.
13174 	 */
13175 	ctl_send_datamove_done(io, /*have_lock*/ 0);
13176 
13177 	return (0);
13178 }
13179 
13180 static void
13181 ctl_datamove_remote_read_cb(struct ctl_ha_dt_req *rq)
13182 {
13183 	union ctl_io *io;
13184 	void (*fe_datamove)(union ctl_io *io);
13185 
13186 	io = rq->context;
13187 
13188 	if (rq->ret != CTL_HA_STATUS_SUCCESS) {
13189 		printf("%s: ISC DMA read failed with error %d", __func__,
13190 		       rq->ret);
13191 		ctl_set_internal_failure(&io->scsiio,
13192 					 /*sks_valid*/ 1,
13193 					 /*retry_count*/ rq->ret);
13194 	}
13195 
13196 	ctl_dt_req_free(rq);
13197 
13198 	/* Switch the pointer over so the FETD knows what to do */
13199 	io->scsiio.kern_data_ptr = (uint8_t *)io->io_hdr.local_sglist;
13200 
13201 	/*
13202 	 * Use a custom move done callback, since we need to send completion
13203 	 * back to the other controller, not to the backend on this side.
13204 	 */
13205 	io->scsiio.be_move_done = ctl_datamove_remote_dm_read_cb;
13206 
13207 	/* XXX KDM add checks like the ones in ctl_datamove? */
13208 
13209 	fe_datamove = control_softc->ctl_ports[ctl_port_idx(io->io_hdr.nexus.targ_port)]->fe_datamove;
13210 
13211 	fe_datamove(io);
13212 }
13213 
13214 static int
13215 ctl_datamove_remote_sgl_setup(union ctl_io *io)
13216 {
13217 	struct ctl_sg_entry *local_sglist, *remote_sglist;
13218 	struct ctl_sg_entry *local_dma_sglist, *remote_dma_sglist;
13219 	struct ctl_softc *softc;
13220 	int retval;
13221 	int i;
13222 
13223 	retval = 0;
13224 	softc = control_softc;
13225 
13226 	local_sglist = io->io_hdr.local_sglist;
13227 	local_dma_sglist = io->io_hdr.local_dma_sglist;
13228 	remote_sglist = io->io_hdr.remote_sglist;
13229 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13230 
13231 	if (io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) {
13232 		for (i = 0; i < io->scsiio.kern_sg_entries; i++) {
13233 			local_sglist[i].len = remote_sglist[i].len;
13234 
13235 			/*
13236 			 * XXX Detect the situation where the RS-level I/O
13237 			 * redirector on the other side has already read the
13238 			 * data off of the AOR RS on this side, and
13239 			 * transferred it to remote (mirror) memory on the
13240 			 * other side.  Since we already have the data in
13241 			 * memory here, we just need to use it.
13242 			 *
13243 			 * XXX KDM this can probably be removed once we
13244 			 * get the cache device code in and take the
13245 			 * current AOR implementation out.
13246 			 */
13247 #ifdef NEEDTOPORT
13248 			if ((remote_sglist[i].addr >=
13249 			     (void *)vtophys(softc->mirr->addr))
13250 			 && (remote_sglist[i].addr <
13251 			     ((void *)vtophys(softc->mirr->addr) +
13252 			     CacheMirrorOffset))) {
13253 				local_sglist[i].addr = remote_sglist[i].addr -
13254 					CacheMirrorOffset;
13255 				if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13256 				     CTL_FLAG_DATA_IN)
13257 					io->io_hdr.flags |= CTL_FLAG_REDIR_DONE;
13258 			} else {
13259 				local_sglist[i].addr = remote_sglist[i].addr +
13260 					CacheMirrorOffset;
13261 			}
13262 #endif
13263 #if 0
13264 			printf("%s: local %p, remote %p, len %d\n",
13265 			       __func__, local_sglist[i].addr,
13266 			       remote_sglist[i].addr, local_sglist[i].len);
13267 #endif
13268 		}
13269 	} else {
13270 		uint32_t len_to_go;
13271 
13272 		/*
13273 		 * In this case, we don't have automatically allocated
13274 		 * memory for this I/O on this controller.  This typically
13275 		 * happens with internal CTL I/O -- e.g. inquiry, mode
13276 		 * sense, etc.  Anything coming from RAIDCore will have
13277 		 * a mirror area available.
13278 		 */
13279 		len_to_go = io->scsiio.kern_data_len;
13280 
13281 		/*
13282 		 * Clear the no datasync flag, we have to use malloced
13283 		 * buffers.
13284 		 */
13285 		io->io_hdr.flags &= ~CTL_FLAG_NO_DATASYNC;
13286 
13287 		/*
13288 		 * The difficult thing here is that the size of the various
13289 		 * S/G segments may be different than the size from the
13290 		 * remote controller.  That'll make it harder when DMAing
13291 		 * the data back to the other side.
13292 		 */
13293 		for (i = 0; (i < sizeof(io->io_hdr.remote_sglist) /
13294 		     sizeof(io->io_hdr.remote_sglist[0])) &&
13295 		     (len_to_go > 0); i++) {
13296 			local_sglist[i].len = ctl_min(len_to_go, 131072);
13297 			CTL_SIZE_8B(local_dma_sglist[i].len,
13298 				    local_sglist[i].len);
13299 			local_sglist[i].addr =
13300 				malloc(local_dma_sglist[i].len, M_CTL,M_WAITOK);
13301 
13302 			local_dma_sglist[i].addr = local_sglist[i].addr;
13303 
13304 			if (local_sglist[i].addr == NULL) {
13305 				int j;
13306 
13307 				printf("malloc failed for %zd bytes!",
13308 				       local_dma_sglist[i].len);
13309 				for (j = 0; j < i; j++) {
13310 					free(local_sglist[j].addr, M_CTL);
13311 				}
13312 				ctl_set_internal_failure(&io->scsiio,
13313 							 /*sks_valid*/ 1,
13314 							 /*retry_count*/ 4857);
13315 				retval = 1;
13316 				goto bailout_error;
13317 
13318 			}
13319 			/* XXX KDM do we need a sync here? */
13320 
13321 			len_to_go -= local_sglist[i].len;
13322 		}
13323 		/*
13324 		 * Reset the number of S/G entries accordingly.  The
13325 		 * original number of S/G entries is available in
13326 		 * rem_sg_entries.
13327 		 */
13328 		io->scsiio.kern_sg_entries = i;
13329 
13330 #if 0
13331 		printf("%s: kern_sg_entries = %d\n", __func__,
13332 		       io->scsiio.kern_sg_entries);
13333 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13334 			printf("%s: sg[%d] = %p, %d (DMA: %d)\n", __func__, i,
13335 			       local_sglist[i].addr, local_sglist[i].len,
13336 			       local_dma_sglist[i].len);
13337 #endif
13338 	}
13339 
13340 
13341 	return (retval);
13342 
13343 bailout_error:
13344 
13345 	ctl_send_datamove_done(io, /*have_lock*/ 0);
13346 
13347 	return (retval);
13348 }
13349 
13350 static int
13351 ctl_datamove_remote_xfer(union ctl_io *io, unsigned command,
13352 			 ctl_ha_dt_cb callback)
13353 {
13354 	struct ctl_ha_dt_req *rq;
13355 	struct ctl_sg_entry *remote_sglist, *local_sglist;
13356 	struct ctl_sg_entry *remote_dma_sglist, *local_dma_sglist;
13357 	uint32_t local_used, remote_used, total_used;
13358 	int retval;
13359 	int i, j;
13360 
13361 	retval = 0;
13362 
13363 	rq = ctl_dt_req_alloc();
13364 
13365 	/*
13366 	 * If we failed to allocate the request, and if the DMA didn't fail
13367 	 * anyway, set busy status.  This is just a resource allocation
13368 	 * failure.
13369 	 */
13370 	if ((rq == NULL)
13371 	 && ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE))
13372 		ctl_set_busy(&io->scsiio);
13373 
13374 	if ((io->io_hdr.status & CTL_STATUS_MASK) != CTL_STATUS_NONE) {
13375 
13376 		if (rq != NULL)
13377 			ctl_dt_req_free(rq);
13378 
13379 		/*
13380 		 * The data move failed.  We need to return status back
13381 		 * to the other controller.  No point in trying to DMA
13382 		 * data to the remote controller.
13383 		 */
13384 
13385 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13386 
13387 		retval = 1;
13388 
13389 		goto bailout;
13390 	}
13391 
13392 	local_sglist = io->io_hdr.local_sglist;
13393 	local_dma_sglist = io->io_hdr.local_dma_sglist;
13394 	remote_sglist = io->io_hdr.remote_sglist;
13395 	remote_dma_sglist = io->io_hdr.remote_dma_sglist;
13396 	local_used = 0;
13397 	remote_used = 0;
13398 	total_used = 0;
13399 
13400 	if (io->io_hdr.flags & CTL_FLAG_REDIR_DONE) {
13401 		rq->ret = CTL_HA_STATUS_SUCCESS;
13402 		rq->context = io;
13403 		callback(rq);
13404 		goto bailout;
13405 	}
13406 
13407 	/*
13408 	 * Pull/push the data over the wire from/to the other controller.
13409 	 * This takes into account the possibility that the local and
13410 	 * remote sglists may not be identical in terms of the size of
13411 	 * the elements and the number of elements.
13412 	 *
13413 	 * One fundamental assumption here is that the length allocated for
13414 	 * both the local and remote sglists is identical.  Otherwise, we've
13415 	 * essentially got a coding error of some sort.
13416 	 */
13417 	for (i = 0, j = 0; total_used < io->scsiio.kern_data_len; ) {
13418 		int isc_ret;
13419 		uint32_t cur_len, dma_length;
13420 		uint8_t *tmp_ptr;
13421 
13422 		rq->id = CTL_HA_DATA_CTL;
13423 		rq->command = command;
13424 		rq->context = io;
13425 
13426 		/*
13427 		 * Both pointers should be aligned.  But it is possible
13428 		 * that the allocation length is not.  They should both
13429 		 * also have enough slack left over at the end, though,
13430 		 * to round up to the next 8 byte boundary.
13431 		 */
13432 		cur_len = ctl_min(local_sglist[i].len - local_used,
13433 				  remote_sglist[j].len - remote_used);
13434 
13435 		/*
13436 		 * In this case, we have a size issue and need to decrease
13437 		 * the size, except in the case where we actually have less
13438 		 * than 8 bytes left.  In that case, we need to increase
13439 		 * the DMA length to get the last bit.
13440 		 */
13441 		if ((cur_len & 0x7) != 0) {
13442 			if (cur_len > 0x7) {
13443 				cur_len = cur_len - (cur_len & 0x7);
13444 				dma_length = cur_len;
13445 			} else {
13446 				CTL_SIZE_8B(dma_length, cur_len);
13447 			}
13448 
13449 		} else
13450 			dma_length = cur_len;
13451 
13452 		/*
13453 		 * If we had to allocate memory for this I/O, instead of using
13454 		 * the non-cached mirror memory, we'll need to flush the cache
13455 		 * before trying to DMA to the other controller.
13456 		 *
13457 		 * We could end up doing this multiple times for the same
13458 		 * segment if we have a larger local segment than remote
13459 		 * segment.  That shouldn't be an issue.
13460 		 */
13461 		if ((io->io_hdr.flags & CTL_FLAG_NO_DATASYNC) == 0) {
13462 			/*
13463 			 * XXX KDM use bus_dmamap_sync() here.
13464 			 */
13465 		}
13466 
13467 		rq->size = dma_length;
13468 
13469 		tmp_ptr = (uint8_t *)local_sglist[i].addr;
13470 		tmp_ptr += local_used;
13471 
13472 		/* Use physical addresses when talking to ISC hardware */
13473 		if ((io->io_hdr.flags & CTL_FLAG_BUS_ADDR) == 0) {
13474 			/* XXX KDM use busdma */
13475 #if 0
13476 			rq->local = vtophys(tmp_ptr);
13477 #endif
13478 		} else
13479 			rq->local = tmp_ptr;
13480 
13481 		tmp_ptr = (uint8_t *)remote_sglist[j].addr;
13482 		tmp_ptr += remote_used;
13483 		rq->remote = tmp_ptr;
13484 
13485 		rq->callback = NULL;
13486 
13487 		local_used += cur_len;
13488 		if (local_used >= local_sglist[i].len) {
13489 			i++;
13490 			local_used = 0;
13491 		}
13492 
13493 		remote_used += cur_len;
13494 		if (remote_used >= remote_sglist[j].len) {
13495 			j++;
13496 			remote_used = 0;
13497 		}
13498 		total_used += cur_len;
13499 
13500 		if (total_used >= io->scsiio.kern_data_len)
13501 			rq->callback = callback;
13502 
13503 		if ((rq->size & 0x7) != 0) {
13504 			printf("%s: warning: size %d is not on 8b boundary\n",
13505 			       __func__, rq->size);
13506 		}
13507 		if (((uintptr_t)rq->local & 0x7) != 0) {
13508 			printf("%s: warning: local %p not on 8b boundary\n",
13509 			       __func__, rq->local);
13510 		}
13511 		if (((uintptr_t)rq->remote & 0x7) != 0) {
13512 			printf("%s: warning: remote %p not on 8b boundary\n",
13513 			       __func__, rq->local);
13514 		}
13515 #if 0
13516 		printf("%s: %s: local %#x remote %#x size %d\n", __func__,
13517 		       (command == CTL_HA_DT_CMD_WRITE) ? "WRITE" : "READ",
13518 		       rq->local, rq->remote, rq->size);
13519 #endif
13520 
13521 		isc_ret = ctl_dt_single(rq);
13522 		if (isc_ret == CTL_HA_STATUS_WAIT)
13523 			continue;
13524 
13525 		if (isc_ret == CTL_HA_STATUS_DISCONNECT) {
13526 			rq->ret = CTL_HA_STATUS_SUCCESS;
13527 		} else {
13528 			rq->ret = isc_ret;
13529 		}
13530 		callback(rq);
13531 		goto bailout;
13532 	}
13533 
13534 bailout:
13535 	return (retval);
13536 
13537 }
13538 
13539 static void
13540 ctl_datamove_remote_read(union ctl_io *io)
13541 {
13542 	int retval;
13543 	int i;
13544 
13545 	/*
13546 	 * This will send an error to the other controller in the case of a
13547 	 * failure.
13548 	 */
13549 	retval = ctl_datamove_remote_sgl_setup(io);
13550 	if (retval != 0)
13551 		return;
13552 
13553 	retval = ctl_datamove_remote_xfer(io, CTL_HA_DT_CMD_READ,
13554 					  ctl_datamove_remote_read_cb);
13555 	if ((retval != 0)
13556 	 && ((io->io_hdr.flags & CTL_FLAG_AUTO_MIRROR) == 0)) {
13557 		/*
13558 		 * Make sure we free memory if there was an error..  The
13559 		 * ctl_datamove_remote_xfer() function will send the
13560 		 * datamove done message, or call the callback with an
13561 		 * error if there is a problem.
13562 		 */
13563 		for (i = 0; i < io->scsiio.kern_sg_entries; i++)
13564 			free(io->io_hdr.local_sglist[i].addr, M_CTL);
13565 	}
13566 
13567 	return;
13568 }
13569 
13570 /*
13571  * Process a datamove request from the other controller.  This is used for
13572  * XFER mode only, not SER_ONLY mode.  For writes, we DMA into local memory
13573  * first.  Once that is complete, the data gets DMAed into the remote
13574  * controller's memory.  For reads, we DMA from the remote controller's
13575  * memory into our memory first, and then move it out to the FETD.
13576  */
13577 static void
13578 ctl_datamove_remote(union ctl_io *io)
13579 {
13580 	struct ctl_softc *softc;
13581 
13582 	softc = control_softc;
13583 
13584 	mtx_assert(&softc->ctl_lock, MA_NOTOWNED);
13585 
13586 	/*
13587 	 * Note that we look for an aborted I/O here, but don't do some of
13588 	 * the other checks that ctl_datamove() normally does.
13589 	 * We don't need to run the datamove delay code, since that should
13590 	 * have been done if need be on the other controller.
13591 	 */
13592 	if (io->io_hdr.flags & CTL_FLAG_ABORT) {
13593 		printf("%s: tag 0x%04x on (%d:%d:%d:%d) aborted\n", __func__,
13594 		       io->scsiio.tag_num, io->io_hdr.nexus.initid.id,
13595 		       io->io_hdr.nexus.targ_port,
13596 		       io->io_hdr.nexus.targ_target.id,
13597 		       io->io_hdr.nexus.targ_lun);
13598 		io->io_hdr.port_status = 31338;
13599 		ctl_send_datamove_done(io, /*have_lock*/ 0);
13600 		return;
13601 	}
13602 
13603 	if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_OUT) {
13604 		ctl_datamove_remote_write(io);
13605 	} else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) == CTL_FLAG_DATA_IN){
13606 		ctl_datamove_remote_read(io);
13607 	} else {
13608 		union ctl_ha_msg msg;
13609 		struct scsi_sense_data *sense;
13610 		uint8_t sks[3];
13611 		int retry_count;
13612 
13613 		memset(&msg, 0, sizeof(msg));
13614 
13615 		msg.hdr.msg_type = CTL_MSG_BAD_JUJU;
13616 		msg.hdr.status = CTL_SCSI_ERROR;
13617 		msg.scsi.scsi_status = SCSI_STATUS_CHECK_COND;
13618 
13619 		retry_count = 4243;
13620 
13621 		sense = &msg.scsi.sense_data;
13622 		sks[0] = SSD_SCS_VALID;
13623 		sks[1] = (retry_count >> 8) & 0xff;
13624 		sks[2] = retry_count & 0xff;
13625 
13626 		/* "Internal target failure" */
13627 		scsi_set_sense_data(sense,
13628 				    /*sense_format*/ SSD_TYPE_NONE,
13629 				    /*current_error*/ 1,
13630 				    /*sense_key*/ SSD_KEY_HARDWARE_ERROR,
13631 				    /*asc*/ 0x44,
13632 				    /*ascq*/ 0x00,
13633 				    /*type*/ SSD_ELEM_SKS,
13634 				    /*size*/ sizeof(sks),
13635 				    /*data*/ sks,
13636 				    SSD_ELEM_NONE);
13637 
13638 		io->io_hdr.flags &= ~CTL_FLAG_IO_ACTIVE;
13639 		if (io->io_hdr.flags & CTL_FLAG_FAILOVER) {
13640 			ctl_failover_io(io, /*have_lock*/ 1);
13641 			return;
13642 		}
13643 
13644 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg, sizeof(msg), 0) >
13645 		    CTL_HA_STATUS_SUCCESS) {
13646 			/* XXX KDM what to do if this fails? */
13647 		}
13648 		return;
13649 	}
13650 
13651 }
13652 
13653 static int
13654 ctl_process_done(union ctl_io *io)
13655 {
13656 	struct ctl_lun *lun;
13657 	struct ctl_softc *ctl_softc;
13658 	void (*fe_done)(union ctl_io *io);
13659 	uint32_t targ_port = ctl_port_idx(io->io_hdr.nexus.targ_port);
13660 
13661 	CTL_DEBUG_PRINT(("ctl_process_done\n"));
13662 
13663 	fe_done =
13664 	    control_softc->ctl_ports[targ_port]->fe_done;
13665 
13666 #ifdef CTL_TIME_IO
13667 	if ((time_uptime - io->io_hdr.start_time) > ctl_time_io_secs) {
13668 		char str[256];
13669 		char path_str[64];
13670 		struct sbuf sb;
13671 
13672 		ctl_scsi_path_string(io, path_str, sizeof(path_str));
13673 		sbuf_new(&sb, str, sizeof(str), SBUF_FIXEDLEN);
13674 
13675 		sbuf_cat(&sb, path_str);
13676 		switch (io->io_hdr.io_type) {
13677 		case CTL_IO_SCSI:
13678 			ctl_scsi_command_string(&io->scsiio, NULL, &sb);
13679 			sbuf_printf(&sb, "\n");
13680 			sbuf_cat(&sb, path_str);
13681 			sbuf_printf(&sb, "Tag: 0x%04x, type %d\n",
13682 				    io->scsiio.tag_num, io->scsiio.tag_type);
13683 			break;
13684 		case CTL_IO_TASK:
13685 			sbuf_printf(&sb, "Task I/O type: %d, Tag: 0x%04x, "
13686 				    "Tag Type: %d\n", io->taskio.task_action,
13687 				    io->taskio.tag_num, io->taskio.tag_type);
13688 			break;
13689 		default:
13690 			printf("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13691 			panic("Invalid CTL I/O type %d\n", io->io_hdr.io_type);
13692 			break;
13693 		}
13694 		sbuf_cat(&sb, path_str);
13695 		sbuf_printf(&sb, "ctl_process_done: %jd seconds\n",
13696 			    (intmax_t)time_uptime - io->io_hdr.start_time);
13697 		sbuf_finish(&sb);
13698 		printf("%s", sbuf_data(&sb));
13699 	}
13700 #endif /* CTL_TIME_IO */
13701 
13702 	switch (io->io_hdr.io_type) {
13703 	case CTL_IO_SCSI:
13704 		break;
13705 	case CTL_IO_TASK:
13706 		if (bootverbose || verbose > 0)
13707 			ctl_io_error_print(io, NULL);
13708 		if (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)
13709 			ctl_free_io(io);
13710 		else
13711 			fe_done(io);
13712 		return (CTL_RETVAL_COMPLETE);
13713 		break;
13714 	default:
13715 		printf("ctl_process_done: invalid io type %d\n",
13716 		       io->io_hdr.io_type);
13717 		panic("ctl_process_done: invalid io type %d\n",
13718 		      io->io_hdr.io_type);
13719 		break; /* NOTREACHED */
13720 	}
13721 
13722 	lun = (struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
13723 	if (lun == NULL) {
13724 		CTL_DEBUG_PRINT(("NULL LUN for lun %d\n",
13725 				 io->io_hdr.nexus.targ_mapped_lun));
13726 		fe_done(io);
13727 		goto bailout;
13728 	}
13729 	ctl_softc = lun->ctl_softc;
13730 
13731 	mtx_lock(&lun->lun_lock);
13732 
13733 	/*
13734 	 * Check to see if we have any errors to inject here.  We only
13735 	 * inject errors for commands that don't already have errors set.
13736 	 */
13737 	if ((STAILQ_FIRST(&lun->error_list) != NULL)
13738 	 && ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS))
13739 		ctl_inject_error(lun, io);
13740 
13741 	/*
13742 	 * XXX KDM how do we treat commands that aren't completed
13743 	 * successfully?
13744 	 *
13745 	 * XXX KDM should we also track I/O latency?
13746 	 */
13747 	if ((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SUCCESS &&
13748 	    io->io_hdr.io_type == CTL_IO_SCSI) {
13749 #ifdef CTL_TIME_IO
13750 		struct bintime cur_bt;
13751 #endif
13752 		int type;
13753 
13754 		if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13755 		    CTL_FLAG_DATA_IN)
13756 			type = CTL_STATS_READ;
13757 		else if ((io->io_hdr.flags & CTL_FLAG_DATA_MASK) ==
13758 		    CTL_FLAG_DATA_OUT)
13759 			type = CTL_STATS_WRITE;
13760 		else
13761 			type = CTL_STATS_NO_IO;
13762 
13763 		lun->stats.ports[targ_port].bytes[type] +=
13764 		    io->scsiio.kern_total_len;
13765 		lun->stats.ports[targ_port].operations[type]++;
13766 #ifdef CTL_TIME_IO
13767 		bintime_add(&lun->stats.ports[targ_port].dma_time[type],
13768 		   &io->io_hdr.dma_bt);
13769 		lun->stats.ports[targ_port].num_dmas[type] +=
13770 		    io->io_hdr.num_dmas;
13771 		getbintime(&cur_bt);
13772 		bintime_sub(&cur_bt, &io->io_hdr.start_bt);
13773 		bintime_add(&lun->stats.ports[targ_port].time[type], &cur_bt);
13774 #endif
13775 	}
13776 
13777 	/*
13778 	 * Remove this from the OOA queue.
13779 	 */
13780 	TAILQ_REMOVE(&lun->ooa_queue, &io->io_hdr, ooa_links);
13781 
13782 	/*
13783 	 * Run through the blocked queue on this LUN and see if anything
13784 	 * has become unblocked, now that this transaction is done.
13785 	 */
13786 	ctl_check_blocked(lun);
13787 
13788 	/*
13789 	 * If the LUN has been invalidated, free it if there is nothing
13790 	 * left on its OOA queue.
13791 	 */
13792 	if ((lun->flags & CTL_LUN_INVALID)
13793 	 && TAILQ_EMPTY(&lun->ooa_queue)) {
13794 		mtx_unlock(&lun->lun_lock);
13795 		mtx_lock(&ctl_softc->ctl_lock);
13796 		ctl_free_lun(lun);
13797 		mtx_unlock(&ctl_softc->ctl_lock);
13798 	} else
13799 		mtx_unlock(&lun->lun_lock);
13800 
13801 	/*
13802 	 * If this command has been aborted, make sure we set the status
13803 	 * properly.  The FETD is responsible for freeing the I/O and doing
13804 	 * whatever it needs to do to clean up its state.
13805 	 */
13806 	if (io->io_hdr.flags & CTL_FLAG_ABORT)
13807 		ctl_set_task_aborted(&io->scsiio);
13808 
13809 	/*
13810 	 * We print out status for every task management command.  For SCSI
13811 	 * commands, we filter out any unit attention errors; they happen
13812 	 * on every boot, and would clutter up the log.  Note:  task
13813 	 * management commands aren't printed here, they are printed above,
13814 	 * since they should never even make it down here.
13815 	 */
13816 	switch (io->io_hdr.io_type) {
13817 	case CTL_IO_SCSI: {
13818 		int error_code, sense_key, asc, ascq;
13819 
13820 		sense_key = 0;
13821 
13822 		if (((io->io_hdr.status & CTL_STATUS_MASK) == CTL_SCSI_ERROR)
13823 		 && (io->scsiio.scsi_status == SCSI_STATUS_CHECK_COND)) {
13824 			/*
13825 			 * Since this is just for printing, no need to
13826 			 * show errors here.
13827 			 */
13828 			scsi_extract_sense_len(&io->scsiio.sense_data,
13829 					       io->scsiio.sense_len,
13830 					       &error_code,
13831 					       &sense_key,
13832 					       &asc,
13833 					       &ascq,
13834 					       /*show_errors*/ 0);
13835 		}
13836 
13837 		if (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SUCCESS)
13838 		 && (((io->io_hdr.status & CTL_STATUS_MASK) != CTL_SCSI_ERROR)
13839 		  || (io->scsiio.scsi_status != SCSI_STATUS_CHECK_COND)
13840 		  || (sense_key != SSD_KEY_UNIT_ATTENTION))) {
13841 
13842 			if ((time_uptime - ctl_softc->last_print_jiffies) <= 0){
13843 				ctl_softc->skipped_prints++;
13844 			} else {
13845 				uint32_t skipped_prints;
13846 
13847 				skipped_prints = ctl_softc->skipped_prints;
13848 
13849 				ctl_softc->skipped_prints = 0;
13850 				ctl_softc->last_print_jiffies = time_uptime;
13851 
13852 				if (skipped_prints > 0) {
13853 #ifdef NEEDTOPORT
13854 					csevent_log(CSC_CTL | CSC_SHELF_SW |
13855 					    CTL_ERROR_REPORT,
13856 					    csevent_LogType_Trace,
13857 					    csevent_Severity_Information,
13858 					    csevent_AlertLevel_Green,
13859 					    csevent_FRU_Firmware,
13860 					    csevent_FRU_Unknown,
13861 					    "High CTL error volume, %d prints "
13862 					    "skipped", skipped_prints);
13863 #endif
13864 				}
13865 				if (bootverbose || verbose > 0)
13866 					ctl_io_error_print(io, NULL);
13867 			}
13868 		}
13869 		break;
13870 	}
13871 	case CTL_IO_TASK:
13872 		if (bootverbose || verbose > 0)
13873 			ctl_io_error_print(io, NULL);
13874 		break;
13875 	default:
13876 		break;
13877 	}
13878 
13879 	/*
13880 	 * Tell the FETD or the other shelf controller we're done with this
13881 	 * command.  Note that only SCSI commands get to this point.  Task
13882 	 * management commands are completed above.
13883 	 *
13884 	 * We only send status to the other controller if we're in XFER
13885 	 * mode.  In SER_ONLY mode, the I/O is done on the controller that
13886 	 * received the I/O (from CTL's perspective), and so the status is
13887 	 * generated there.
13888 	 *
13889 	 * XXX KDM if we hold the lock here, we could cause a deadlock
13890 	 * if the frontend comes back in in this context to queue
13891 	 * something.
13892 	 */
13893 	if ((ctl_softc->ha_mode == CTL_HA_MODE_XFER)
13894 	 && (io->io_hdr.flags & CTL_FLAG_FROM_OTHER_SC)) {
13895 		union ctl_ha_msg msg;
13896 
13897 		memset(&msg, 0, sizeof(msg));
13898 		msg.hdr.msg_type = CTL_MSG_FINISH_IO;
13899 		msg.hdr.original_sc = io->io_hdr.original_sc;
13900 		msg.hdr.nexus = io->io_hdr.nexus;
13901 		msg.hdr.status = io->io_hdr.status;
13902 		msg.scsi.scsi_status = io->scsiio.scsi_status;
13903 		msg.scsi.tag_num = io->scsiio.tag_num;
13904 		msg.scsi.tag_type = io->scsiio.tag_type;
13905 		msg.scsi.sense_len = io->scsiio.sense_len;
13906 		msg.scsi.sense_residual = io->scsiio.sense_residual;
13907 		msg.scsi.residual = io->scsiio.residual;
13908 		memcpy(&msg.scsi.sense_data, &io->scsiio.sense_data,
13909 		       sizeof(io->scsiio.sense_data));
13910 		/*
13911 		 * We copy this whether or not this is an I/O-related
13912 		 * command.  Otherwise, we'd have to go and check to see
13913 		 * whether it's a read/write command, and it really isn't
13914 		 * worth it.
13915 		 */
13916 		memcpy(&msg.scsi.lbalen,
13917 		       &io->io_hdr.ctl_private[CTL_PRIV_LBA_LEN].bytes,
13918 		       sizeof(msg.scsi.lbalen));
13919 
13920 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg,
13921 				sizeof(msg), 0) > CTL_HA_STATUS_SUCCESS) {
13922 			/* XXX do something here */
13923 		}
13924 
13925 		ctl_free_io(io);
13926 	} else
13927 		fe_done(io);
13928 
13929 bailout:
13930 
13931 	return (CTL_RETVAL_COMPLETE);
13932 }
13933 
13934 #ifdef CTL_WITH_CA
13935 /*
13936  * Front end should call this if it doesn't do autosense.  When the request
13937  * sense comes back in from the initiator, we'll dequeue this and send it.
13938  */
13939 int
13940 ctl_queue_sense(union ctl_io *io)
13941 {
13942 	struct ctl_lun *lun;
13943 	struct ctl_softc *ctl_softc;
13944 	uint32_t initidx, targ_lun;
13945 
13946 	ctl_softc = control_softc;
13947 
13948 	CTL_DEBUG_PRINT(("ctl_queue_sense\n"));
13949 
13950 	/*
13951 	 * LUN lookup will likely move to the ctl_work_thread() once we
13952 	 * have our new queueing infrastructure (that doesn't put things on
13953 	 * a per-LUN queue initially).  That is so that we can handle
13954 	 * things like an INQUIRY to a LUN that we don't have enabled.  We
13955 	 * can't deal with that right now.
13956 	 */
13957 	mtx_lock(&ctl_softc->ctl_lock);
13958 
13959 	/*
13960 	 * If we don't have a LUN for this, just toss the sense
13961 	 * information.
13962 	 */
13963 	targ_lun = io->io_hdr.nexus.targ_lun;
13964 	targ_lun = ctl_map_lun(io->io_hdr.nexus.targ_port, targ_lun);
13965 	if ((targ_lun < CTL_MAX_LUNS)
13966 	 && (ctl_softc->ctl_luns[targ_lun] != NULL))
13967 		lun = ctl_softc->ctl_luns[targ_lun];
13968 	else
13969 		goto bailout;
13970 
13971 	initidx = ctl_get_initindex(&io->io_hdr.nexus);
13972 
13973 	mtx_lock(&lun->lun_lock);
13974 	/*
13975 	 * Already have CA set for this LUN...toss the sense information.
13976 	 */
13977 	if (ctl_is_set(lun->have_ca, initidx)) {
13978 		mtx_unlock(&lun->lun_lock);
13979 		goto bailout;
13980 	}
13981 
13982 	memcpy(&lun->pending_sense[initidx], &io->scsiio.sense_data,
13983 	       ctl_min(sizeof(lun->pending_sense[initidx]),
13984 	       sizeof(io->scsiio.sense_data)));
13985 	ctl_set_mask(lun->have_ca, initidx);
13986 	mtx_unlock(&lun->lun_lock);
13987 
13988 bailout:
13989 	mtx_unlock(&ctl_softc->ctl_lock);
13990 
13991 	ctl_free_io(io);
13992 
13993 	return (CTL_RETVAL_COMPLETE);
13994 }
13995 #endif
13996 
13997 /*
13998  * Primary command inlet from frontend ports.  All SCSI and task I/O
13999  * requests must go through this function.
14000  */
14001 int
14002 ctl_queue(union ctl_io *io)
14003 {
14004 	struct ctl_softc *ctl_softc;
14005 
14006 	CTL_DEBUG_PRINT(("ctl_queue cdb[0]=%02X\n", io->scsiio.cdb[0]));
14007 
14008 	ctl_softc = control_softc;
14009 
14010 #ifdef CTL_TIME_IO
14011 	io->io_hdr.start_time = time_uptime;
14012 	getbintime(&io->io_hdr.start_bt);
14013 #endif /* CTL_TIME_IO */
14014 
14015 	/* Map FE-specific LUN ID into global one. */
14016 	io->io_hdr.nexus.targ_mapped_lun =
14017 	    ctl_map_lun(io->io_hdr.nexus.targ_port, io->io_hdr.nexus.targ_lun);
14018 
14019 	switch (io->io_hdr.io_type) {
14020 	case CTL_IO_SCSI:
14021 	case CTL_IO_TASK:
14022 		ctl_enqueue_incoming(io);
14023 		break;
14024 	default:
14025 		printf("ctl_queue: unknown I/O type %d\n", io->io_hdr.io_type);
14026 		return (EINVAL);
14027 	}
14028 
14029 	return (CTL_RETVAL_COMPLETE);
14030 }
14031 
14032 #ifdef CTL_IO_DELAY
14033 static void
14034 ctl_done_timer_wakeup(void *arg)
14035 {
14036 	union ctl_io *io;
14037 
14038 	io = (union ctl_io *)arg;
14039 	ctl_done(io);
14040 }
14041 #endif /* CTL_IO_DELAY */
14042 
14043 void
14044 ctl_done(union ctl_io *io)
14045 {
14046 	struct ctl_softc *ctl_softc;
14047 
14048 	ctl_softc = control_softc;
14049 
14050 	/*
14051 	 * Enable this to catch duplicate completion issues.
14052 	 */
14053 #if 0
14054 	if (io->io_hdr.flags & CTL_FLAG_ALREADY_DONE) {
14055 		printf("%s: type %d msg %d cdb %x iptl: "
14056 		       "%d:%d:%d:%d tag 0x%04x "
14057 		       "flag %#x status %x\n",
14058 			__func__,
14059 			io->io_hdr.io_type,
14060 			io->io_hdr.msg_type,
14061 			io->scsiio.cdb[0],
14062 			io->io_hdr.nexus.initid.id,
14063 			io->io_hdr.nexus.targ_port,
14064 			io->io_hdr.nexus.targ_target.id,
14065 			io->io_hdr.nexus.targ_lun,
14066 			(io->io_hdr.io_type ==
14067 			CTL_IO_TASK) ?
14068 			io->taskio.tag_num :
14069 			io->scsiio.tag_num,
14070 		        io->io_hdr.flags,
14071 			io->io_hdr.status);
14072 	} else
14073 		io->io_hdr.flags |= CTL_FLAG_ALREADY_DONE;
14074 #endif
14075 
14076 	/*
14077 	 * This is an internal copy of an I/O, and should not go through
14078 	 * the normal done processing logic.
14079 	 */
14080 	if (io->io_hdr.flags & CTL_FLAG_INT_COPY)
14081 		return;
14082 
14083 	/*
14084 	 * We need to send a msg to the serializing shelf to finish the IO
14085 	 * as well.  We don't send a finish message to the other shelf if
14086 	 * this is a task management command.  Task management commands
14087 	 * aren't serialized in the OOA queue, but rather just executed on
14088 	 * both shelf controllers for commands that originated on that
14089 	 * controller.
14090 	 */
14091 	if ((io->io_hdr.flags & CTL_FLAG_SENT_2OTHER_SC)
14092 	 && (io->io_hdr.io_type != CTL_IO_TASK)) {
14093 		union ctl_ha_msg msg_io;
14094 
14095 		msg_io.hdr.msg_type = CTL_MSG_FINISH_IO;
14096 		msg_io.hdr.serializing_sc = io->io_hdr.serializing_sc;
14097 		if (ctl_ha_msg_send(CTL_HA_CHAN_CTL, &msg_io,
14098 		    sizeof(msg_io), 0 ) != CTL_HA_STATUS_SUCCESS) {
14099 		}
14100 		/* continue on to finish IO */
14101 	}
14102 #ifdef CTL_IO_DELAY
14103 	if (io->io_hdr.flags & CTL_FLAG_DELAY_DONE) {
14104 		struct ctl_lun *lun;
14105 
14106 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14107 
14108 		io->io_hdr.flags &= ~CTL_FLAG_DELAY_DONE;
14109 	} else {
14110 		struct ctl_lun *lun;
14111 
14112 		lun =(struct ctl_lun *)io->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14113 
14114 		if ((lun != NULL)
14115 		 && (lun->delay_info.done_delay > 0)) {
14116 			struct callout *callout;
14117 
14118 			callout = (struct callout *)&io->io_hdr.timer_bytes;
14119 			callout_init(callout, /*mpsafe*/ 1);
14120 			io->io_hdr.flags |= CTL_FLAG_DELAY_DONE;
14121 			callout_reset(callout,
14122 				      lun->delay_info.done_delay * hz,
14123 				      ctl_done_timer_wakeup, io);
14124 			if (lun->delay_info.done_type == CTL_DELAY_TYPE_ONESHOT)
14125 				lun->delay_info.done_delay = 0;
14126 			return;
14127 		}
14128 	}
14129 #endif /* CTL_IO_DELAY */
14130 
14131 	ctl_enqueue_done(io);
14132 }
14133 
14134 int
14135 ctl_isc(struct ctl_scsiio *ctsio)
14136 {
14137 	struct ctl_lun *lun;
14138 	int retval;
14139 
14140 	lun = (struct ctl_lun *)ctsio->io_hdr.ctl_private[CTL_PRIV_LUN].ptr;
14141 
14142 	CTL_DEBUG_PRINT(("ctl_isc: command: %02x\n", ctsio->cdb[0]));
14143 
14144 	CTL_DEBUG_PRINT(("ctl_isc: calling data_submit()\n"));
14145 
14146 	retval = lun->backend->data_submit((union ctl_io *)ctsio);
14147 
14148 	return (retval);
14149 }
14150 
14151 
14152 static void
14153 ctl_work_thread(void *arg)
14154 {
14155 	struct ctl_thread *thr = (struct ctl_thread *)arg;
14156 	struct ctl_softc *softc = thr->ctl_softc;
14157 	union ctl_io *io;
14158 	int retval;
14159 
14160 	CTL_DEBUG_PRINT(("ctl_work_thread starting\n"));
14161 
14162 	for (;;) {
14163 		retval = 0;
14164 
14165 		/*
14166 		 * We handle the queues in this order:
14167 		 * - ISC
14168 		 * - done queue (to free up resources, unblock other commands)
14169 		 * - RtR queue
14170 		 * - incoming queue
14171 		 *
14172 		 * If those queues are empty, we break out of the loop and
14173 		 * go to sleep.
14174 		 */
14175 		mtx_lock(&thr->queue_lock);
14176 		io = (union ctl_io *)STAILQ_FIRST(&thr->isc_queue);
14177 		if (io != NULL) {
14178 			STAILQ_REMOVE_HEAD(&thr->isc_queue, links);
14179 			mtx_unlock(&thr->queue_lock);
14180 			ctl_handle_isc(io);
14181 			continue;
14182 		}
14183 		io = (union ctl_io *)STAILQ_FIRST(&thr->done_queue);
14184 		if (io != NULL) {
14185 			STAILQ_REMOVE_HEAD(&thr->done_queue, links);
14186 			/* clear any blocked commands, call fe_done */
14187 			mtx_unlock(&thr->queue_lock);
14188 			retval = ctl_process_done(io);
14189 			continue;
14190 		}
14191 		io = (union ctl_io *)STAILQ_FIRST(&thr->incoming_queue);
14192 		if (io != NULL) {
14193 			STAILQ_REMOVE_HEAD(&thr->incoming_queue, links);
14194 			mtx_unlock(&thr->queue_lock);
14195 			if (io->io_hdr.io_type == CTL_IO_TASK)
14196 				ctl_run_task(io);
14197 			else
14198 				ctl_scsiio_precheck(softc, &io->scsiio);
14199 			continue;
14200 		}
14201 		if (!ctl_pause_rtr) {
14202 			io = (union ctl_io *)STAILQ_FIRST(&thr->rtr_queue);
14203 			if (io != NULL) {
14204 				STAILQ_REMOVE_HEAD(&thr->rtr_queue, links);
14205 				mtx_unlock(&thr->queue_lock);
14206 				retval = ctl_scsiio(&io->scsiio);
14207 				if (retval != CTL_RETVAL_COMPLETE)
14208 					CTL_DEBUG_PRINT(("ctl_scsiio failed\n"));
14209 				continue;
14210 			}
14211 		}
14212 
14213 		/* Sleep until we have something to do. */
14214 		mtx_sleep(thr, &thr->queue_lock, PDROP | PRIBIO, "-", 0);
14215 	}
14216 }
14217 
14218 static void
14219 ctl_lun_thread(void *arg)
14220 {
14221 	struct ctl_softc *softc = (struct ctl_softc *)arg;
14222 	struct ctl_be_lun *be_lun;
14223 	int retval;
14224 
14225 	CTL_DEBUG_PRINT(("ctl_lun_thread starting\n"));
14226 
14227 	for (;;) {
14228 		retval = 0;
14229 		mtx_lock(&softc->ctl_lock);
14230 		be_lun = STAILQ_FIRST(&softc->pending_lun_queue);
14231 		if (be_lun != NULL) {
14232 			STAILQ_REMOVE_HEAD(&softc->pending_lun_queue, links);
14233 			mtx_unlock(&softc->ctl_lock);
14234 			ctl_create_lun(be_lun);
14235 			continue;
14236 		}
14237 
14238 		/* Sleep until we have something to do. */
14239 		mtx_sleep(&softc->pending_lun_queue, &softc->ctl_lock,
14240 		    PDROP | PRIBIO, "-", 0);
14241 	}
14242 }
14243 
14244 static void
14245 ctl_enqueue_incoming(union ctl_io *io)
14246 {
14247 	struct ctl_softc *softc = control_softc;
14248 	struct ctl_thread *thr;
14249 	u_int idx;
14250 
14251 	idx = (io->io_hdr.nexus.targ_port * 127 +
14252 	       io->io_hdr.nexus.initid.id) % worker_threads;
14253 	thr = &softc->threads[idx];
14254 	mtx_lock(&thr->queue_lock);
14255 	STAILQ_INSERT_TAIL(&thr->incoming_queue, &io->io_hdr, links);
14256 	mtx_unlock(&thr->queue_lock);
14257 	wakeup(thr);
14258 }
14259 
14260 static void
14261 ctl_enqueue_rtr(union ctl_io *io)
14262 {
14263 	struct ctl_softc *softc = control_softc;
14264 	struct ctl_thread *thr;
14265 
14266 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14267 	mtx_lock(&thr->queue_lock);
14268 	STAILQ_INSERT_TAIL(&thr->rtr_queue, &io->io_hdr, links);
14269 	mtx_unlock(&thr->queue_lock);
14270 	wakeup(thr);
14271 }
14272 
14273 static void
14274 ctl_enqueue_done(union ctl_io *io)
14275 {
14276 	struct ctl_softc *softc = control_softc;
14277 	struct ctl_thread *thr;
14278 
14279 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14280 	mtx_lock(&thr->queue_lock);
14281 	STAILQ_INSERT_TAIL(&thr->done_queue, &io->io_hdr, links);
14282 	mtx_unlock(&thr->queue_lock);
14283 	wakeup(thr);
14284 }
14285 
14286 static void
14287 ctl_enqueue_isc(union ctl_io *io)
14288 {
14289 	struct ctl_softc *softc = control_softc;
14290 	struct ctl_thread *thr;
14291 
14292 	thr = &softc->threads[io->io_hdr.nexus.targ_mapped_lun % worker_threads];
14293 	mtx_lock(&thr->queue_lock);
14294 	STAILQ_INSERT_TAIL(&thr->isc_queue, &io->io_hdr, links);
14295 	mtx_unlock(&thr->queue_lock);
14296 	wakeup(thr);
14297 }
14298 
14299 /* Initialization and failover */
14300 
14301 void
14302 ctl_init_isc_msg(void)
14303 {
14304 	printf("CTL: Still calling this thing\n");
14305 }
14306 
14307 /*
14308  * Init component
14309  * 	Initializes component into configuration defined by bootMode
14310  *	(see hasc-sv.c)
14311  *  	returns hasc_Status:
14312  * 		OK
14313  *		ERROR - fatal error
14314  */
14315 static ctl_ha_comp_status
14316 ctl_isc_init(struct ctl_ha_component *c)
14317 {
14318 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14319 
14320 	c->status = ret;
14321 	return ret;
14322 }
14323 
14324 /* Start component
14325  * 	Starts component in state requested. If component starts successfully,
14326  *	it must set its own state to the requestrd state
14327  *	When requested state is HASC_STATE_HA, the component may refine it
14328  * 	by adding _SLAVE or _MASTER flags.
14329  *	Currently allowed state transitions are:
14330  *	UNKNOWN->HA		- initial startup
14331  *	UNKNOWN->SINGLE - initial startup when no parter detected
14332  *	HA->SINGLE		- failover
14333  * returns ctl_ha_comp_status:
14334  * 		OK	- component successfully started in requested state
14335  *		FAILED  - could not start the requested state, failover may
14336  * 			  be possible
14337  *		ERROR	- fatal error detected, no future startup possible
14338  */
14339 static ctl_ha_comp_status
14340 ctl_isc_start(struct ctl_ha_component *c, ctl_ha_state state)
14341 {
14342 	ctl_ha_comp_status ret = CTL_HA_COMP_STATUS_OK;
14343 
14344 	printf("%s: go\n", __func__);
14345 
14346 	// UNKNOWN->HA or UNKNOWN->SINGLE (bootstrap)
14347 	if (c->state == CTL_HA_STATE_UNKNOWN ) {
14348 		ctl_is_single = 0;
14349 		if (ctl_ha_msg_create(CTL_HA_CHAN_CTL, ctl_isc_event_handler)
14350 		    != CTL_HA_STATUS_SUCCESS) {
14351 			printf("ctl_isc_start: ctl_ha_msg_create failed.\n");
14352 			ret = CTL_HA_COMP_STATUS_ERROR;
14353 		}
14354 	} else if (CTL_HA_STATE_IS_HA(c->state)
14355 		&& CTL_HA_STATE_IS_SINGLE(state)){
14356 		// HA->SINGLE transition
14357 	        ctl_failover();
14358 		ctl_is_single = 1;
14359 	} else {
14360 		printf("ctl_isc_start:Invalid state transition %X->%X\n",
14361 		       c->state, state);
14362 		ret = CTL_HA_COMP_STATUS_ERROR;
14363 	}
14364 	if (CTL_HA_STATE_IS_SINGLE(state))
14365 		ctl_is_single = 1;
14366 
14367 	c->state = state;
14368 	c->status = ret;
14369 	return ret;
14370 }
14371 
14372 /*
14373  * Quiesce component
14374  * The component must clear any error conditions (set status to OK) and
14375  * prepare itself to another Start call
14376  * returns ctl_ha_comp_status:
14377  * 	OK
14378  *	ERROR
14379  */
14380 static ctl_ha_comp_status
14381 ctl_isc_quiesce(struct ctl_ha_component *c)
14382 {
14383 	int ret = CTL_HA_COMP_STATUS_OK;
14384 
14385 	ctl_pause_rtr = 1;
14386 	c->status = ret;
14387 	return ret;
14388 }
14389 
14390 struct ctl_ha_component ctl_ha_component_ctlisc =
14391 {
14392 	.name = "CTL ISC",
14393 	.state = CTL_HA_STATE_UNKNOWN,
14394 	.init = ctl_isc_init,
14395 	.start = ctl_isc_start,
14396 	.quiesce = ctl_isc_quiesce
14397 };
14398 
14399 /*
14400  *  vim: ts=8
14401  */
14402